@smartkomm/plexus-cli 0.1.353 → 0.1.354

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.
Files changed (2) hide show
  1. package/dist/cli.mjs +5 -5
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -11783,12 +11783,12 @@ The link is valid for 30 days and answers in your name. Please do not forward th
11783
11783
  - ${i.join(`
11784
11784
  - `)}`);return r}s(uh,"readMappingFile");async function Hd(e,t,n,r,i){let o=[];for(let a=0;a<t.length;a+=n)try{o.push(...await i(t.slice(a,a+n)))}catch(l){let d=a===0?"":r?` The first ${a} of ${t.length} rows were written; a re-run finds them again.`:` (after ${a} of ${t.length} rows planned; nothing was written)`;throw Lt(l,c=>`${e}: ${c}${d}`)}return o}s(Hd,"sendInBatches");var oQ=100,Cv="learning-groups apply",Dv=class extends P{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=E.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 t=uh(Cv,this.mapping,uM),n=ch(Yd(Cv,this.file),t.delimiter,this.file),{rows:r,problems:i}=fM(n,t);if(i.length>0)throw new g(`learning-groups apply: ${i.length} problems, nothing was sent:
11785
11785
  - ${i.join(`
11786
- - `)}`);let o=await this.caller(),a=this.requireTenant(o),l=await Hd(Cv,r,oQ,this.confirm,async d=>(await o.mutation(S.learningGroupImport.apply,{client:a,dryRun:!this.confirm,schoolYear:t.schoolYear,rows:d})).rows);return this.print(sQ(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 sQ(e,t){let n=s(a=>{let l=new Map;for(let[d,c]of a)l.get(d)!=="create"&&l.set(d,c);return l},"created"),r=n(e.map(a=>[a.program.key,a.program.action])),i=n(e.map(a=>[a.run.key,a.run.action])),o=s(a=>e.filter(l=>l.group.action===a).length,"count");return{mode:t?"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(sQ,"summary");var mM=[Dv];function Fv(e){return e.trim().toLowerCase()}s(Fv,"normalizeEmail");var aQ={newTaskDelayMinutes:30,reminderAfterDays:3,reminderIntervalDays:7,reminderMax:2,businessHoursOnly:!0},gM={newTaskDelayMinutes:{min:1,max:1440},reminderAfterDays:{min:1,max:30},reminderIntervalDays:{min:1,max:30},reminderMax:{min:1,max:5}},lQ=Object.keys(gM),hM=Object.keys(aQ);function yM(e){if(typeof e!="object"||e===null||Array.isArray(e))return["externalMail must be an object"];let t=[];for(let i of Object.keys(e))hM.includes(i)||t.push(`externalMail.${i} is not a setting (known: ${hM.join(", ")})`);let n=e;for(let i of lQ){let o=n[i];if(o===void 0)continue;let{min:a,max:l}=gM[i];(typeof o!="number"||!Number.isInteger(o)||o<a||o>l)&&t.push(`externalMail.${i} must be a whole number from ${a} to ${l}`)}let r=n.businessHoursOnly;return r!==void 0&&typeof r!="boolean"&&t.push("externalMail.businessHoursOnly must be true or false"),t}s(yM,"externalMailIssues");var dQ=["permanentLink","periodLink"],AEe=720*60*1e3;function wM(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.mode==="oneTimeLink"&&Object.keys(t).join(",")==="mode"}s(wM,"isExternalSignIn");function kM(e){if(typeof e!="object"||e===null)return!1;let t=e.mode;return dQ.includes(t)}s(kM,"namesRetiredExternalSignIn");function bM(e,t,n){let r=new Map,i=new Set,o=e;for(;o!==void 0;){i.has(o)&&F(`Role inheritance cycle at ${o}.`),t.has(o)||F(`Missing role ${o} in inheritance path.`),i.add(o);for(let a of n.get(o)??[]){let l=r.get(a.customFieldId);l&&ue("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=t.get(o)}return[...r.values()]}s(bM,"resolveRoleFields");var vM=new Set(["input","parties"]);function xM(e,t){let n=new Set(Array.from(e,oh));for(let i of n)(!/^[a-z][a-z0-9_]*$/.test(i)||vM.has(i))&&ue("INVALID",{de:`Ung\xFCltiger oder reservierter Feldschl\xFCssel: ${i}.`,en:`Invalid or reserved field key: ${i}.`});let r=new Set;for(let i of t){let o=oh(i);(!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(o)||vM.has(o.split(".")[0]))&&ue("INVALID",{de:`Ung\xFCltiger oder reservierter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Invalid or reserved resolver parameter key: ${i}.`}),n.has(o)&&ue("INVALID",{de:`Der Resolver-Parameter ${i} kollidiert mit einem Feldschl\xFCssel.`,en:`The resolver parameter ${i} collides with a field key.`}),r.has(o)&&ue("INVALID",{de:`Doppelter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Duplicate resolver parameter key: ${i}.`}),r.add(o)}}s(xM,"assertResolverFieldKeys");var Lv=["debtor","beneficiary","service_provider"];var SM=["stammdaten","bewerbungsmanagement","finanzen_vertraege","administration","aufgaben","notifications"],cQ={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"]}},Mv=Object.entries(cQ).flatMap(([e,t])=>Object.entries(t).flatMap(([n,r])=>r.map(i=>`${e}.${n}.${i}`))),AM=["read","write","configure"];var uQ={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 qv=Object.entries(uQ).flatMap(([e,t])=>t.map(n=>`_platform.${e}.${n}`)),fQ=qv,pQ=["_platform.feedback.assign","_platform.audit.readActor","_platform.apiTokens.manage"],DEe=fQ.filter(e=>!pQ.includes(e));function Jd(e,t){return e?.includes(t)??!1}s(Jd,"tenantHasModule");var TM=["bewerbungsmanagement.applications.submitOwn"];function RM(e){return Number.isSafeInteger(e)&&e>=1&&e<=36500}s(RM,"isRetentionDays");var jEe=m.union(m.literal("persons.firstName"),m.literal("persons.lastName"),m.literal("organizations.name"));var mQ={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 Ts(e,t=mQ[e]){return(t===void 0||t.trim()==="")&&F(`label("${e}"): no English text \u2014 pass it, or add it to ENGLISH_LABELS`),{de:e.trim(),en:t.trim()}}s(Ts,"label");var Kv=[{key:"first_name",label:Ts("Vorname","First name"),type:"string",systemColumn:"persons.firstName",partyKind:"person",required:!0},{key:"last_name",label:Ts("Nachname","Last name"),type:"string",systemColumn:"persons.lastName",partyKind:"person",required:!0},{key:"organization_name",label:Ts("Name der Organisation","Organization name"),type:"string",systemColumn:"organizations.name",partyKind:"organization",required:!0}],hQ=new Map(Kv.map(e=>[e.key,e]));function $M(e){return hQ.has(e)}s($M,"isSystemFieldKey");var jv={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 eIe=11*6e4;var tIe=30*6e4;var nIe=5*6e4;var fh="tenant",rIe=m.record(m.string(),m.string());var fi={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},gQ=m.object({storageId:m.id("_storage"),filename:fi.filename,mimeType:fi.mimeType,sizeBytes:fi.sizeBytes,sha256:m.optional(fi.sha256)}),aIe=m.object({storageId:gQ.fields.storageId,filename:fi.filename,mimeType:m.optional(fi.mimeType),sizeBytes:m.optional(fi.sizeBytes),sha256:m.optional(fi.sha256),url:m.union(m.string(),m.null())});var pIe=m.union(m.literal("de"),m.literal("en")),mIe=m.record(m.string(),m.string()),Ui=m.object({de:m.string(),en:m.string()}),hIe=m.object({value:m.string(),label:Ui,countryCode:m.optional(m.union(m.string(),m.null()))}),gIe=m.object({title:Ui,body:Ui,confirmLabel:Ui}),yIe=m.union(m.string(),Ui);function ph(e){return Ge.includes(e)}s(ph,"isSupportedLocale");var yQ=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),EM=m.object({storageId:m.string(),filename:fi.filename,uploadedAt:m.number()}),wIe=m.union(m.string(),m.number(),m.boolean(),m.null(),yQ,EM,m.array(m.string()),m.array(EM)),kIe=m.record(m.string(),m.string());var Vv=["Bewerbung","Anmeldung"];var OM=m.object({application:m.optional(m.union(...Vv.map(e=>m.literal(e))))}),SIe=m.object({application:m.union(...Vv.map(e=>m.literal(e)))}),IM={application:Vv};function Bv(e,t="tenant.terms"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[terms/shape] ${t} muss ein Objekt sein, z. B. { "application": "Anmeldung" }.`];let n=[];for(let[r,i]of Object.entries(e)){let o=IM[r];if(o===void 0){n.push(`[terms/unknownTerm] ${t}.${r} gibt es nicht. Einstellbar: ${Object.keys(IM).join(", ")}.`);continue}(typeof i!="string"||!o.includes(i))&&n.push(`[terms/unknownChoice] ${t}.${r} = ${JSON.stringify(i)} ist keine Wahl. M\xF6glich: ${o.join(", ")}.`)}return n}s(Bv,"termsFindings");var pi="recipientName",il="Name der Empf\xE4ngerin oder des Empf\xE4ngers";var Qd={de:{greeting:`Hallo {{${pi}}},`,closing:`Viele Gr\xFC\xDFe
11786
+ - `)}`);let o=await this.caller(),a=this.requireTenant(o),l=await Hd(Cv,r,oQ,this.confirm,async d=>(await o.mutation(S.learningGroupImport.apply,{client:a,dryRun:!this.confirm,schoolYear:t.schoolYear,rows:d})).rows);return this.print(sQ(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 sQ(e,t){let n=s(a=>{let l=new Map;for(let[d,c]of a)l.get(d)!=="create"&&l.set(d,c);return l},"created"),r=n(e.map(a=>[a.program.key,a.program.action])),i=n(e.map(a=>[a.run.key,a.run.action])),o=s(a=>e.filter(l=>l.group.action===a).length,"count");return{mode:t?"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(sQ,"summary");var mM=[Dv];function Fv(e){return e.trim().toLowerCase()}s(Fv,"normalizeEmail");var aQ={newTaskDelayMinutes:30,reminderAfterDays:3,reminderIntervalDays:7,reminderMax:2,businessHoursOnly:!0},gM={newTaskDelayMinutes:{min:1,max:1440},reminderAfterDays:{min:1,max:30},reminderIntervalDays:{min:1,max:30},reminderMax:{min:1,max:5}},lQ=Object.keys(gM),hM=Object.keys(aQ);function yM(e){if(typeof e!="object"||e===null||Array.isArray(e))return["externalMail must be an object"];let t=[];for(let i of Object.keys(e))hM.includes(i)||t.push(`externalMail.${i} is not a setting (known: ${hM.join(", ")})`);let n=e;for(let i of lQ){let o=n[i];if(o===void 0)continue;let{min:a,max:l}=gM[i];(typeof o!="number"||!Number.isInteger(o)||o<a||o>l)&&t.push(`externalMail.${i} must be a whole number from ${a} to ${l}`)}let r=n.businessHoursOnly;return r!==void 0&&typeof r!="boolean"&&t.push("externalMail.businessHoursOnly must be true or false"),t}s(yM,"externalMailIssues");var dQ=["permanentLink","periodLink"],AEe=720*60*1e3;function wM(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.mode==="oneTimeLink"&&Object.keys(t).join(",")==="mode"}s(wM,"isExternalSignIn");function kM(e){if(typeof e!="object"||e===null)return!1;let t=e.mode;return dQ.includes(t)}s(kM,"namesRetiredExternalSignIn");function bM(e,t,n){let r=new Map,i=new Set,o=e;for(;o!==void 0;){i.has(o)&&F(`Role inheritance cycle at ${o}.`),t.has(o)||F(`Missing role ${o} in inheritance path.`),i.add(o);for(let a of n.get(o)??[]){let l=r.get(a.customFieldId);l&&ue("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=t.get(o)}return[...r.values()]}s(bM,"resolveRoleFields");var vM=new Set(["input","parties"]);function xM(e,t){let n=new Set(Array.from(e,oh));for(let i of n)(!/^[a-z][a-z0-9_]*$/.test(i)||vM.has(i))&&ue("INVALID",{de:`Ung\xFCltiger oder reservierter Feldschl\xFCssel: ${i}.`,en:`Invalid or reserved field key: ${i}.`});let r=new Set;for(let i of t){let o=oh(i);(!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(o)||vM.has(o.split(".")[0]))&&ue("INVALID",{de:`Ung\xFCltiger oder reservierter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Invalid or reserved resolver parameter key: ${i}.`}),n.has(o)&&ue("INVALID",{de:`Der Resolver-Parameter ${i} kollidiert mit einem Feldschl\xFCssel.`,en:`The resolver parameter ${i} collides with a field key.`}),r.has(o)&&ue("INVALID",{de:`Doppelter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Duplicate resolver parameter key: ${i}.`}),r.add(o)}}s(xM,"assertResolverFieldKeys");var Lv=["debtor","beneficiary","service_provider"];var SM=["stammdaten","bewerbungsmanagement","finanzen_vertraege","administration","aufgaben","notifications"],cQ={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"]}},Mv=Object.entries(cQ).flatMap(([e,t])=>Object.entries(t).flatMap(([n,r])=>r.map(i=>`${e}.${n}.${i}`))),AM=["read","write","configure"];var uQ={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 qv=Object.entries(uQ).flatMap(([e,t])=>t.map(n=>`_platform.${e}.${n}`)),fQ=qv,pQ=["_platform.feedback.assign","_platform.audit.readActor","_platform.apiTokens.manage"],DEe=fQ.filter(e=>!pQ.includes(e));function Jd(e,t){return e?.includes(t)??!1}s(Jd,"tenantHasModule");var TM=["bewerbungsmanagement.applications.submitOwn"];function RM(e){return Number.isSafeInteger(e)&&e>=1&&e<=36500}s(RM,"isRetentionDays");var jEe=m.union(m.literal("persons.firstName"),m.literal("persons.lastName"),m.literal("organizations.name"));var mQ={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 Ts(e,t=mQ[e]){return(t===void 0||t.trim()==="")&&F(`label("${e}"): no English text \u2014 pass it, or add it to ENGLISH_LABELS`),{de:e.trim(),en:t.trim()}}s(Ts,"label");var Kv=[{key:"first_name",label:Ts("Vorname","First name"),type:"string",systemColumn:"persons.firstName",partyKind:"person",required:!0},{key:"last_name",label:Ts("Nachname","Last name"),type:"string",systemColumn:"persons.lastName",partyKind:"person",required:!0},{key:"organization_name",label:Ts("Name der Organisation","Organization name"),type:"string",systemColumn:"organizations.name",partyKind:"organization",required:!0}],hQ=new Map(Kv.map(e=>[e.key,e]));function $M(e){return hQ.has(e)}s($M,"isSystemFieldKey");var jv={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 eIe=11*6e4;var tIe=30*6e4;var nIe=5*6e4;var fh="tenant",rIe=m.record(m.string(),m.string());var fi={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},gQ=m.object({storageId:m.id("_storage"),filename:fi.filename,mimeType:fi.mimeType,sizeBytes:fi.sizeBytes,sha256:m.optional(fi.sha256)}),aIe=m.object({storageId:gQ.fields.storageId,filename:fi.filename,mimeType:m.optional(fi.mimeType),sizeBytes:m.optional(fi.sizeBytes),sha256:m.optional(fi.sha256),url:m.union(m.string(),m.null())});var pIe=m.union(m.literal("de"),m.literal("en")),mIe=m.record(m.string(),m.string()),Ui=m.object({de:m.string(),en:m.string()}),hIe=m.object({value:m.string(),label:Ui,countryCode:m.optional(m.union(m.string(),m.null()))}),gIe=m.object({title:Ui,body:Ui,confirmLabel:Ui}),yIe=m.union(m.string(),Ui);function ph(e){return Ge.includes(e)}s(ph,"isSupportedLocale");var yQ=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),EM=m.object({storageId:m.string(),filename:fi.filename,uploadedAt:m.number()}),wIe=m.union(m.string(),m.number(),m.boolean(),m.null(),yQ,EM,m.array(m.string()),m.array(EM)),kIe=m.record(m.string(),m.string()),bIe=m.union(m.object({filterKey:m.string(),optionKeys:m.array(m.string())}),m.object({filterKey:m.string(),text:m.string()}),m.object({filterKey:m.string(),min:m.optional(m.number()),max:m.optional(m.number())}));var Vv=["Bewerbung","Anmeldung"];var OM=m.object({application:m.optional(m.union(...Vv.map(e=>m.literal(e))))}),AIe=m.object({application:m.union(...Vv.map(e=>m.literal(e)))}),IM={application:Vv};function Bv(e,t="tenant.terms"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[terms/shape] ${t} muss ein Objekt sein, z. B. { "application": "Anmeldung" }.`];let n=[];for(let[r,i]of Object.entries(e)){let o=IM[r];if(o===void 0){n.push(`[terms/unknownTerm] ${t}.${r} gibt es nicht. Einstellbar: ${Object.keys(IM).join(", ")}.`);continue}(typeof i!="string"||!o.includes(i))&&n.push(`[terms/unknownChoice] ${t}.${r} = ${JSON.stringify(i)} ist keine Wahl. M\xF6glich: ${o.join(", ")}.`)}return n}s(Bv,"termsFindings");var pi="recipientName",il="Name der Empf\xE4ngerin oder des Empf\xE4ngers";var Qd={de:{greeting:`Hallo {{${pi}}},`,closing:`Viele Gr\xFC\xDFe
11787
11787
  Ihr Aufnahme-Team`,noReplyNote:"Diese E-Mail wurde automatisch versandt. Bitte antworten Sie nicht auf diese Nachricht."},en:{greeting:`Hello {{${pi}}},`,closing:`Kind regards
11788
11788
  The admissions team`,noReplyNote:"This e-mail was sent automatically. Please do not reply to it."}},wQ={de:{...Qd.de,closing:`Viele Gr\xFC\xDFe
11789
11789
  Ihr Plexus-Team`},en:{...Qd.en,closing:`Kind regards
11790
11790
  The Plexus team`}},kQ={de:{...Qd.de,closing:null},en:{...Qd.en,closing:null}};var bQ=/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g,Rs=2e3;function mh(e){let t=[];for(let n of e.matchAll(bQ)){let r=n[1];t.includes(r)||t.push(r)}return t}s(mh,"placeholdersIn");function _M(e){return e.slots??[]}s(_M,"slotsOf");function vQ(e){return e.bodyVariants!==void 0?e.bodyVariants:[_M(e).filter(t=>t.key!==xd).map(t=>t.key)]}s(vQ,"bodyVariantsOf");var xQ=/:\/\/|www\.|mailto:/i;function SQ(e,t){let n=`{{${t}}}`,r=0;for(;;){let i=e.indexOf(n,r);if(i===-1)return!1;let o=i===0?"":e[i-1],a=e[i+n.length]??"";if(o!==""&&!/\s/.test(o)||a!==""&&!/[\s.,;:!?)]/.test(a))return!0;r=i+n.length}}s(SQ,"linkGlued");function AQ(e,t){let n=e.default[t];return(typeof n!="string"||n.length===0)&&F(`notifications: slot "${e.key}" has no "${t}" text`),n}s(AQ,"defaultText");function NM(e,t,n){let r=[],i=_M(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(t)){let h=i.find(y=>y.key===u);if(h===void 0){r.push({slotKey:u,code:"unknownSlot",message:i.length===0?{de:`Die Benachrichtigung \u201E${e.label}\u201C l\xE4sst sich nicht anpassen.`,en:`The notification "${e.label}" cannot be customized.`}:{de:`Der Baustein \u201E${u}\u201C geh\xF6rt nicht zur Benachrichtigung \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>Rs){r.push({slotKey:u,code:"tooLong",message:{de:`\u201E${h.label}\u201C ist ${p.length} Zeichen lang, erlaubt sind ${Rs}.`,en:`"${h.label}" is ${p.length} characters long; the limit is ${Rs}.`}});continue}if(DC(e)){xQ.test(p)&&r.push({slotKey:u,code:"foreignUrl",message:{de:`\u201E${h.label}\u201C enth\xE4lt eine Adresse. Die Benachrichtigung \u201E${e.label}\u201C tr\xE4gt einen Anmeldeschl\xFCssel und darf keine weiteren Links enthalten.`,en:`"${h.label}" contains an address. The notification "${e.label}" carries a sign-in key and must not contain any further links.`}});for(let y of o)y.link!==!0||!SQ(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 mh(p)){if(!a.includes(y)){r.push({slotKey:u,code:"unknownPlaceholder",message:y===pi?{de:`\u201E{{${pi}}}\u201C (${il}) geh\xF6rt in die Anrede der Schule (unter \u201EAnrede und Gru\xDFformel\u201C), nicht in \u201E${h.label}\u201C \u2014 dort gibt es eine neutrale Anrede, wenn kein Name bekannt ist.`,en:`"{{${pi}}}" (${il}) belongs in the school's greeting (under \u201CGreeting and sign-off\u201D), not in "${h.label}" \u2014 the greeting has a neutral form for when no name is known.`}:a.length===0?{de:`Die Benachrichtigung \u201E${e.label}\u201C kennt keine Platzhalter, \u201E{{${y}}}\u201C bliebe unersetzt stehen.`,en:`The notification "${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(k=>`{{${k}}}`).join(", ")}.`,en:`"{{${y}}}" does not exist in "${e.label}". Allowed: ${a.map(k=>`{{${k}}}`).join(", ")}.`}});continue}if(u!==xd||l.includes(y))continue;let b=o.find(k=>k.key===y)?.label??y;r.push({slotKey:u,code:"subjectUnsupported",message:{de:`\u201E{{${y}}}\u201C (${b}) l\xE4sst sich im Betreff nicht einsetzen \u2014 der Wert entsteht erst beim Versand. `+(l.length===0?"In dieser Benachrichtigung kann der Betreff keine Platzhalter tragen.":`Im Betreff m\xF6glich: ${l.map(k=>`{{${k}}}`).join(", ")}.`),en:`"{{${y}}}" (${b}) 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(k=>`{{${k}}}`).join(", ")}.`)}})}}let d=s(u=>t[u]??TQ(i,u,n),"textOf"),c=vQ(e);for(let u of o){if(u.required!==!0)continue;let p=c.filter(k=>!mh(k.map(d).join(`
11791
- `)).includes(u.key));if(p.length===0)continue;let h=s((k,v)=>k.map(A=>v(i.find(T=>T.key===A)?.label??A)).join(" + "),"variantLabel"),y=c.length===1?"":` Er fehlt in der Fassung aus ${p.map(k=>h(k,v=>`\u201E${v}\u201C`)).join(" und in der aus ")}.`,b=c.length===1?"":` It is missing in the version made of ${p.map(k=>h(k,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 die Benachrichtigung \u201E${e.label}\u201C nicht \u2014 der Platzhalter muss im Text stehen, nicht nur im Betreff.`+y,en:`Without "{{${u.key}}}" (${u.label}) the notification "${e.label}" does not work \u2014 the placeholder must be in the text, not only in the subject.`+b}})}return r}s(NM,"validateOverride");function TQ(e,t,n){let r=e.find(i=>i.key===t);return r===void 0?"":AQ(r,n)}s(TQ,"defaultTextOf");function Uv(e){let t=e?.trim();return t===void 0||t.length===0?void 0:t}s(Uv,"normalizeChromeText");var $s=s(e=>String.fromCharCode(e),"cp"),RQ=new RegExp(`[${$s(0)}-${$s(31)}${$s(127)}]`,"g"),$Q=new RegExp(`[${$s(8234)}-${$s(8238)}${$s(8294)}-${$s(8297)}]`,"g");var EQ=200;function IQ(e,t=EQ){return e.replace(RQ," ").replace($Q,"").replace(/\s+/g," ").trim().slice(0,t)}s(IQ,"sanitizeHeaderValue");function hh(e){return IQ(e.replace(/["<>@]/g,""),100)}s(hh,"sanitizeDisplayName");var Gv={de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}},OQ={greeting:{de:"Anrede",en:"Greeting"},closing:{de:"Gru\xDFformel",en:"Closing"}};function PM(e){let t=[],n=[];for(let i of["greeting","closing"]){let o=e[i];if(o===void 0)continue;let a=OQ[i],l=Ft(o);l!=="not-localized"&&l.length>0&&l.length<Ge.length&&n.push({de:`${a.de} fehlt auf ${l.map(d=>Gv[d].de).join(" und ")}`,en:`${a.en} is missing in ${l.map(d=>Gv[d].en).join(" and ")}`});for(let d of Ge){let c=Uk(h=>`${a[h]} (${Gv[d][h]})`),u=Uv(o[d]);u!==void 0&&u.length>Rs&&t.push({de:`${c.de} hat ${u.length} Zeichen \u2014 h\xF6chstens ${Rs}; Anrede und Gru\xDFformel sind je eine Zeile der Mail, kein Dokument.`,en:`${c.en} has ${u.length} characters \u2014 at most ${Rs}; the greeting and the sign-off are one line of the mail each, not a document.`});let p=i==="greeting"?[pi]:[];for(let h of mh(u??""))p.includes(h)||t.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: {{${pi}}} (${il}).`,en:`"{{${h}}}" does not exist in the ${c.en}. Allowed: {{${pi}}} (${il}).`})}}n.length>0&&t.unshift({de:`[notification/chromeMissingTranslation] ${n.map(i=>i.de).join("; ")} \u2014 Anrede und Gru\xDFformel gelten f\xFCr jede Benachrichtigung, in jeder Sprache.`,en:`[notification/chromeMissingTranslation] ${n.map(i=>i.en).join("; ")} \u2014 the greeting and sign-off apply to every notification, in every language.`});let r=Uv(e.senderName);return r!==void 0&&hh(r)!==r&&t.push({de:`Absendername (senderName) \u201E${r}\u201C \xFCbersteht die Kopfzeile der Mail nicht unver\xE4ndert \u2014 er ginge als \u201E${hh(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 "${hh(r)}". No quotation marks, angle brackets, "@" or control characters.`}),t}s(PM,"chromeFindings");var Zd=["application/pdf","image/jpeg","image/png","image/webp"];var gh=["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"],CM={docRef:{maxBytes:25*1048576,allowedMime:Zd},partyFile:{maxBytes:25*1048576,allowedMime:Zd},import:{maxBytes:500*1048576,allowedMime:null},signedContract:{maxBytes:25*1048576,allowedMime:Zd},artifactVersion:{maxBytes:25*1048576,allowedMime:Zd},chatAttachment:{maxBytes:25*1048576,allowedMime:Zd},tenantFile:{maxBytes:20*1048576,allowedMime:gh},documentTemplate:{maxBytes:25*1048576,allowedMime:null}};function DM(e){let t=atob(e),n="";for(let r=0;r<t.length;r++)n+=t.charCodeAt(r).toString(16).padStart(2,"0");return n}s(DM,"sha256Base64ToHex");var FM=m.object({family:m.string()}),LM=m.object({family:m.string(),url:m.optional(m.string())}),pOe=m.object({heading:m.optional(LM),body:m.optional(LM)}),_Q=m.union(m.literal("sharp"),m.literal("rounded"),m.literal("soft")),NQ=m.union(m.literal("light"),m.literal("dark")),PQ=m.union(m.literal("sm"),m.literal("md"),m.literal("lg"),m.literal("max")),CQ=m.union(m.literal("compact"),m.literal("normal"),m.literal("spacious")),DQ=m.object({primary:m.optional(m.string()),accent:m.optional(m.string()),background:m.optional(m.string()),foreground:m.optional(m.string())}),FQ=m.object({heading:m.optional(FM),body:m.optional(FM)}),mOe=m.object({colors:m.optional(DQ),radius:m.optional(_Q),logoSize:m.optional(PQ),bannerDensity:m.optional(CQ),logoGround:m.optional(NQ),filledHeader:m.optional(m.boolean()),websiteUrl:m.optional(m.string()),fonts:m.optional(FQ)}),hOe=m.object({primaryUrl:m.union(m.null(),m.string())}),gOe=m.literal("primary"),yOe=m.object({headingUrl:m.union(m.null(),m.string()),bodyUrl:m.union(m.null(),m.string())}),wOe=m.union(m.literal("heading"),m.literal("body")),yh=["logo","fontHeading","fontBody"],MM={logo:null,fontHeading:"heading",fontBody:"body"};function qM(e){let{contentType:t,size:n}=e;return t==null||!t.startsWith("image/")?{de:`Das Logo muss ein Bild sein (erhalten: \u201E${t??"unbekannt"}\u201C).`,en:`The logo must be an image (received: "${t??"unknown"}").`}:t.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."}:n>3e6?{de:`Das Logo ist zu gro\xDF (${n} Byte, h\xF6chstens 3000000 Byte).`,en:`The logo is too large (${n} bytes, at most 3000000 bytes).`}:null}s(qM,"logoFileProblem");var zv="font/woff2";var LQ=["Inter Variable","Azeret Mono Variable","Source Sans 3 Variable"];function KM(e){return e?.trim()?LQ.some(t=>t.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(KM,"fontFamilyProblem");var MQ=["approved","rejected","withdrawn","waitlist","expired"];var wh=["admitted","rejected","withdrawn","waitlist","expired","unknown"],TOe=m.union(...MQ.map(e=>m.literal(e))),ROe=m.union(...wh.map(e=>m.literal(e))),qQ=["approved","rejected","waitlist"],KQ=["withdrawn","expired"],jQ=m.union(...qQ.map(e=>m.literal(e))),VQ=m.union(...KQ.map(e=>m.literal(e))),$Oe={active:{status:m.literal("active")},completed:{status:m.literal("completed"),outcome:jQ,endedAt:m.number()},aborted:{status:m.literal("aborted"),outcome:m.optional(VQ),endedAt:m.number()}};var jM=30,VM=3650;var BQ=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())}),POe=BQ.fields,UQ=s(e=>wh.includes(e),"isClassification");function BM(e,t="tenant.retentionDays"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[retention/shape] ${t} must be an object of days per classification (got ${JSON.stringify(e)}).`];let n=[];for(let[r,i]of Object.entries(e)){if(!UQ(r)){n.push(`[retention/unknownClassification] ${t}.${r} is no retention classification \u2014 one of ${wh.join(", ")}.`);continue}(typeof i!="number"||!Number.isSafeInteger(i)||i<jM||i>VM)&&n.push(`[retention/days] ${t}.${r} must be a whole number of days from ${jM} to ${VM} (got ${JSON.stringify(i)}).`)}return n}s(BM,"retentionDaysFindings");var GQ=["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"],zQ=new Set(GQ);function kh(e){return zQ.has(e)}s(kh,"isCountryCode");var Wv=["off","always","deviating"],UM={mode:"deviating",defaultCountryCode:"de"};function GM(e,t){return[["programKey",e.programKey],["runKey",e.runKey],["learningGroupKey",e.learningGroupKey]].filter(([,n])=>n!==void 0&&n.trim().length===0).map(([n])=>`Search filter option "${t}" has an empty enrollment ${n}.`)}s(GM,"enrollmentPredicateShapeErrors");var WQ=["street","plz","ort"];function YQ(e){return WQ.filter(t=>!e.has(t))}s(YQ,"missingInvoiceAddressParts");var HQ=new Set(["0-1-select","0-n-select"]);function zM(e){return e===void 0?null:new Set(e.properties.flatMap(t=>t.addressPart!==void 0&&AP(t.addressPart)?[t.addressPart]:[]))}s(zM,"declaredAddressParts");function JQ(e){return HQ.has(e)}s(JQ,"isSelectFieldKind");function WM(e){let t=[];for(let o of e)if(o.isNationality&&(JQ(o.kind)?o.listKind!=="country"&&t.push({code:"nationality/notCountryList",fieldKey:o.key}):t.push({code:"nationality/wrongFieldKind",fieldKey:o.key})),o.isAccountEmail&&o.kind!=="email"&&t.push({code:"accountEmail/wrongFieldKind",fieldKey:o.key}),o.isContactPhone&&o.kind!=="tel"&&t.push({code:"contactPhone/wrongFieldKind",fieldKey:o.key}),o.isInvoiceAddress)if(o.addressParts===null)t.push({code:"invoiceAddress/wrongFieldKind",fieldKey:o.key});else{let a=YQ(o.addressParts);a.length>0&&t.push({code:"invoiceAddress/missingPart",fieldKey:o.key,parts:a})}let n=e.filter(o=>o.isAccountEmail);if(n.length>1)for(let o of n)t.push({code:"accountEmail/multiple",fieldKey:o.key});let r=e.filter(o=>o.isContactPhone);if(r.length>1)for(let o of r)t.push({code:"contactPhone/multiple",fieldKey:o.key});let i=e.filter(o=>o.isInvoiceAddress);if(i.length>1)for(let o of i)t.push({code:"invoiceAddress/multiple",fieldKey:o.key});return t}s(WM,"fieldRoleFindings");function YM(e,t,...n){let r=e[t.code];return r(t,...n)}s(YM,"wordListElementFinding");function HM(e,t){let n=[];for(let r of t){if(e.kind==="plain"){r.countryCode!==void 0&&n.push({code:"list/countryCodeOnPlain",elementKey:r.key,countryCode:r.countryCode});continue}r.countryCode===void 0?n.push({code:"list/countryCodeMissing",elementKey:r.key}):r.countryCode!==null&&!kh(r.countryCode)&&n.push({code:"list/unknownCountryCode",elementKey:r.key,countryCode:r.countryCode})}return n}s(HM,"listElementCountryFindings");var ZQ={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},XQ={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,externalMail:!0,testMailRecipients:!0,magicLinkLogin:!0,externalSignIn:!0,nationalityFlag:!0,adminSeesSignatureImages:!0,signatureStamp:!0,bankImportScope:!0,branding:!0,brandingAssets:!0,partyRetention:!0},e8=new Set(["enabledMailCategories","mailEnabled"]);function t8(e){let t=s((n,r,i)=>n.filter(o=>!Object.hasOwn(r,o)&&!(i==="tenant."&&e8.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[...t(Object.keys(e),ZQ,""),...t(Object.keys(e.tenant),XQ,"tenant.")]}s(t8,"unknownKeyFindings");var JM=["plain","country"],n8={"list/countryCodeMissing":s(({elementKey:e},t)=>`Element "${t}.${e}" of a country list must state countryCode (null for no state).`,"list/countryCodeMissing"),"list/countryCodeOnPlain":s(({elementKey:e},t)=>`Element "${t}.${e}" carries countryCode, but list "${t}" is not kind "country".`,"list/countryCodeOnPlain"),"list/unknownCountryCode":s(({elementKey:e,countryCode:t},n)=>`Element "${n}.${e}" has unknown countryCode ${JSON.stringify(t)}.`,"list/unknownCountryCode")},r8={"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:t})=>`Field "${e}" is isInvoiceAddress but declares no property for the address part(s) ${t.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 i8(e){let t=r8[e.code];return t(e)}s(i8,"roleText");function o8(e){let t=[],n=e.tenant.nationalityFlag,r=typeof n=="object"&&n!==null?n:{},i=r.mode;if(Wv.includes(i)||t.push(`[nationality/flagMode] tenant.nationalityFlag.mode must be one of ${Wv.join(", ")} (got ${n===void 0?"no tenant.nationalityFlag":JSON.stringify(i??null)}).`),n!==void 0){let l=r.defaultCountryCode;(typeof l!="string"||!kh(l))&&t.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(!JM.includes(d)){t.push(`[list/kind] List "${l.key}" has kind ${JSON.stringify(d??null)} \u2014 one of ${JM.join(", ")}.`);continue}o.set(l.key,l.kind);for(let c of HM({key:l.key,kind:l.kind},l.elements))t.push(`[${c.code}] ${YM(n8,c,l.key)}`)}let a=WM(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"?zM(l.objectSchema??{properties:[]}):null})));for(let l of a)t.push(`[${l.code}] ${i8(l)}`);return t}s(o8,"nationalityFindings");function QM(e){return ar(e)?.message.de??(e instanceof Error?e.message:String(e))}s(QM,"errorText");function eq(e,t={}){let n=[...t8(e)],r=[];e.source!==void 0&&n.push(...h8(e.source,e.foundation.units));try{xM(e.fields.map(x=>x.key),[])}catch(x){n.push(QM(x))}e.tenant.terms!==void 0&&n.push(...Bv(e.tenant.terms)),e.tenant.retentionDays!==void 0&&n.push(...BM(e.tenant.retentionDays)),AD(e.tenant.mailLevel)?e.tenant.mailLevel==="all"&&!Jd(e.tenant.enabledModules,"notifications")&&n.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".'):n.push(`[notification/mailLevel] tenant.mailLevel must be one of ${rb.join(", ")} (got ${e.tenant.mailLevel===void 0?"nothing":JSON.stringify(e.tenant.mailLevel)}).`);let i=e.tenant.testMailRecipients;i!==void 0&&(!Array.isArray(i)||i.length===0||!i.every(x=>typeof x=="string"&&Fv(x).includes("@"))?n.push("[notification/testRecipients] tenant.testMailRecipients must be a non-empty list of login addresses (leave it out for no test recipients)."):new Set(i.map(x=>Fv(x))).size!==i.length&&n.push("[notification/testRecipients] tenant.testMailRecipients names an address twice."),(e.tenant.mailLevel!=="loginOnly"||!Jd(e.tenant.enabledModules,"notifications"))&&n.push('[notification/testRecipientsWithoutEffect] tenant.testMailRecipients decides only at mailLevel "loginOnly" with the notifications module on \u2014 at "all" everybody gets mail, with the module off nobody. Remove the list or change the level.')),"enabledMailCategories"in e.tenant&&n.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&&n.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).'),Rt(e.displayGroups.map(x=>x.key),"display group",n),Rt(e.lists.map(x=>x.key),"list",n),Rt(e.roles.map(x=>x.key),"role",n),Rt(e.fields.map(x=>x.key),"field",n),Rt(e.foundation.legalEntities.map(x=>x.key),"legal entity",n),Rt(e.foundation.units.map(x=>x.key),"unit",n),Rt(e.foundation.permissionGroups.map(x=>x.key),"permission group",n),"teams"in e.foundation&&n.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 x of e.foundation.users)"teamKeys"in x&&n.push(`User "${x.email}" carries teamKeys, retired: team membership is the user's permission-group membership.`);if(Rt(e.foundation.users.map(x=>x.key),"user",n),Rt((e.searchFilters??[]).map(x=>x.key),"search filter",n),Rt((e.searchTargets??[]).map(x=>x.objectPropertyKey===void 0?x.fieldKey:`${x.fieldKey}.${x.objectPropertyKey}`),"search target",n),Rt((e.partyResultIcons??[]).map(x=>x.key),"party result icon",n),Rt((e.templatePlaceholders??[]).map(x=>x.key),"template placeholder",n),Rt((e.notificationLetters??[]).map(tq),"notification letter",n),p8(e.notificationLetters??[],n),m8(e.tenant.notificationChrome,n),e.tenant.bankImportScope!==void 0&&!["sepa_only","full_statement"].includes(e.tenant.bankImportScope)&&n.push("tenant.bankImportScope must be sepa_only or full_statement."),e.tenant.hideMailLevelNotice!==void 0&&typeof e.tenant.hideMailLevelNotice!="boolean"&&n.push("tenant.hideMailLevelNotice must be true or false (the dashboard's mail-level notice)."),e.tenant.unassignedTaskNoticeDays!==void 0&&!ND(e.tenant.unassignedTaskNoticeDays)&&n.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."),e.tenant.externalMail!==void 0)for(let x of yM(e.tenant.externalMail))n.push(`tenant.${x}; leave it out for the platform default.`);typeof e.tenant.magicLinkLogin!="boolean"&&n.push("tenant.magicLinkLogin must be true or false (the login page's sign-in link option)."),typeof e.tenant.adminSeesSignatureImages!="boolean"&&n.push("tenant.adminSeesSignatureImages must be true or false (whether a school administrator sees other accounts' signature images)."),typeof e.tenant.signatureStamp!="boolean"&&n.push("tenant.signatureStamp must be true or false (whether the school offers the signature stamp at the countersignature)."),kM(e.tenant.externalSignIn)?n.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" }.`):wM(e.tenant.externalSignIn)||n.push('[auth/externalSignIn] tenant.externalSignIn must be { mode: "oneTimeLink" } (how families sign in).');let o=new Set(e.displayGroups.map(x=>x.key)),a=new Set(e.lists.map(x=>x.key)),l=new Set(e.roles.map(x=>x.key)),d=new Set(e.fields.map(x=>x.key)),c=new Map(e.fields.map(x=>[x.key,x])),u=new Set(e.foundation.legalEntities.map(x=>x.key)),p=new Set(e.foundation.units.map(x=>x.key)),h=new Set(e.foundation.permissionGroups.map(x=>x.key));Jd(e.tenant.enabledModules,"bewerbungsmanagement")&&e.tenant.defaultApplicantGroupKey!==void 0&&(e.foundation.permissionGroups.find(D=>D.key===e.tenant.defaultApplicantGroupKey)?.permissions.includes("bewerbungsmanagement.applications.submitOwn")||n.push(`Default applicant group "${e.tenant.defaultApplicantGroupKey}" must grant submitOwn.`));let y=e.tenant.admissionFieldDisplayGroupKey;y!==void 0&&!o.has(y)&&n.push(`tenant.admissionFieldDisplayGroupKey "${y}" names no display group of this config.`),y===void 0&&(Jd(e.tenant.enabledModules,"bewerbungsmanagement")||(e.admission?.fields.length??0)>0)&&n.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."),n.push(...o8(e)),Rt(e.fields.flatMap(x=>(x.relationshipKinds??[]).map(D=>D.key)),"relationship kind",n);for(let x of e.fields){o.has(x.displayGroupKey)||n.push(`Field "${x.key}" references missing display group "${x.displayGroupKey}".`),a8(x,n),x.formWritable===!0&&!jv[x.type].fieldMapTarget&&n.push(`Field "${x.key}" is formWritable, but a form cannot write a "${x.type}" field.`),x.type==="files"&&x.shareable===!0&&n.push(`[field/filesShareable] Field "${x.key}" is a files field and cannot be shareable.`),x.type==="auto-string"?l8(x,c,n):x.autoString!==void 0&&n.push(`Non-automatic field "${x.key}" must not define autoString.`),(!Number.isFinite(x.sortOrder)||x.sortOrder<0)&&n.push(`Field "${x.key}" has invalid sortOrder "${x.sortOrder}" (must be a non-negative number).`),(x.type==="0-1-select"||x.type==="0-n-select")&&!x.listKey&&n.push(`Select field "${x.key}" must define listKey.`),x.type!=="0-1-select"&&x.type!=="0-n-select"&&x.listKey!==void 0&&n.push(`Non-select field "${x.key}" must not define listKey.`),x.listKey&&!a.has(x.listKey)&&n.push(`Field "${x.key}" references missing list "${x.listKey}".`),(x.type==="object"||x.type==="relationship")&&!x.objectSchema&&n.push(`Field "${x.key}" must define objectSchema.`),x.type!=="object"&&x.type!=="relationship"&&x.objectSchema&&n.push(`Non-object field "${x.key}" must not define objectSchema.`);for(let D of x.objectSchema?.properties??[])(D.type==="0-1-select"||D.type==="0-n-select")&&!D.listKey&&n.push(`Object select property "${x.key}.${D.key}" must define listKey.`),D.listKey&&!a.has(D.listKey)&&n.push(`Object property "${x.key}.${D.key}" references missing list "${D.listKey}".`);s8(x,n)}let b=e.tenant.priceCriteriaFacts;if(b){let x=e.fields.find(D=>D.key===b.birthDateFieldKey);(!x||x.type!=="date")&&n.push("Price criteria require a configured date field for birth dates."),l.has(b.studentRoleKey)||n.push("Price criteria require a configured Student eligibility role."),b.siblingRankSource!==void 0&&b.siblingRankSource!=="derived"&&b.siblingRankSource!=="chosen"&&n.push('Price criteria siblingRankSource must be "derived" or "chosen".');for(let D of Object.keys(b))D!=="birthDateFieldKey"&&D!=="studentRoleKey"&&D!=="siblingRankSource"&&n.push(`Unknown price criteria fact setting "${D}".`)}let k=e.tenant.defaultEnrolleeRoleKey;k&&!l.has(k)&&n.push(`Default enrollment role "${k}" does not exist.`),k&&e.roles.some(x=>x.parentRoleKey===k)&&n.push(`Default enrollment role "${k}" must be a leaf role.`);for(let x of e.roles){(typeof x.icon!="string"||x.icon.trim().length===0)&&n.push(`Role "${x.key}" must define an icon.`),x.parentRoleKey&&!l.has(x.parentRoleKey)&&n.push(`Role "${x.key}" references missing parent role "${x.parentRoleKey}".`);for(let D of x.listDisplayFieldKeys??[])d.has(D)||n.push(`Role "${x.key}" list display references missing field "${D}".`)}let v=new Map(e.roles.map(x=>[x.key,x.parentRoleKey])),A=new Map;for(let x of e.roleFields){let D=A.get(x.roleKey)??[];D.push({roleId:x.roleKey,customFieldId:x.fieldKey}),A.set(x.roleKey,D)}for(let x of e.roles)try{bM(x.key,v,A)}catch(D){n.push(QM(D))}for(let x of e.roleFields){l.has(x.roleKey)||n.push(`Role field references missing role "${x.roleKey}" for field "${x.fieldKey}".`),d.has(x.fieldKey)||n.push(`Role field references missing field "${x.fieldKey}" for role "${x.roleKey}".`);for(let D of x.targetRequirementFieldKeys??[])d.has(D)||n.push(`Role field "${x.roleKey}.${x.fieldKey}" references missing target requirement field "${D}".`)}f8(e.contractRoleMappings??[],l,n);for(let x of e.templatePlaceholders??[])H0.test(x.key)||n.push(`Template placeholder "${x.key}" must use lower_snake_case segments, optionally separated by dots.`),x.source.kind==="customField"?bh(x.source,c,n,`Template placeholder "${x.key}"`):x.source.kind==="relationshipTargetField"&&d8(x,c,n);for(let x of e.searchTargets??[])bh(x,c,n,"Search target");for(let x of e.fields)$M(x.key)&&(x.defaultValue!==void 0||x.validations!==void 0)&&n.push(`System field "${x.key}" takes no defaultValue or validations.`);for(let x of e.lists)if(Rt(x.elements.map((D,R)=>String(D.sortOrder??(R+1)*10)),`sortOrder of an element of list "${x.key}"`,n),x.labelOrder!==void 0){let D=x.labelOrder.last;if(!Array.isArray(D)||D.some(R=>typeof R!="string")){n.push(`[list/labelOrder] List "${x.key}" states labelOrder.last ${JSON.stringify(D??null)} \u2014 a list of element keys.`);continue}Rt(x.labelOrder.last,`labelOrder.last key of list "${x.key}"`,n);for(let R of iC(x.labelOrder,x.elements.map(q=>q.key)))n.push(`[list/labelOrder] List "${x.key}" keeps "${R}" at the end, but has no element "${R}".`)}for(let x of e.searchFilters??[])Rt((x.options??[]).map((D,R)=>String(D.sortOrder??(R+1)*10)),`sortOrder of an option of search filter "${x.key}"`,n);for(let x of e.foundation.permissionGroups){x.grantAllCustomFields===!0&&x.customFieldPermissions!==void 0&&n.push(`Permission group "${x.key}" states both grantAllCustomFields and customFieldPermissions \u2014 one of them.`),Rt((x.customFieldPermissions??[]).map(D=>D.displayGroupKey),`display group of a field permission of group "${x.key}"`,n);for(let D of x.customFieldPermissions??[]){o.has(D.displayGroupKey)||n.push(`Permission group "${x.key}" grants field permissions on missing display group "${D.displayGroupKey}".`);for(let R of D.permissions)AM.includes(R)||n.push(`Permission group "${x.key}" grants unknown field permission "${R}".`)}}let T=e.tenant.partyRetention;T!==void 0&&(RM(T.days)||n.push(`tenant.partyRetention.days must be a whole number of days from 1 to ${36500} (got ${JSON.stringify(T.days)}).`),Number.isFinite(T.enabledAt)||n.push("tenant.partyRetention.enabledAt must be a timestamp (epoch ms)."),T.formerRoleKey!==void 0&&!l.has(T.formerRoleKey)&&n.push(`tenant.partyRetention references missing role "${T.formerRoleKey}".`));for(let x of e.searchFilters??[]){(x.kind==="chips"||x.kind==="select")&&(x.options?.length??0)===0&&n.push(`Search filter "${x.key}" must define options.`),(x.kind==="text"||x.kind==="numberRange")&&x.target===void 0&&n.push(`Search filter "${x.key}" must define a target field.`),x.options!==void 0&&Rt(x.options.map(D=>D.key),`search filter option for "${x.key}"`,n),bh(x.target,c,n,`Search filter "${x.key}"`);for(let D of x.options??[]){D.predicates.length===0&&n.push(`Search filter option "${x.key}.${D.key}" must define at least one predicate.`);for(let R of D.predicates){if(R.kind==="role"){l.has(R.roleKey)||n.push(`Search filter option "${x.key}.${D.key}" references missing role "${R.roleKey}".`);continue}R.kind==="enrollment"?n.push(...GM(R,`${x.key}.${D.key}`)):bh(R,c,n,`Search filter option "${x.key}.${D.key}"`)}}}for(let x of e.partyResultIcons??[])c8(x,c,n);for(let x of e.foundation.legalEntities)if(x.terms!==void 0&&n.push(...Bv(x.terms,`foundation.legalEntities.${x.key}.terms`)),ZM(x.branding,n,`foundation.legalEntities.${x.key}.branding`),XM(x,n,`foundation.legalEntities.${x.key}`),x.signatoryUserKey!==void 0&&x.type==="school_group"&&n.push(`[config/signatoryOnGroup] Legal entity "${x.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) declares an Unterschriftsperson.`),x.parentLegalEntityKey&&!u.has(x.parentLegalEntityKey)&&n.push(`Legal entity "${x.key}" references missing parent "${x.parentLegalEntityKey}".`),x.address!==void 0){let D=x.address,R=["street","hausnr","plz","ort"];x.type==="school_group"?n.push(`Legal entity "${x.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) has an address.`):(typeof D!="object"||D===null||Array.isArray(D)||Object.keys(D).some(q=>!R.includes(q))||R.some(q=>typeof D[q]!="string"||(D[q]??"").trim()===""))&&n.push(`Legal entity "${x.key}" has an invalid address \u2014 expected { street, hausnr, plz, ort }, each non-empty.`)}let I=new Map;for(let x of e.foundation.units){if(x.slug!==void 0){let D=typeof x.slug=="string"?L_(x.slug):"must be a string";D!==void 0&&n.push(`Unit "${x.key}" has invalid slug "${x.slug}" (${D}).`);let R=I.get(x.slug);R!==void 0&&n.push(`Units "${R}" and "${x.key}" both declare slug "${x.slug}" (unit slugs are unique per tenant).`),I.set(x.slug,x.key)}u.has(x.legalEntityKey)||n.push(`Unit "${x.key}" references missing legal entity "${x.legalEntityKey}".`),x.parentUnitKey&&!p.has(x.parentUnitKey)&&n.push(`Unit "${x.key}" references missing parent unit "${x.parentUnitKey}".`),x.sortOrder!==void 0&&(!Number.isFinite(x.sortOrder)||x.sortOrder<0)&&n.push(`Unit "${x.key}" has invalid sortOrder "${x.sortOrder}" (must be a non-negative number).`)}let C=/^[0-9a-f]{32}:[0-9a-f]{128}$/;for(let x of e.foundation.users){h.has(x.permissionGroupKey)||n.push(`User "${x.email}" references missing permission group "${x.permissionGroupKey}".`),x.unitKey&&!p.has(x.unitKey)&&n.push(`User "${x.email}" references missing unit "${x.unitKey}".`),x.status!==void 0&&x.status!=="deactivated"&&n.push(`User "${x.email}": status must be "deactivated" or absent, not "${String(x.status)}".`);let D=[x,...x.additionalMemberships??[]];for(let q of x.additionalMemberships??[])h.has(q.permissionGroupKey)||n.push(`User "${x.email}" references missing permission group "${q.permissionGroupKey}".`),q.unitKey&&!p.has(q.unitKey)&&n.push(`User "${x.email}" references missing unit "${q.unitKey}".`);Rt(D.map(q=>`${q.permissionGroupKey}/${q.unitKey??""}`),`membership (permission group/unit) of user "${x.email}"`,n);for(let q of D)q.validFrom!==void 0&&q.validTo!==void 0&&q.validTo<=q.validFrom&&n.push(`User "${x.email}": membership "${q.permissionGroupKey}" ends (validTo) before it starts (validFrom).`);let R=[x.firstName,x.lastName];R.some(q=>q!==void 0)&&R.some(q=>typeof q!="string"||q.trim()==="")&&n.push(`[config/userNameIncomplete] User "${x.email}" states only part of firstName/lastName (or an empty one) \u2014 set both or neither.`);for(let q of["staging","prod"]){let G=x.passwordHashes?.[q];G!==void 0&&!C.test(G)&&n.push(`User "${x.email}" passwordHashes.${q} is not in Better Auth scrypt format "<32hex>:<128hex>".`)}}ZM(e.tenant.branding,n),XM(e.tenant,n);let L=nq(e.fields.flatMap(x=>x.sourceColumns));for(let x of L)r.push(`Source column "${x}" is mapped by more than one field.`);w8(e,n);let N=t.sourceColumns===void 0||e.source===void 0?void 0:g8(e,t.sourceColumns,n);return{ok:n.length===0,errors:n,warnings:r,coverage:N}}s(eq,"validateTenantConfig");function s8(e,t){let n=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(!_k.includes(i)){t.push(`${o}: addressPart "${i}" is none of ${_k.join(", ")}.`);continue}e.type!=="object"&&t.push(`${o}: only an object field stores an address (addressPart).`),r.type!=="string"&&t.push(`${o}: addressPart "${i}" needs a string property, not "${r.type}".`);let a=n.get(i);a!==void 0&&t.push(`${o}: addressPart "${i}" is already declared by "${e.key}.${a}".`),n.set(i,r.key)}}s(s8,"validateAddressParts");function a8(e,t){let n=e.relationshipKinds;if(n===void 0)return;if(e.type!=="relationship"){t.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 n){let o=`Field "${e.key}" relationship kind "${i.key}"`;if(typeof i.key!="string"||i.key.trim()===""){t.push(`Field "${e.key}": a relationship kind needs a key.`);continue}for(let l of["de","en"])(i.label?.[l]??"").trim()===""&&t.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)){t.push(`${o}: edge must be an object.`);continue}i.sibling!==void 0&&i.sibling!==!0&&t.push(`${o}: sibling must be true or absent.`),i.sibling===!0&&i.mergeInto!==void 0&&t.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare mergeInto.`);let a=n.flatMap(l=>l.mergeInto!==void 0?[l.mergeInto]:[]);if(i.sibling===!0&&a.some(l=>l in i.edge)&&t.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&&t.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"?t.push(`${o}: mergeInto "${i.mergeInto}" must name a 0-n-select property of the field's objectSchema.`):Array.isArray(i.edge[i.mergeInto])||t.push(`${o}: mergeInto "${i.mergeInto}" must be set to a list in the edge.`)}}}s(a8,"validateRelationshipKinds");function l8(e,t,n){if(e.autoString===void 0){n.push(`Automatic field "${e.key}" must define autoString.`);return}e.allowMultiple===!0&&n.push(`Automatic field "${e.key}" must not allow multiple values.`),e.shareable===!0&&n.push(`Automatic field "${e.key}" must not be shareable.`),e.autoString.segments.length===0&&n.push(`Automatic field "${e.key}" must define at least one segment.`),e.autoString.segments.filter(i=>i.kind==="sequence").length!==1&&n.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&&n.push(`Automatic field "${e.key}" has an empty literal segment.`),i.kind==="sequence"&&(i.startAt!==void 0&&(!Number.isInteger(i.startAt)||i.startAt<1)&&n.push(`Automatic field "${e.key}" sequence startAt must be an integer >= 1.`),i.minDigits!==void 0&&(!Number.isInteger(i.minDigits)||i.minDigits<0)&&n.push(`Automatic field "${e.key}" sequence minDigits must be an integer >= 0.`)),i.kind==="field"){let o=t.get(i.fieldKey);if(o===void 0){n.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&&n.push(`Automatic field "${e.key}" references missing object property "${i.fieldKey}.${i.objectPropertyKey}".`)}}s(l8,"validateAutomaticStringField");function bh(e,t,n,r){if(e===void 0)return;let i=t.get(e.fieldKey);if(i===void 0){n.push(`${r} references missing field "${e.fieldKey}".`);return}if(e.objectPropertyKey===void 0)return;(i.objectSchema?.properties.some(a=>a.key===e.objectPropertyKey)??!1)||n.push(`${r} references missing object property "${e.fieldKey}.${e.objectPropertyKey}".`)}s(bh,"validateSearchTarget");function d8(e,t,n){if(e.source.kind!=="relationshipTargetField")return;let r=`Template placeholder "${e.key}"`,i=t.get(e.source.relationshipFieldKey);if(i===void 0)n.push(`${r} references missing relationship field "${e.source.relationshipFieldKey}".`);else if(i.type!=="relationship")n.push(`${r} relationship field "${e.source.relationshipFieldKey}" must be a relationship field.`);else{for(let a of e.source.edgeFilters??[])Yv(i,a.propertyKey,n,`${r} edge filter`);e.source.selection?.sortPropertyKey!==void 0&&Yv(i,e.source.selection.sortPropertyKey,n,`${r} selection sort`)}let o=t.get(e.source.targetFieldKey);if(o===void 0){n.push(`${r} references missing target field "${e.source.targetFieldKey}".`);return}o.type==="relationship"&&n.push(`${r} target field "${e.source.targetFieldKey}" must not be a relationship field.`),e.source.targetObjectPropertyKey!==void 0&&Yv(o,e.source.targetObjectPropertyKey,n,`${r} target`)}s(d8,"validateRelationshipTemplatePlaceholder");function Yv(e,t,n,r){(e.objectSchema?.properties.some(o=>o.key===t)??!1)||n.push(`${r} references missing object property "${e.key}.${t}".`)}s(Yv,"validateObjectPropertyReference");function c8(e,t,n){let r=`Party result icon "${e.key}"`,i=t.get(e.when.fieldKey);if(i===void 0){n.push(`${r} references missing field "${e.when.fieldKey}".`);return}if(e.when.objectPropertyKey===void 0){i.type!=="boolean"&&n.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){n.push(`${r} references missing object property "${e.when.fieldKey}.${e.when.objectPropertyKey}".`);return}o.type!=="boolean"&&n.push(`${r} must target a Boolean field or object property.`)}s(c8,"validatePartyResultIconTarget");function tq(e){return`${e.templateId}:${e.locale}:${e.scopeKey}`}s(tq,"letterIdentity");function u8(e){return`${e.generatorKey??"*"}/${e.partyKind}/${e.roleKey}`}s(u8,"contractRoleMappingIdentity");function f8(e,t,n){let r=new Set;for(let i of e){let o=u8(i),a=`Contract role mapping "${o}"`;Lv.includes(i.partyKind)||n.push(`${a}: partyKind must be one of ${Lv.join(", ")}.`),i.partyKind==="beneficiary"&&n.push(`${a}: a beneficiary holds the enrollee role of the program it attends (programs.enrolleeRoleKey, else tenant.defaultEnrolleeRoleKey) \u2014 remove the mapping.`),t.has(i.roleKey)||n.push(`${a} references missing role "${i.roleKey}".`),i.generatorKey!==void 0&&i.generatorKey.trim()===""&&n.push(`${a}: generatorKey must not be blank \u2014 omit it for the tenant default.`),r.has(o)&&n.push(`${a} is declared twice.`),r.add(o)}}s(f8,"validateContractRoleMappings");function p8(e,t){for(let n of e){let r=`Notification letter "${tq(n)}"`;if(!ph(n.locale)){t.push(`${r} declares locale "${String(n.locale)}" \u2014 letters are written in ${Ge.map(i=>`"${i}"`).join(" and ")} only, so no mail would ever read this deviation.`);continue}if(n.scopeKey!==fh){t.push(`${r} declares scopeKey "${n.scopeKey}" \u2014 the only scope is "${fh}" (the whole school).`);continue}if(Object.keys(n.slots).length===0){t.push(`${r} overrides no block. A deviation that deviates in nothing is not an entry \u2014 remove it.`);continue}if(!ab(n.templateId)){t.push(`${r} references no registered letter \u2014 "${n.templateId}" is not in the letter catalog.`);continue}for(let i of NM(sb(n.templateId),n.slots,n.locale))t.push(`${r}, block "${i.slotKey}" [${i.code}]: ${i.message.de}`)}}s(p8,"validateNotificationLetters");function m8(e,t){if(e!==void 0)for(let n of PM(e))t.push(`Notification chrome: ${n.de}`)}s(m8,"validateNotificationChrome");function ZM(e,t,n){if(e===void 0)return;let r=n===void 0?t:{push:s((...p)=>t.push(...p.map(h=>`${n}: ${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(ZM,"validateBranding");function XM(e,t,n="tenant"){let r=e.brandingAssets;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r)){t.push(`${n}.brandingAssets must be an object keyed by slot (${yh.join(", ")}).`);return}for(let[i,o]of Object.entries(r)){let a=`${n}.brandingAssets.${i}`;if(!yh.includes(i)){t.push(`${a}: unknown slot (expected ${yh.join(", ")}).`);continue}if(typeof o!="object"||o===null){t.push(`${a}: must be { sha256, sizeBytes, mimeType }.`);continue}if("size"in o){t.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}rq.test(o.sha256??"")||t.push(`${a}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(o.sizeBytes)||o.sizeBytes<=0)&&t.push(`${a}: sizeBytes must be a positive integer.`);let l=MM[i];if(l===null){let d=qM({contentType:o.mimeType,size:o.sizeBytes});d!==null&&t.push(`${a}: ${d.de}`)}else{o.mimeType!==zv&&t.push(`${a}: mimeType must be "${zv}" (got "${o.mimeType}").`);let d=KM(e.branding?.fonts?.[l]?.family);d!==null&&t.push(`${a}: [branding/fontFamilyMissing] ${n}.branding.fonts.${l}: ${d.de}`)}"path"in o&&t.push(`${a}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}}s(XM,"validateBrandingAssets");function h8(e,t){let n=e.defaultUnitKey,r=t.map(i=>i.key);return typeof n!="string"||n===""?[`[import/defaultUnitMissing] source "${e.sourceKey}" names no default unit \u2014 set source.defaultUnitKey to one of ${r.join(", ")||"(no units declared)"}.`]:r.includes(n)?[]:[`[import/defaultUnitUnknown] source "${e.sourceKey}" names the default unit "${n}", which is not in foundation.units \u2014 one of ${r.join(", ")||"(no units declared)"}.`]}s(h8,"sourceDefaultUnitFindings");function g8(e,t,n){let{source:r}=e;r===void 0&&F("validateSourceCoverage: called without a `source` block.");let i=new Set(t),o=new Set(e.fields.flatMap(b=>b.sourceColumns)),a=new Set(e.deferredColumns.map(b=>b.column)),l=new Set(e.ignoredColumns.map(b=>b.column)),d=new Set([...o,...a,...l]),c=r.requiredColumns.filter(b=>!i.has(b)),u=t.filter(b=>!d.has(b)),p=[...o].filter(b=>!i.has(b)),h=[...a].filter(b=>!i.has(b)),y=[...l].filter(b=>!i.has(b));for(let b of c)n.push(`Required source column "${b}" is missing from ${r.primaryTable}.`);for(let b of u)n.push(`Source column "${b}" is neither mapped nor explicitly deferred/ignored.`);for(let b of p)n.push(`Mapped source column "${b}" does not exist in the source schema.`);for(let b of h)n.push(`Deferred source column "${b}" does not exist in the source schema.`);for(let b of y)n.push(`Ignored source column "${b}" does not exist in the source schema.`);return{table:r.primaryTable,availableColumns:t.length,mappedColumns:[...o].filter(b=>i.has(b)).length,deferredColumns:[...a].filter(b=>i.has(b)).length,ignoredColumns:[...l].filter(b=>i.has(b)).length,missingRequiredColumns:c,unmappedColumns:u,unknownMappedColumns:p,unknownDeferredColumns:h,unknownIgnoredColumns:y}}s(g8,"validateSourceCoverage");function Rt(e,t,n){for(let r of nq(e))n.push(`Duplicate ${t} key "${r}".`)}s(Rt,"requireUnique");function nq(e){let t=new Set,n=new Set;for(let r of e)t.has(r)&&n.add(r),t.add(r);return[...n]}s(nq,"duplicates");var rq=/^[0-9a-f]{64}$/,y8=["fileName","size"];function w8(e,t){if(!Array.isArray(e.files)){t.push('"files" is missing \u2014 declare the file library (an empty list is fine).');return}Rt(e.files.map(n=>n.key),"file",t);for(let n of e.files){let r=`files["${n.key}"]`;Za(n.key)||t.push(`${r}: key must match ${pv}.`);for(let o of["de","en"])(n.label?.[o]??"").trim()===""&&t.push(`${r}: label.${o} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);let i=y8.filter(o=>o in n);if(i.length>0){t.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 n.filename!="string")t.push(`${r}: filename is missing.`);else{let o=As(n.filename);o!==null&&t.push(`${r}: filename ${o}.`)}gh.includes(n.mimeType)||t.push(`${r}: mimeType "${n.mimeType}" is not allowed (${gh.join(", ")}).`),rq.test(n.sha256??"")||t.push(`${r}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(n.sizeBytes)||n.sizeBytes<=0)&&t.push(`${r}: sizeBytes must be a positive integer.`),"path"in n&&t.push(`${r}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}s(w8,"validateFiles");var k8=new WeakMap,b8=new WeakSet;function Hv(e,t){t(e);let r=e.asOptional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>Hv(r(),t),"value"),enumerable:!1}),e}s(Hv,"carry");function ol(e,t){return Hv(e,n=>k8.set(n,t))}s(ol,"tagged");var v8="tenant teardown drains every table explicitly (config/wipe.ts)",ze={belongsTo:s(e=>ol(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>ol(e,{kind:"owns"}),"owns"),holds:s(e=>ol(e,{kind:"holds"}),"holds"),restrict:s((e,t)=>ol(e,t?{kind:"restrict",unindexed:t.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>ol(e,{kind:"history"}),"history"),tenant:s(e=>ol(e,{kind:"restrict",unindexed:v8}),"tenant"),historyOf:s(e=>Hv(e,t=>b8.add(t)),"historyOf")};var x8=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string()}),iq=m.union(m.literal("school_operator"),m.literal("school_group"),m.literal("service_entity")),mi=iq.members.map(e=>e.value),S8={tenantId:ze.tenant(m.id("tenants")),name:m.optional(m.string()),type:iq,parentLegalEntityId:m.optional(ze.restrict(m.id("legal_entities"))),configKey:m.optional(m.string()),partyId:m.optional(ze.restrict(m.id("parties"))),address:m.optional(x8),signatoryUserId:m.optional(ze.restrict(m.id("users"))),terms:m.optional(OM)},F_e=Gn(S8).index("by_tenantId",["tenantId"]).index("by_parentLegalEntityId",["parentLegalEntityId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_partyId",["partyId"]).index("by_signatoryUserId",["signatoryUserId"]);var A8=m.union(m.literal("school"),m.literal("kindergarten"),m.literal("after_school_care"),m.literal("department"),m.literal("site"),m.literal("other")),Xn=A8.members.map(e=>e.value),q_e=m.union(m.literal("school"),m.literal("vocational"),m.literal("care"),m.literal("seminar"),m.literal("other")),K_e=m.union(m.literal("none"),m.literal("manual"),m.literal("annual_rollover")),j_e=m.union(m.literal("grade_level"),m.literal("module"),m.literal("phase"),m.literal("other")),V_e=m.union(m.literal("school_year"),m.literal("cohort"),m.literal("seminar"),m.literal("care_period"),m.literal("other")),B_e=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("archived")),U_e=m.union(m.literal("class"),m.literal("course"),m.literal("care_group"),m.literal("seminar_group"),m.literal("mixed_age_group"),m.literal("other")),G_e=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("cancelled")),z_e=m.union(m.literal("class_teacher"),m.literal("teacher"),m.literal("mentor"),m.literal("instructor"),m.literal("assistant"),m.literal("other")),W_e=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")),Y_e=m.union(m.literal("open"),m.literal("mapped"),m.literal("ignored"));function sq(e){let t=["street","hausnr","plz","ort"].filter(n=>e[n]!==void 0);if(t.length!==0){if(t.length!==4)throw new g(`config legal-entity add: an address needs all of --street, --hausnr, --plz and --ort (got ${t.map(n=>`--${n}`).join(", ")})`);return{street:e.street,hausnr:e.hausnr,plz:e.plz,ort:e.ort}}}s(sq,"addressFrom");function aq(e){if(!mi.includes(e))throw new g(`config legal-entity add: --type "${e}" is none of ${mi.join(", ")}`);return e}s(aq,"legalEntityType");function lq(e){if(!Xn.includes(e))throw new g(`config unit add: --kind "${e}" is none of ${Xn.join(", ")}`);return e}s(lq,"unitKind");function dq(e,t,n){let r=e.find(i=>i.key===t.key);if(r===void 0)return e.push(t),"create";if(Ce(r)===Ce(t))return"same";throw new g(`${n} "${t.key}" already exists with other values \u2014 decide by hand, nothing written.
11791
+ `)).includes(u.key));if(p.length===0)continue;let h=s((k,v)=>k.map(A=>v(i.find(T=>T.key===A)?.label??A)).join(" + "),"variantLabel"),y=c.length===1?"":` Er fehlt in der Fassung aus ${p.map(k=>h(k,v=>`\u201E${v}\u201C`)).join(" und in der aus ")}.`,b=c.length===1?"":` It is missing in the version made of ${p.map(k=>h(k,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 die Benachrichtigung \u201E${e.label}\u201C nicht \u2014 der Platzhalter muss im Text stehen, nicht nur im Betreff.`+y,en:`Without "{{${u.key}}}" (${u.label}) the notification "${e.label}" does not work \u2014 the placeholder must be in the text, not only in the subject.`+b}})}return r}s(NM,"validateOverride");function TQ(e,t,n){let r=e.find(i=>i.key===t);return r===void 0?"":AQ(r,n)}s(TQ,"defaultTextOf");function Uv(e){let t=e?.trim();return t===void 0||t.length===0?void 0:t}s(Uv,"normalizeChromeText");var $s=s(e=>String.fromCharCode(e),"cp"),RQ=new RegExp(`[${$s(0)}-${$s(31)}${$s(127)}]`,"g"),$Q=new RegExp(`[${$s(8234)}-${$s(8238)}${$s(8294)}-${$s(8297)}]`,"g");var EQ=200;function IQ(e,t=EQ){return e.replace(RQ," ").replace($Q,"").replace(/\s+/g," ").trim().slice(0,t)}s(IQ,"sanitizeHeaderValue");function hh(e){return IQ(e.replace(/["<>@]/g,""),100)}s(hh,"sanitizeDisplayName");var Gv={de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}},OQ={greeting:{de:"Anrede",en:"Greeting"},closing:{de:"Gru\xDFformel",en:"Closing"}};function PM(e){let t=[],n=[];for(let i of["greeting","closing"]){let o=e[i];if(o===void 0)continue;let a=OQ[i],l=Ft(o);l!=="not-localized"&&l.length>0&&l.length<Ge.length&&n.push({de:`${a.de} fehlt auf ${l.map(d=>Gv[d].de).join(" und ")}`,en:`${a.en} is missing in ${l.map(d=>Gv[d].en).join(" and ")}`});for(let d of Ge){let c=Uk(h=>`${a[h]} (${Gv[d][h]})`),u=Uv(o[d]);u!==void 0&&u.length>Rs&&t.push({de:`${c.de} hat ${u.length} Zeichen \u2014 h\xF6chstens ${Rs}; Anrede und Gru\xDFformel sind je eine Zeile der Mail, kein Dokument.`,en:`${c.en} has ${u.length} characters \u2014 at most ${Rs}; the greeting and the sign-off are one line of the mail each, not a document.`});let p=i==="greeting"?[pi]:[];for(let h of mh(u??""))p.includes(h)||t.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: {{${pi}}} (${il}).`,en:`"{{${h}}}" does not exist in the ${c.en}. Allowed: {{${pi}}} (${il}).`})}}n.length>0&&t.unshift({de:`[notification/chromeMissingTranslation] ${n.map(i=>i.de).join("; ")} \u2014 Anrede und Gru\xDFformel gelten f\xFCr jede Benachrichtigung, in jeder Sprache.`,en:`[notification/chromeMissingTranslation] ${n.map(i=>i.en).join("; ")} \u2014 the greeting and sign-off apply to every notification, in every language.`});let r=Uv(e.senderName);return r!==void 0&&hh(r)!==r&&t.push({de:`Absendername (senderName) \u201E${r}\u201C \xFCbersteht die Kopfzeile der Mail nicht unver\xE4ndert \u2014 er ginge als \u201E${hh(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 "${hh(r)}". No quotation marks, angle brackets, "@" or control characters.`}),t}s(PM,"chromeFindings");var Zd=["application/pdf","image/jpeg","image/png","image/webp"];var gh=["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"],CM={docRef:{maxBytes:25*1048576,allowedMime:Zd},partyFile:{maxBytes:25*1048576,allowedMime:Zd},import:{maxBytes:500*1048576,allowedMime:null},signedContract:{maxBytes:25*1048576,allowedMime:Zd},artifactVersion:{maxBytes:25*1048576,allowedMime:Zd},chatAttachment:{maxBytes:25*1048576,allowedMime:Zd},tenantFile:{maxBytes:20*1048576,allowedMime:gh},documentTemplate:{maxBytes:25*1048576,allowedMime:null}};function DM(e){let t=atob(e),n="";for(let r=0;r<t.length;r++)n+=t.charCodeAt(r).toString(16).padStart(2,"0");return n}s(DM,"sha256Base64ToHex");var FM=m.object({family:m.string()}),LM=m.object({family:m.string(),url:m.optional(m.string())}),mOe=m.object({heading:m.optional(LM),body:m.optional(LM)}),_Q=m.union(m.literal("sharp"),m.literal("rounded"),m.literal("soft")),NQ=m.union(m.literal("light"),m.literal("dark")),PQ=m.union(m.literal("sm"),m.literal("md"),m.literal("lg"),m.literal("max")),CQ=m.union(m.literal("compact"),m.literal("normal"),m.literal("spacious")),DQ=m.object({primary:m.optional(m.string()),accent:m.optional(m.string()),background:m.optional(m.string()),foreground:m.optional(m.string())}),FQ=m.object({heading:m.optional(FM),body:m.optional(FM)}),hOe=m.object({colors:m.optional(DQ),radius:m.optional(_Q),logoSize:m.optional(PQ),bannerDensity:m.optional(CQ),logoGround:m.optional(NQ),filledHeader:m.optional(m.boolean()),websiteUrl:m.optional(m.string()),fonts:m.optional(FQ)}),gOe=m.object({primaryUrl:m.union(m.null(),m.string())}),yOe=m.literal("primary"),wOe=m.object({headingUrl:m.union(m.null(),m.string()),bodyUrl:m.union(m.null(),m.string())}),kOe=m.union(m.literal("heading"),m.literal("body")),yh=["logo","fontHeading","fontBody"],MM={logo:null,fontHeading:"heading",fontBody:"body"};function qM(e){let{contentType:t,size:n}=e;return t==null||!t.startsWith("image/")?{de:`Das Logo muss ein Bild sein (erhalten: \u201E${t??"unbekannt"}\u201C).`,en:`The logo must be an image (received: "${t??"unknown"}").`}:t.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."}:n>3e6?{de:`Das Logo ist zu gro\xDF (${n} Byte, h\xF6chstens 3000000 Byte).`,en:`The logo is too large (${n} bytes, at most 3000000 bytes).`}:null}s(qM,"logoFileProblem");var zv="font/woff2";var LQ=["Inter Variable","Azeret Mono Variable","Source Sans 3 Variable"];function KM(e){return e?.trim()?LQ.some(t=>t.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(KM,"fontFamilyProblem");var MQ=["approved","rejected","withdrawn","waitlist","expired"];var wh=["admitted","rejected","withdrawn","waitlist","expired","unknown"],ROe=m.union(...MQ.map(e=>m.literal(e))),$Oe=m.union(...wh.map(e=>m.literal(e))),qQ=["approved","rejected","waitlist"],KQ=["withdrawn","expired"],jQ=m.union(...qQ.map(e=>m.literal(e))),VQ=m.union(...KQ.map(e=>m.literal(e))),EOe={active:{status:m.literal("active")},completed:{status:m.literal("completed"),outcome:jQ,endedAt:m.number()},aborted:{status:m.literal("aborted"),outcome:m.optional(VQ),endedAt:m.number()}};var jM=30,VM=3650;var BQ=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())}),COe=BQ.fields,UQ=s(e=>wh.includes(e),"isClassification");function BM(e,t="tenant.retentionDays"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[retention/shape] ${t} must be an object of days per classification (got ${JSON.stringify(e)}).`];let n=[];for(let[r,i]of Object.entries(e)){if(!UQ(r)){n.push(`[retention/unknownClassification] ${t}.${r} is no retention classification \u2014 one of ${wh.join(", ")}.`);continue}(typeof i!="number"||!Number.isSafeInteger(i)||i<jM||i>VM)&&n.push(`[retention/days] ${t}.${r} must be a whole number of days from ${jM} to ${VM} (got ${JSON.stringify(i)}).`)}return n}s(BM,"retentionDaysFindings");var GQ=["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"],zQ=new Set(GQ);function kh(e){return zQ.has(e)}s(kh,"isCountryCode");var Wv=["off","always","deviating"],UM={mode:"deviating",defaultCountryCode:"de"};function GM(e,t){return[["programKey",e.programKey],["runKey",e.runKey],["learningGroupKey",e.learningGroupKey]].filter(([,n])=>n!==void 0&&n.trim().length===0).map(([n])=>`Search filter option "${t}" has an empty enrollment ${n}.`)}s(GM,"enrollmentPredicateShapeErrors");var WQ=["street","plz","ort"];function YQ(e){return WQ.filter(t=>!e.has(t))}s(YQ,"missingInvoiceAddressParts");var HQ=new Set(["0-1-select","0-n-select"]);function zM(e){return e===void 0?null:new Set(e.properties.flatMap(t=>t.addressPart!==void 0&&AP(t.addressPart)?[t.addressPart]:[]))}s(zM,"declaredAddressParts");function JQ(e){return HQ.has(e)}s(JQ,"isSelectFieldKind");function WM(e){let t=[];for(let o of e)if(o.isNationality&&(JQ(o.kind)?o.listKind!=="country"&&t.push({code:"nationality/notCountryList",fieldKey:o.key}):t.push({code:"nationality/wrongFieldKind",fieldKey:o.key})),o.isAccountEmail&&o.kind!=="email"&&t.push({code:"accountEmail/wrongFieldKind",fieldKey:o.key}),o.isContactPhone&&o.kind!=="tel"&&t.push({code:"contactPhone/wrongFieldKind",fieldKey:o.key}),o.isInvoiceAddress)if(o.addressParts===null)t.push({code:"invoiceAddress/wrongFieldKind",fieldKey:o.key});else{let a=YQ(o.addressParts);a.length>0&&t.push({code:"invoiceAddress/missingPart",fieldKey:o.key,parts:a})}let n=e.filter(o=>o.isAccountEmail);if(n.length>1)for(let o of n)t.push({code:"accountEmail/multiple",fieldKey:o.key});let r=e.filter(o=>o.isContactPhone);if(r.length>1)for(let o of r)t.push({code:"contactPhone/multiple",fieldKey:o.key});let i=e.filter(o=>o.isInvoiceAddress);if(i.length>1)for(let o of i)t.push({code:"invoiceAddress/multiple",fieldKey:o.key});return t}s(WM,"fieldRoleFindings");function YM(e,t,...n){let r=e[t.code];return r(t,...n)}s(YM,"wordListElementFinding");function HM(e,t){let n=[];for(let r of t){if(e.kind==="plain"){r.countryCode!==void 0&&n.push({code:"list/countryCodeOnPlain",elementKey:r.key,countryCode:r.countryCode});continue}r.countryCode===void 0?n.push({code:"list/countryCodeMissing",elementKey:r.key}):r.countryCode!==null&&!kh(r.countryCode)&&n.push({code:"list/unknownCountryCode",elementKey:r.key,countryCode:r.countryCode})}return n}s(HM,"listElementCountryFindings");var ZQ={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},XQ={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,externalMail:!0,testMailRecipients:!0,magicLinkLogin:!0,externalSignIn:!0,nationalityFlag:!0,adminSeesSignatureImages:!0,signatureStamp:!0,bankImportScope:!0,branding:!0,brandingAssets:!0,partyRetention:!0},e8=new Set(["enabledMailCategories","mailEnabled"]);function t8(e){let t=s((n,r,i)=>n.filter(o=>!Object.hasOwn(r,o)&&!(i==="tenant."&&e8.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[...t(Object.keys(e),ZQ,""),...t(Object.keys(e.tenant),XQ,"tenant.")]}s(t8,"unknownKeyFindings");var JM=["plain","country"],n8={"list/countryCodeMissing":s(({elementKey:e},t)=>`Element "${t}.${e}" of a country list must state countryCode (null for no state).`,"list/countryCodeMissing"),"list/countryCodeOnPlain":s(({elementKey:e},t)=>`Element "${t}.${e}" carries countryCode, but list "${t}" is not kind "country".`,"list/countryCodeOnPlain"),"list/unknownCountryCode":s(({elementKey:e,countryCode:t},n)=>`Element "${n}.${e}" has unknown countryCode ${JSON.stringify(t)}.`,"list/unknownCountryCode")},r8={"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:t})=>`Field "${e}" is isInvoiceAddress but declares no property for the address part(s) ${t.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 i8(e){let t=r8[e.code];return t(e)}s(i8,"roleText");function o8(e){let t=[],n=e.tenant.nationalityFlag,r=typeof n=="object"&&n!==null?n:{},i=r.mode;if(Wv.includes(i)||t.push(`[nationality/flagMode] tenant.nationalityFlag.mode must be one of ${Wv.join(", ")} (got ${n===void 0?"no tenant.nationalityFlag":JSON.stringify(i??null)}).`),n!==void 0){let l=r.defaultCountryCode;(typeof l!="string"||!kh(l))&&t.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(!JM.includes(d)){t.push(`[list/kind] List "${l.key}" has kind ${JSON.stringify(d??null)} \u2014 one of ${JM.join(", ")}.`);continue}o.set(l.key,l.kind);for(let c of HM({key:l.key,kind:l.kind},l.elements))t.push(`[${c.code}] ${YM(n8,c,l.key)}`)}let a=WM(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"?zM(l.objectSchema??{properties:[]}):null})));for(let l of a)t.push(`[${l.code}] ${i8(l)}`);return t}s(o8,"nationalityFindings");function QM(e){return ar(e)?.message.de??(e instanceof Error?e.message:String(e))}s(QM,"errorText");function eq(e,t={}){let n=[...t8(e)],r=[];e.source!==void 0&&n.push(...h8(e.source,e.foundation.units));try{xM(e.fields.map(x=>x.key),[])}catch(x){n.push(QM(x))}e.tenant.terms!==void 0&&n.push(...Bv(e.tenant.terms)),e.tenant.retentionDays!==void 0&&n.push(...BM(e.tenant.retentionDays)),AD(e.tenant.mailLevel)?e.tenant.mailLevel==="all"&&!Jd(e.tenant.enabledModules,"notifications")&&n.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".'):n.push(`[notification/mailLevel] tenant.mailLevel must be one of ${rb.join(", ")} (got ${e.tenant.mailLevel===void 0?"nothing":JSON.stringify(e.tenant.mailLevel)}).`);let i=e.tenant.testMailRecipients;i!==void 0&&(!Array.isArray(i)||i.length===0||!i.every(x=>typeof x=="string"&&Fv(x).includes("@"))?n.push("[notification/testRecipients] tenant.testMailRecipients must be a non-empty list of login addresses (leave it out for no test recipients)."):new Set(i.map(x=>Fv(x))).size!==i.length&&n.push("[notification/testRecipients] tenant.testMailRecipients names an address twice."),(e.tenant.mailLevel!=="loginOnly"||!Jd(e.tenant.enabledModules,"notifications"))&&n.push('[notification/testRecipientsWithoutEffect] tenant.testMailRecipients decides only at mailLevel "loginOnly" with the notifications module on \u2014 at "all" everybody gets mail, with the module off nobody. Remove the list or change the level.')),"enabledMailCategories"in e.tenant&&n.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&&n.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).'),Rt(e.displayGroups.map(x=>x.key),"display group",n),Rt(e.lists.map(x=>x.key),"list",n),Rt(e.roles.map(x=>x.key),"role",n),Rt(e.fields.map(x=>x.key),"field",n),Rt(e.foundation.legalEntities.map(x=>x.key),"legal entity",n),Rt(e.foundation.units.map(x=>x.key),"unit",n),Rt(e.foundation.permissionGroups.map(x=>x.key),"permission group",n),"teams"in e.foundation&&n.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 x of e.foundation.users)"teamKeys"in x&&n.push(`User "${x.email}" carries teamKeys, retired: team membership is the user's permission-group membership.`);if(Rt(e.foundation.users.map(x=>x.key),"user",n),Rt((e.searchFilters??[]).map(x=>x.key),"search filter",n),Rt((e.searchTargets??[]).map(x=>x.objectPropertyKey===void 0?x.fieldKey:`${x.fieldKey}.${x.objectPropertyKey}`),"search target",n),Rt((e.partyResultIcons??[]).map(x=>x.key),"party result icon",n),Rt((e.templatePlaceholders??[]).map(x=>x.key),"template placeholder",n),Rt((e.notificationLetters??[]).map(tq),"notification letter",n),p8(e.notificationLetters??[],n),m8(e.tenant.notificationChrome,n),e.tenant.bankImportScope!==void 0&&!["sepa_only","full_statement"].includes(e.tenant.bankImportScope)&&n.push("tenant.bankImportScope must be sepa_only or full_statement."),e.tenant.hideMailLevelNotice!==void 0&&typeof e.tenant.hideMailLevelNotice!="boolean"&&n.push("tenant.hideMailLevelNotice must be true or false (the dashboard's mail-level notice)."),e.tenant.unassignedTaskNoticeDays!==void 0&&!ND(e.tenant.unassignedTaskNoticeDays)&&n.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."),e.tenant.externalMail!==void 0)for(let x of yM(e.tenant.externalMail))n.push(`tenant.${x}; leave it out for the platform default.`);typeof e.tenant.magicLinkLogin!="boolean"&&n.push("tenant.magicLinkLogin must be true or false (the login page's sign-in link option)."),typeof e.tenant.adminSeesSignatureImages!="boolean"&&n.push("tenant.adminSeesSignatureImages must be true or false (whether a school administrator sees other accounts' signature images)."),typeof e.tenant.signatureStamp!="boolean"&&n.push("tenant.signatureStamp must be true or false (whether the school offers the signature stamp at the countersignature)."),kM(e.tenant.externalSignIn)?n.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" }.`):wM(e.tenant.externalSignIn)||n.push('[auth/externalSignIn] tenant.externalSignIn must be { mode: "oneTimeLink" } (how families sign in).');let o=new Set(e.displayGroups.map(x=>x.key)),a=new Set(e.lists.map(x=>x.key)),l=new Set(e.roles.map(x=>x.key)),d=new Set(e.fields.map(x=>x.key)),c=new Map(e.fields.map(x=>[x.key,x])),u=new Set(e.foundation.legalEntities.map(x=>x.key)),p=new Set(e.foundation.units.map(x=>x.key)),h=new Set(e.foundation.permissionGroups.map(x=>x.key));Jd(e.tenant.enabledModules,"bewerbungsmanagement")&&e.tenant.defaultApplicantGroupKey!==void 0&&(e.foundation.permissionGroups.find(D=>D.key===e.tenant.defaultApplicantGroupKey)?.permissions.includes("bewerbungsmanagement.applications.submitOwn")||n.push(`Default applicant group "${e.tenant.defaultApplicantGroupKey}" must grant submitOwn.`));let y=e.tenant.admissionFieldDisplayGroupKey;y!==void 0&&!o.has(y)&&n.push(`tenant.admissionFieldDisplayGroupKey "${y}" names no display group of this config.`),y===void 0&&(Jd(e.tenant.enabledModules,"bewerbungsmanagement")||(e.admission?.fields.length??0)>0)&&n.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."),n.push(...o8(e)),Rt(e.fields.flatMap(x=>(x.relationshipKinds??[]).map(D=>D.key)),"relationship kind",n);for(let x of e.fields){o.has(x.displayGroupKey)||n.push(`Field "${x.key}" references missing display group "${x.displayGroupKey}".`),a8(x,n),x.formWritable===!0&&!jv[x.type].fieldMapTarget&&n.push(`Field "${x.key}" is formWritable, but a form cannot write a "${x.type}" field.`),x.type==="files"&&x.shareable===!0&&n.push(`[field/filesShareable] Field "${x.key}" is a files field and cannot be shareable.`),x.type==="auto-string"?l8(x,c,n):x.autoString!==void 0&&n.push(`Non-automatic field "${x.key}" must not define autoString.`),(!Number.isFinite(x.sortOrder)||x.sortOrder<0)&&n.push(`Field "${x.key}" has invalid sortOrder "${x.sortOrder}" (must be a non-negative number).`),(x.type==="0-1-select"||x.type==="0-n-select")&&!x.listKey&&n.push(`Select field "${x.key}" must define listKey.`),x.type!=="0-1-select"&&x.type!=="0-n-select"&&x.listKey!==void 0&&n.push(`Non-select field "${x.key}" must not define listKey.`),x.listKey&&!a.has(x.listKey)&&n.push(`Field "${x.key}" references missing list "${x.listKey}".`),(x.type==="object"||x.type==="relationship")&&!x.objectSchema&&n.push(`Field "${x.key}" must define objectSchema.`),x.type!=="object"&&x.type!=="relationship"&&x.objectSchema&&n.push(`Non-object field "${x.key}" must not define objectSchema.`);for(let D of x.objectSchema?.properties??[])(D.type==="0-1-select"||D.type==="0-n-select")&&!D.listKey&&n.push(`Object select property "${x.key}.${D.key}" must define listKey.`),D.listKey&&!a.has(D.listKey)&&n.push(`Object property "${x.key}.${D.key}" references missing list "${D.listKey}".`);s8(x,n)}let b=e.tenant.priceCriteriaFacts;if(b){let x=e.fields.find(D=>D.key===b.birthDateFieldKey);(!x||x.type!=="date")&&n.push("Price criteria require a configured date field for birth dates."),l.has(b.studentRoleKey)||n.push("Price criteria require a configured Student eligibility role."),b.siblingRankSource!==void 0&&b.siblingRankSource!=="derived"&&b.siblingRankSource!=="chosen"&&n.push('Price criteria siblingRankSource must be "derived" or "chosen".');for(let D of Object.keys(b))D!=="birthDateFieldKey"&&D!=="studentRoleKey"&&D!=="siblingRankSource"&&n.push(`Unknown price criteria fact setting "${D}".`)}let k=e.tenant.defaultEnrolleeRoleKey;k&&!l.has(k)&&n.push(`Default enrollment role "${k}" does not exist.`),k&&e.roles.some(x=>x.parentRoleKey===k)&&n.push(`Default enrollment role "${k}" must be a leaf role.`);for(let x of e.roles){(typeof x.icon!="string"||x.icon.trim().length===0)&&n.push(`Role "${x.key}" must define an icon.`),x.parentRoleKey&&!l.has(x.parentRoleKey)&&n.push(`Role "${x.key}" references missing parent role "${x.parentRoleKey}".`);for(let D of x.listDisplayFieldKeys??[])d.has(D)||n.push(`Role "${x.key}" list display references missing field "${D}".`)}let v=new Map(e.roles.map(x=>[x.key,x.parentRoleKey])),A=new Map;for(let x of e.roleFields){let D=A.get(x.roleKey)??[];D.push({roleId:x.roleKey,customFieldId:x.fieldKey}),A.set(x.roleKey,D)}for(let x of e.roles)try{bM(x.key,v,A)}catch(D){n.push(QM(D))}for(let x of e.roleFields){l.has(x.roleKey)||n.push(`Role field references missing role "${x.roleKey}" for field "${x.fieldKey}".`),d.has(x.fieldKey)||n.push(`Role field references missing field "${x.fieldKey}" for role "${x.roleKey}".`);for(let D of x.targetRequirementFieldKeys??[])d.has(D)||n.push(`Role field "${x.roleKey}.${x.fieldKey}" references missing target requirement field "${D}".`)}f8(e.contractRoleMappings??[],l,n);for(let x of e.templatePlaceholders??[])H0.test(x.key)||n.push(`Template placeholder "${x.key}" must use lower_snake_case segments, optionally separated by dots.`),x.source.kind==="customField"?bh(x.source,c,n,`Template placeholder "${x.key}"`):x.source.kind==="relationshipTargetField"&&d8(x,c,n);for(let x of e.searchTargets??[])bh(x,c,n,"Search target");for(let x of e.fields)$M(x.key)&&(x.defaultValue!==void 0||x.validations!==void 0)&&n.push(`System field "${x.key}" takes no defaultValue or validations.`);for(let x of e.lists)if(Rt(x.elements.map((D,R)=>String(D.sortOrder??(R+1)*10)),`sortOrder of an element of list "${x.key}"`,n),x.labelOrder!==void 0){let D=x.labelOrder.last;if(!Array.isArray(D)||D.some(R=>typeof R!="string")){n.push(`[list/labelOrder] List "${x.key}" states labelOrder.last ${JSON.stringify(D??null)} \u2014 a list of element keys.`);continue}Rt(x.labelOrder.last,`labelOrder.last key of list "${x.key}"`,n);for(let R of iC(x.labelOrder,x.elements.map(q=>q.key)))n.push(`[list/labelOrder] List "${x.key}" keeps "${R}" at the end, but has no element "${R}".`)}for(let x of e.searchFilters??[])Rt((x.options??[]).map((D,R)=>String(D.sortOrder??(R+1)*10)),`sortOrder of an option of search filter "${x.key}"`,n);for(let x of e.foundation.permissionGroups){x.grantAllCustomFields===!0&&x.customFieldPermissions!==void 0&&n.push(`Permission group "${x.key}" states both grantAllCustomFields and customFieldPermissions \u2014 one of them.`),Rt((x.customFieldPermissions??[]).map(D=>D.displayGroupKey),`display group of a field permission of group "${x.key}"`,n);for(let D of x.customFieldPermissions??[]){o.has(D.displayGroupKey)||n.push(`Permission group "${x.key}" grants field permissions on missing display group "${D.displayGroupKey}".`);for(let R of D.permissions)AM.includes(R)||n.push(`Permission group "${x.key}" grants unknown field permission "${R}".`)}}let T=e.tenant.partyRetention;T!==void 0&&(RM(T.days)||n.push(`tenant.partyRetention.days must be a whole number of days from 1 to ${36500} (got ${JSON.stringify(T.days)}).`),Number.isFinite(T.enabledAt)||n.push("tenant.partyRetention.enabledAt must be a timestamp (epoch ms)."),T.formerRoleKey!==void 0&&!l.has(T.formerRoleKey)&&n.push(`tenant.partyRetention references missing role "${T.formerRoleKey}".`));for(let x of e.searchFilters??[]){(x.kind==="chips"||x.kind==="select")&&(x.options?.length??0)===0&&n.push(`Search filter "${x.key}" must define options.`),(x.kind==="text"||x.kind==="numberRange")&&x.target===void 0&&n.push(`Search filter "${x.key}" must define a target field.`),x.options!==void 0&&Rt(x.options.map(D=>D.key),`search filter option for "${x.key}"`,n),bh(x.target,c,n,`Search filter "${x.key}"`);for(let D of x.options??[]){D.predicates.length===0&&n.push(`Search filter option "${x.key}.${D.key}" must define at least one predicate.`);for(let R of D.predicates){if(R.kind==="role"){l.has(R.roleKey)||n.push(`Search filter option "${x.key}.${D.key}" references missing role "${R.roleKey}".`);continue}R.kind==="enrollment"?n.push(...GM(R,`${x.key}.${D.key}`)):bh(R,c,n,`Search filter option "${x.key}.${D.key}"`)}}}for(let x of e.partyResultIcons??[])c8(x,c,n);for(let x of e.foundation.legalEntities)if(x.terms!==void 0&&n.push(...Bv(x.terms,`foundation.legalEntities.${x.key}.terms`)),ZM(x.branding,n,`foundation.legalEntities.${x.key}.branding`),XM(x,n,`foundation.legalEntities.${x.key}`),x.signatoryUserKey!==void 0&&x.type==="school_group"&&n.push(`[config/signatoryOnGroup] Legal entity "${x.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) declares an Unterschriftsperson.`),x.parentLegalEntityKey&&!u.has(x.parentLegalEntityKey)&&n.push(`Legal entity "${x.key}" references missing parent "${x.parentLegalEntityKey}".`),x.address!==void 0){let D=x.address,R=["street","hausnr","plz","ort"];x.type==="school_group"?n.push(`Legal entity "${x.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) has an address.`):(typeof D!="object"||D===null||Array.isArray(D)||Object.keys(D).some(q=>!R.includes(q))||R.some(q=>typeof D[q]!="string"||(D[q]??"").trim()===""))&&n.push(`Legal entity "${x.key}" has an invalid address \u2014 expected { street, hausnr, plz, ort }, each non-empty.`)}let I=new Map;for(let x of e.foundation.units){if(x.slug!==void 0){let D=typeof x.slug=="string"?L_(x.slug):"must be a string";D!==void 0&&n.push(`Unit "${x.key}" has invalid slug "${x.slug}" (${D}).`);let R=I.get(x.slug);R!==void 0&&n.push(`Units "${R}" and "${x.key}" both declare slug "${x.slug}" (unit slugs are unique per tenant).`),I.set(x.slug,x.key)}u.has(x.legalEntityKey)||n.push(`Unit "${x.key}" references missing legal entity "${x.legalEntityKey}".`),x.parentUnitKey&&!p.has(x.parentUnitKey)&&n.push(`Unit "${x.key}" references missing parent unit "${x.parentUnitKey}".`),x.sortOrder!==void 0&&(!Number.isFinite(x.sortOrder)||x.sortOrder<0)&&n.push(`Unit "${x.key}" has invalid sortOrder "${x.sortOrder}" (must be a non-negative number).`)}let C=/^[0-9a-f]{32}:[0-9a-f]{128}$/;for(let x of e.foundation.users){h.has(x.permissionGroupKey)||n.push(`User "${x.email}" references missing permission group "${x.permissionGroupKey}".`),x.unitKey&&!p.has(x.unitKey)&&n.push(`User "${x.email}" references missing unit "${x.unitKey}".`),x.status!==void 0&&x.status!=="deactivated"&&n.push(`User "${x.email}": status must be "deactivated" or absent, not "${String(x.status)}".`);let D=[x,...x.additionalMemberships??[]];for(let q of x.additionalMemberships??[])h.has(q.permissionGroupKey)||n.push(`User "${x.email}" references missing permission group "${q.permissionGroupKey}".`),q.unitKey&&!p.has(q.unitKey)&&n.push(`User "${x.email}" references missing unit "${q.unitKey}".`);Rt(D.map(q=>`${q.permissionGroupKey}/${q.unitKey??""}`),`membership (permission group/unit) of user "${x.email}"`,n);for(let q of D)q.validFrom!==void 0&&q.validTo!==void 0&&q.validTo<=q.validFrom&&n.push(`User "${x.email}": membership "${q.permissionGroupKey}" ends (validTo) before it starts (validFrom).`);let R=[x.firstName,x.lastName];R.some(q=>q!==void 0)&&R.some(q=>typeof q!="string"||q.trim()==="")&&n.push(`[config/userNameIncomplete] User "${x.email}" states only part of firstName/lastName (or an empty one) \u2014 set both or neither.`);for(let q of["staging","prod"]){let G=x.passwordHashes?.[q];G!==void 0&&!C.test(G)&&n.push(`User "${x.email}" passwordHashes.${q} is not in Better Auth scrypt format "<32hex>:<128hex>".`)}}ZM(e.tenant.branding,n),XM(e.tenant,n);let L=nq(e.fields.flatMap(x=>x.sourceColumns));for(let x of L)r.push(`Source column "${x}" is mapped by more than one field.`);w8(e,n);let N=t.sourceColumns===void 0||e.source===void 0?void 0:g8(e,t.sourceColumns,n);return{ok:n.length===0,errors:n,warnings:r,coverage:N}}s(eq,"validateTenantConfig");function s8(e,t){let n=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(!_k.includes(i)){t.push(`${o}: addressPart "${i}" is none of ${_k.join(", ")}.`);continue}e.type!=="object"&&t.push(`${o}: only an object field stores an address (addressPart).`),r.type!=="string"&&t.push(`${o}: addressPart "${i}" needs a string property, not "${r.type}".`);let a=n.get(i);a!==void 0&&t.push(`${o}: addressPart "${i}" is already declared by "${e.key}.${a}".`),n.set(i,r.key)}}s(s8,"validateAddressParts");function a8(e,t){let n=e.relationshipKinds;if(n===void 0)return;if(e.type!=="relationship"){t.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 n){let o=`Field "${e.key}" relationship kind "${i.key}"`;if(typeof i.key!="string"||i.key.trim()===""){t.push(`Field "${e.key}": a relationship kind needs a key.`);continue}for(let l of["de","en"])(i.label?.[l]??"").trim()===""&&t.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)){t.push(`${o}: edge must be an object.`);continue}i.sibling!==void 0&&i.sibling!==!0&&t.push(`${o}: sibling must be true or absent.`),i.sibling===!0&&i.mergeInto!==void 0&&t.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare mergeInto.`);let a=n.flatMap(l=>l.mergeInto!==void 0?[l.mergeInto]:[]);if(i.sibling===!0&&a.some(l=>l in i.edge)&&t.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&&t.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"?t.push(`${o}: mergeInto "${i.mergeInto}" must name a 0-n-select property of the field's objectSchema.`):Array.isArray(i.edge[i.mergeInto])||t.push(`${o}: mergeInto "${i.mergeInto}" must be set to a list in the edge.`)}}}s(a8,"validateRelationshipKinds");function l8(e,t,n){if(e.autoString===void 0){n.push(`Automatic field "${e.key}" must define autoString.`);return}e.allowMultiple===!0&&n.push(`Automatic field "${e.key}" must not allow multiple values.`),e.shareable===!0&&n.push(`Automatic field "${e.key}" must not be shareable.`),e.autoString.segments.length===0&&n.push(`Automatic field "${e.key}" must define at least one segment.`),e.autoString.segments.filter(i=>i.kind==="sequence").length!==1&&n.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&&n.push(`Automatic field "${e.key}" has an empty literal segment.`),i.kind==="sequence"&&(i.startAt!==void 0&&(!Number.isInteger(i.startAt)||i.startAt<1)&&n.push(`Automatic field "${e.key}" sequence startAt must be an integer >= 1.`),i.minDigits!==void 0&&(!Number.isInteger(i.minDigits)||i.minDigits<0)&&n.push(`Automatic field "${e.key}" sequence minDigits must be an integer >= 0.`)),i.kind==="field"){let o=t.get(i.fieldKey);if(o===void 0){n.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&&n.push(`Automatic field "${e.key}" references missing object property "${i.fieldKey}.${i.objectPropertyKey}".`)}}s(l8,"validateAutomaticStringField");function bh(e,t,n,r){if(e===void 0)return;let i=t.get(e.fieldKey);if(i===void 0){n.push(`${r} references missing field "${e.fieldKey}".`);return}if(e.objectPropertyKey===void 0)return;(i.objectSchema?.properties.some(a=>a.key===e.objectPropertyKey)??!1)||n.push(`${r} references missing object property "${e.fieldKey}.${e.objectPropertyKey}".`)}s(bh,"validateSearchTarget");function d8(e,t,n){if(e.source.kind!=="relationshipTargetField")return;let r=`Template placeholder "${e.key}"`,i=t.get(e.source.relationshipFieldKey);if(i===void 0)n.push(`${r} references missing relationship field "${e.source.relationshipFieldKey}".`);else if(i.type!=="relationship")n.push(`${r} relationship field "${e.source.relationshipFieldKey}" must be a relationship field.`);else{for(let a of e.source.edgeFilters??[])Yv(i,a.propertyKey,n,`${r} edge filter`);e.source.selection?.sortPropertyKey!==void 0&&Yv(i,e.source.selection.sortPropertyKey,n,`${r} selection sort`)}let o=t.get(e.source.targetFieldKey);if(o===void 0){n.push(`${r} references missing target field "${e.source.targetFieldKey}".`);return}o.type==="relationship"&&n.push(`${r} target field "${e.source.targetFieldKey}" must not be a relationship field.`),e.source.targetObjectPropertyKey!==void 0&&Yv(o,e.source.targetObjectPropertyKey,n,`${r} target`)}s(d8,"validateRelationshipTemplatePlaceholder");function Yv(e,t,n,r){(e.objectSchema?.properties.some(o=>o.key===t)??!1)||n.push(`${r} references missing object property "${e.key}.${t}".`)}s(Yv,"validateObjectPropertyReference");function c8(e,t,n){let r=`Party result icon "${e.key}"`,i=t.get(e.when.fieldKey);if(i===void 0){n.push(`${r} references missing field "${e.when.fieldKey}".`);return}if(e.when.objectPropertyKey===void 0){i.type!=="boolean"&&n.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){n.push(`${r} references missing object property "${e.when.fieldKey}.${e.when.objectPropertyKey}".`);return}o.type!=="boolean"&&n.push(`${r} must target a Boolean field or object property.`)}s(c8,"validatePartyResultIconTarget");function tq(e){return`${e.templateId}:${e.locale}:${e.scopeKey}`}s(tq,"letterIdentity");function u8(e){return`${e.generatorKey??"*"}/${e.partyKind}/${e.roleKey}`}s(u8,"contractRoleMappingIdentity");function f8(e,t,n){let r=new Set;for(let i of e){let o=u8(i),a=`Contract role mapping "${o}"`;Lv.includes(i.partyKind)||n.push(`${a}: partyKind must be one of ${Lv.join(", ")}.`),i.partyKind==="beneficiary"&&n.push(`${a}: a beneficiary holds the enrollee role of the program it attends (programs.enrolleeRoleKey, else tenant.defaultEnrolleeRoleKey) \u2014 remove the mapping.`),t.has(i.roleKey)||n.push(`${a} references missing role "${i.roleKey}".`),i.generatorKey!==void 0&&i.generatorKey.trim()===""&&n.push(`${a}: generatorKey must not be blank \u2014 omit it for the tenant default.`),r.has(o)&&n.push(`${a} is declared twice.`),r.add(o)}}s(f8,"validateContractRoleMappings");function p8(e,t){for(let n of e){let r=`Notification letter "${tq(n)}"`;if(!ph(n.locale)){t.push(`${r} declares locale "${String(n.locale)}" \u2014 letters are written in ${Ge.map(i=>`"${i}"`).join(" and ")} only, so no mail would ever read this deviation.`);continue}if(n.scopeKey!==fh){t.push(`${r} declares scopeKey "${n.scopeKey}" \u2014 the only scope is "${fh}" (the whole school).`);continue}if(Object.keys(n.slots).length===0){t.push(`${r} overrides no block. A deviation that deviates in nothing is not an entry \u2014 remove it.`);continue}if(!ab(n.templateId)){t.push(`${r} references no registered letter \u2014 "${n.templateId}" is not in the letter catalog.`);continue}for(let i of NM(sb(n.templateId),n.slots,n.locale))t.push(`${r}, block "${i.slotKey}" [${i.code}]: ${i.message.de}`)}}s(p8,"validateNotificationLetters");function m8(e,t){if(e!==void 0)for(let n of PM(e))t.push(`Notification chrome: ${n.de}`)}s(m8,"validateNotificationChrome");function ZM(e,t,n){if(e===void 0)return;let r=n===void 0?t:{push:s((...p)=>t.push(...p.map(h=>`${n}: ${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(ZM,"validateBranding");function XM(e,t,n="tenant"){let r=e.brandingAssets;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r)){t.push(`${n}.brandingAssets must be an object keyed by slot (${yh.join(", ")}).`);return}for(let[i,o]of Object.entries(r)){let a=`${n}.brandingAssets.${i}`;if(!yh.includes(i)){t.push(`${a}: unknown slot (expected ${yh.join(", ")}).`);continue}if(typeof o!="object"||o===null){t.push(`${a}: must be { sha256, sizeBytes, mimeType }.`);continue}if("size"in o){t.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}rq.test(o.sha256??"")||t.push(`${a}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(o.sizeBytes)||o.sizeBytes<=0)&&t.push(`${a}: sizeBytes must be a positive integer.`);let l=MM[i];if(l===null){let d=qM({contentType:o.mimeType,size:o.sizeBytes});d!==null&&t.push(`${a}: ${d.de}`)}else{o.mimeType!==zv&&t.push(`${a}: mimeType must be "${zv}" (got "${o.mimeType}").`);let d=KM(e.branding?.fonts?.[l]?.family);d!==null&&t.push(`${a}: [branding/fontFamilyMissing] ${n}.branding.fonts.${l}: ${d.de}`)}"path"in o&&t.push(`${a}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}}s(XM,"validateBrandingAssets");function h8(e,t){let n=e.defaultUnitKey,r=t.map(i=>i.key);return typeof n!="string"||n===""?[`[import/defaultUnitMissing] source "${e.sourceKey}" names no default unit \u2014 set source.defaultUnitKey to one of ${r.join(", ")||"(no units declared)"}.`]:r.includes(n)?[]:[`[import/defaultUnitUnknown] source "${e.sourceKey}" names the default unit "${n}", which is not in foundation.units \u2014 one of ${r.join(", ")||"(no units declared)"}.`]}s(h8,"sourceDefaultUnitFindings");function g8(e,t,n){let{source:r}=e;r===void 0&&F("validateSourceCoverage: called without a `source` block.");let i=new Set(t),o=new Set(e.fields.flatMap(b=>b.sourceColumns)),a=new Set(e.deferredColumns.map(b=>b.column)),l=new Set(e.ignoredColumns.map(b=>b.column)),d=new Set([...o,...a,...l]),c=r.requiredColumns.filter(b=>!i.has(b)),u=t.filter(b=>!d.has(b)),p=[...o].filter(b=>!i.has(b)),h=[...a].filter(b=>!i.has(b)),y=[...l].filter(b=>!i.has(b));for(let b of c)n.push(`Required source column "${b}" is missing from ${r.primaryTable}.`);for(let b of u)n.push(`Source column "${b}" is neither mapped nor explicitly deferred/ignored.`);for(let b of p)n.push(`Mapped source column "${b}" does not exist in the source schema.`);for(let b of h)n.push(`Deferred source column "${b}" does not exist in the source schema.`);for(let b of y)n.push(`Ignored source column "${b}" does not exist in the source schema.`);return{table:r.primaryTable,availableColumns:t.length,mappedColumns:[...o].filter(b=>i.has(b)).length,deferredColumns:[...a].filter(b=>i.has(b)).length,ignoredColumns:[...l].filter(b=>i.has(b)).length,missingRequiredColumns:c,unmappedColumns:u,unknownMappedColumns:p,unknownDeferredColumns:h,unknownIgnoredColumns:y}}s(g8,"validateSourceCoverage");function Rt(e,t,n){for(let r of nq(e))n.push(`Duplicate ${t} key "${r}".`)}s(Rt,"requireUnique");function nq(e){let t=new Set,n=new Set;for(let r of e)t.has(r)&&n.add(r),t.add(r);return[...n]}s(nq,"duplicates");var rq=/^[0-9a-f]{64}$/,y8=["fileName","size"];function w8(e,t){if(!Array.isArray(e.files)){t.push('"files" is missing \u2014 declare the file library (an empty list is fine).');return}Rt(e.files.map(n=>n.key),"file",t);for(let n of e.files){let r=`files["${n.key}"]`;Za(n.key)||t.push(`${r}: key must match ${pv}.`);for(let o of["de","en"])(n.label?.[o]??"").trim()===""&&t.push(`${r}: label.${o} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);let i=y8.filter(o=>o in n);if(i.length>0){t.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 n.filename!="string")t.push(`${r}: filename is missing.`);else{let o=As(n.filename);o!==null&&t.push(`${r}: filename ${o}.`)}gh.includes(n.mimeType)||t.push(`${r}: mimeType "${n.mimeType}" is not allowed (${gh.join(", ")}).`),rq.test(n.sha256??"")||t.push(`${r}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(n.sizeBytes)||n.sizeBytes<=0)&&t.push(`${r}: sizeBytes must be a positive integer.`),"path"in n&&t.push(`${r}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}s(w8,"validateFiles");var k8=new WeakMap,b8=new WeakSet;function Hv(e,t){t(e);let r=e.asOptional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>Hv(r(),t),"value"),enumerable:!1}),e}s(Hv,"carry");function ol(e,t){return Hv(e,n=>k8.set(n,t))}s(ol,"tagged");var v8="tenant teardown drains every table explicitly (config/wipe.ts)",ze={belongsTo:s(e=>ol(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>ol(e,{kind:"owns"}),"owns"),holds:s(e=>ol(e,{kind:"holds"}),"holds"),restrict:s((e,t)=>ol(e,t?{kind:"restrict",unindexed:t.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>ol(e,{kind:"history"}),"history"),tenant:s(e=>ol(e,{kind:"restrict",unindexed:v8}),"tenant"),historyOf:s(e=>Hv(e,t=>b8.add(t)),"historyOf")};var x8=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string()}),iq=m.union(m.literal("school_operator"),m.literal("school_group"),m.literal("service_entity")),mi=iq.members.map(e=>e.value),S8={tenantId:ze.tenant(m.id("tenants")),name:m.optional(m.string()),type:iq,parentLegalEntityId:m.optional(ze.restrict(m.id("legal_entities"))),configKey:m.optional(m.string()),partyId:m.optional(ze.restrict(m.id("parties"))),address:m.optional(x8),signatoryUserId:m.optional(ze.restrict(m.id("users"))),terms:m.optional(OM)},L_e=Gn(S8).index("by_tenantId",["tenantId"]).index("by_parentLegalEntityId",["parentLegalEntityId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_partyId",["partyId"]).index("by_signatoryUserId",["signatoryUserId"]);var A8=m.union(m.literal("school"),m.literal("kindergarten"),m.literal("after_school_care"),m.literal("department"),m.literal("site"),m.literal("other")),Xn=A8.members.map(e=>e.value),K_e=m.union(m.literal("school"),m.literal("vocational"),m.literal("care"),m.literal("seminar"),m.literal("other")),j_e=m.union(m.literal("none"),m.literal("manual"),m.literal("annual_rollover")),V_e=m.union(m.literal("grade_level"),m.literal("module"),m.literal("phase"),m.literal("other")),B_e=m.union(m.literal("school_year"),m.literal("cohort"),m.literal("seminar"),m.literal("care_period"),m.literal("other")),U_e=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("archived")),G_e=m.union(m.literal("class"),m.literal("course"),m.literal("care_group"),m.literal("seminar_group"),m.literal("mixed_age_group"),m.literal("other")),z_e=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("cancelled")),W_e=m.union(m.literal("class_teacher"),m.literal("teacher"),m.literal("mentor"),m.literal("instructor"),m.literal("assistant"),m.literal("other")),Y_e=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")),H_e=m.union(m.literal("open"),m.literal("mapped"),m.literal("ignored"));function sq(e){let t=["street","hausnr","plz","ort"].filter(n=>e[n]!==void 0);if(t.length!==0){if(t.length!==4)throw new g(`config legal-entity add: an address needs all of --street, --hausnr, --plz and --ort (got ${t.map(n=>`--${n}`).join(", ")})`);return{street:e.street,hausnr:e.hausnr,plz:e.plz,ort:e.ort}}}s(sq,"addressFrom");function aq(e){if(!mi.includes(e))throw new g(`config legal-entity add: --type "${e}" is none of ${mi.join(", ")}`);return e}s(aq,"legalEntityType");function lq(e){if(!Xn.includes(e))throw new g(`config unit add: --kind "${e}" is none of ${Xn.join(", ")}`);return e}s(lq,"unitKind");function dq(e,t,n){let r=e.find(i=>i.key===t.key);if(r===void 0)return e.push(t),"create";if(Ce(r)===Ce(t))return"same";throw new g(`${n} "${t.key}" already exists with other values \u2014 decide by hand, nothing written.
11792
11792
  in the file: ${JSON.stringify(r)}
11793
11793
  requested: ${JSON.stringify(t)}`)}s(dq,"addRow");function oq(e){return new Set(eq(e).errors)}s(oq,"findings");function cq(e,t){let n=s(()=>Be(e,"config"),"read"),r=n();if(typeof r!="object"||r===null||typeof r.foundation!="object")throw new g(`config: ${e} is no exported tenant config (no "foundation" block) \u2014 export one with \`config export --out <file>\``);let i=oq(r),o=n(),a=t(o),l=[...oq(o)].filter(d=>!i.has(d));if(l.length>0)throw new g(`config: the edit is refused by the config validator, nothing written:
11794
11794
  ${l.join(`
@@ -11812,7 +11812,7 @@ The Plexus team`}},kQ={de:{...Qd.de,closing:null},en:{...Qd.en,closing:null}};va
11812
11812
  `)+`\r
11813
11813
  `}s(j8,"linksCsv");function V8(e,t){if(e.to===void 0==(e.from===void 0))throw new g("demo link create: give exactly one of --to <name> or --from <recipients.csv>.");if(e.from!==void 0){if(e.email!==void 0)throw new g("demo link create: --email goes with --to, not --from.");return q8(M8(t(e.from),e.from))}return[{name:e.to,...e.email!==void 0?{email:e.email}:{}}]}s(V8,"recipientsOf");async function B8(e,t,n=r=>C8(r)){return await e.mutation(S.demoLinks.createLinks,{recipients:V8(t,n),...t.video!==void 0?{videoId:t.video}:{},...t.campaign!==void 0?{campaign:t.campaign}:{},...t.note!==void 0?{note:t.note}:{}})}s(B8,"createLinksRun");async function Iq(e,t){let{rows:n}=await dp(e,S.demoLinks.listLinks,t===void 0?{}:{campaign:t},{pageSize:200});return n}s(Iq,"allLinks");function Rx(e){return e.map(t=>({empf\u00E4nger:t.recipientName,email:t.recipientEmail??"\u2014",video:t.videoId??"(alle)",kampagne:t.campaign??"\u2014",url:t.url,...t.revokedAt!==void 0?{widerrufen:kx(t.revokedAt)}:{}}))}s(Rx,"linkRows");function U8(e){return e.pages.length===0?"\u2014":e.pages.map(t=>`${Eq(t.path).de} ${Th(t.activeSeconds)} (${t.views}\xD7)`).join(" \xB7 ")}s(U8,"pagesText");function G8(e){return e.flatMap(t=>{let n={empf\u00E4nger:t.recipientName,code:t.code,besuche:String(t.visits),erster:kx(t.firstVisitAt),letzter:kx(t.lastVisitAt),seiten:U8(t)};return t.videos.length===0?[{...n,video:t.videoId??"\u2014",gesehen:"\u2014","%":"\u2014"}]:t.videos.map(r=>({...n,video:r.videoId,gesehen:`${Th(r.watchedSeconds)} / ${Th(r.durationSeconds)}`,"%":`${r.percent} %`}))})}s(G8,"statsRows");var bx=class extends P{static{s(this,"DemoVideosCommand")}static paths=[["demo","videos"]];static usage=E.Usage({category:"Marketing",description:"List the demo video catalogue (the ids a demo link can point at).",examples:[["List the videos","plexus-cli demo videos"]]});async execute(){let n=await(await this.caller()).query(S.demoLinks.listVideos,{});return this.print(n,r=>r.map(i=>({id:i.id,datum:i.date,titel:i.title.de,dauer:Th(i.durationSeconds)})),["id","datum","titel","dauer"]),0}},vx=class extends P{static{s(this,"DemoLinkCreateCommand")}static paths=[["demo","link","create"]];static usage=E.Usage({category:"Marketing",description:"Create personalised demo video links (one recipient, or a CSV). Needs _platform.demoLinks.manage.",details:`Each link belongs to one named recipient and, with --video, jumps to that video; without it the link opens the whole page. A visit counts once the page was visible for 5 s or the visitor interacted \u2014 a mail scanner that only fetches the link does not count. --from reads a UTF-8 CSV ("," or ";") with a header row: name, optional email (or E-Mail), optional video (a row's video wins over --video). The batch is created all or nothing. --out writes the links as a ";" CSV that German Excel opens directly.`,examples:[["One recipient, one video",'plexus-cli demo link create --to "Erika Mustermann" --video vorlagen --env prod --allow-prod'],["A CSV batch, result as CSV","plexus-cli demo link create --from recipients.csv --campaign herbst --out links.csv --env prod --allow-prod"]]});to=f.String("--to",{description:"The recipient's name."});email=f.String("--email",{description:"The recipient's email address (with --to)."});from=f.String("--from",{description:"UTF-8 CSV of recipients: name, email, video."});video=f.String("--video",{description:"Video id (see `demo videos`); without it the whole page."});campaign=f.String("--campaign",{description:"Campaign label, to list and count links together."});note=f.String("--note",{description:"Free note kept with the links."});out=f.String("--out",{description:"Also write the created links as CSV to this file (refused when it exists, unless --force)."});force=xt();async execute(){let t=this.out===void 0?void 0:Vt(this.out,this.force),n=await this.caller(),r=await B8(n,{to:this.to,email:this.email,from:this.from,video:this.video,campaign:this.campaign,note:this.note});return this.print(r,Rx,["empf\xE4nger","email","video","kampagne","url"]),t!==void 0&&D8(t,j8(r)),0}},xx=class extends P{static{s(this,"DemoLinkListCommand")}static paths=[["demo","link","list"]];static usage=E.Usage({category:"Marketing",description:"List demo links, newest first. Needs _platform.demoLinks.manage."});campaign=f.String("--campaign",{description:"Only this campaign."});async execute(){let t=await this.caller();return this.print(await Iq(t,this.campaign),Rx,["empf\xE4nger","email","video","kampagne","url","widerrufen"]),0}},Sx=class extends P{static{s(this,"DemoLinkStatsCommand")}static paths=[["demo","link","stats"]];static usage=E.Usage({category:"Marketing",description:"Who opened their demo link, when, how often, how long per video and per demo page. Needs _platform.demoLinks.manage.",details:"besuche = page loads a person engaged with (visible 5 s or an interaction); erster/letzter = first and latest visit (Europe/Berlin); gesehen = seconds actually played, summed over visits, / video length; % = how much of the video the best single visit actually played (skipping ahead does not count); seiten = per demo page the time it was visible, summed over visits (mm:ss), and how many visits viewed it \u2014 a page counts after 5 s visible or an interaction there.",examples:[["One link","plexus-cli demo link stats k7m2q9xdp3ab --env prod"],["A campaign","plexus-cli demo link stats --campaign herbst --env prod"]]});code=f.String({required:!1,name:"code"});campaign=f.String("--campaign",{description:"Only this campaign (not together with a code)."});async execute(){if(this.code!==void 0&&this.campaign!==void 0)throw new g("demo link stats: either a code or --campaign, not both.");let t=await this.caller(),n=this.code===void 0?await Iq(t,this.campaign):[await t.query(S.demoLinks.getLink,{code:this.code})];return this.print(n,G8,["empf\xE4nger","code","video","besuche","erster","letzter","seiten","gesehen","%"]),0}},Ax=class extends P{static{s(this,"DemoLinkRevokeCommand")}static paths=[["demo","link","revoke"]];static usage=E.Usage({category:"Marketing",description:"Stop recording for a demo link \u2014 plan unless --confirm; the page keeps working and its statistics stay. Needs _platform.demoLinks.manage."});code=f.String({required:!0,name:"code"});confirm=f.Boolean("--confirm",!1,{description:"Revoke (without it, only the plan is printed)."});async execute(){let t=await this.caller();if(!this.confirm){let r=await t.query(S.demoLinks.getLink,{code:this.code});return this.context.stdout.write(`Would stop recording for the link of ${r.recipientName} (${r.code}). Re-run with --confirm.
11814
11814
  `),0}let n=await t.mutation(S.demoLinks.revokeLink,{code:this.code});return this.print([n],Rx,["empf\xE4nger","video","url","widerrufen"]),0}},Tx=class extends P{static{s(this,"DemoLinkDeleteCommand")}static paths=[["demo","link","delete"]];static usage=E.Usage({category:"Marketing",description:"Erase a demo link: the recipient's name and address and everything recorded for it. Needs _platform.demoLinks.manage.",details:"Without --confirm it only shows what would be deleted. The deletion cannot be undone; the page keeps working for anyone who still has the link, and records nothing.",examples:[["Erase on request","plexus-cli demo link delete k7m2q9xdp3ab --confirm --env prod --allow-prod"]]});code=f.String({required:!0,name:"code"});confirm=f.Boolean("--confirm",!1,{description:"Really delete."});async execute(){let t=await this.caller();if(!this.confirm){let r=await t.query(S.demoLinks.getLink,{code:this.code});return this.context.stdout.write(`Would delete the link of ${r.recipientName} (${r.code}) with ${r.visits} visit(s). Re-run with --confirm.
11815
- `),0}let n=await t.mutation(S.demoLinks.deleteLink,{code:this.code});return this.print(n,r=>[{gel\u00F6scht:r.code,empf\u00E4nger:r.recipientName}]),0}},Oq=[bx,vx,xx,Sx,Ax,Tx];var Is=["offen","todo","bearbeitung","klaerung","abgeschlossen","spaeter"],z8=m.union(m.literal("offen"),m.literal("todo"),m.literal("bearbeitung"),m.literal("klaerung"),m.literal("abgeschlossen"),m.literal("spaeter")),W8=z8,Y8=m.union(m.literal("open"),m.literal("closed")),H8=m.union(m.literal("completed"),m.literal("not_planned"),m.literal("reopened"),m.literal("duplicate"),m.null()),J8=m.object({repo:m.string(),number:m.number(),url:m.string(),state:Y8,stateReason:m.optional(H8),linkedAt:m.number(),lastSyncedAt:m.number()}),Q8=m.object({pathname:m.string(),search:m.string(),hash:m.string(),pageTitle:m.string(),selectedUnit:m.optional(m.object({id:m.string(),unitId:m.optional(ze.history(m.id("units"))),label:m.string(),kind:m.union(m.literal("tenant"),m.literal("unit"))})),viewport:m.object({width:m.number(),height:m.number(),devicePixelRatio:m.number()}),locale:m.string(),timezone:m.string()}),Z8={tenantId:ze.tenant(m.id("tenants")),userId:ze.history(m.id("users")),summary:m.string(),situation:m.optional(m.string()),goal:m.optional(m.string()),needToSee:m.optional(m.string()),needToDo:m.optional(m.string()),reason:m.optional(m.string()),currentWorkaround:m.optional(m.string()),status:W8,boardRank:m.number(),context:Q8,screenshotStorageId:m.optional(ze.owns(m.id("_storage"))),githubIssue:m.optional(J8),githubIssueKey:m.optional(m.string()),deadline:m.optional(m.number()),assigneeUserId:m.optional(ze.restrict(m.id("users"),{unindexed:"only by_status_and_assignee, which leads with status"})),lastActivityAt:m.number(),openReplaySessionURL:m.optional(m.string())},SPe=Gn(Z8).index("by_tenantId",["tenantId"]).index("by_tenantId_and_userId",["tenantId","userId"]).index("by_tenantId_and_status",["tenantId","status"]).index("by_github_issue",["githubIssueKey"]).index("by_status_and_rank",["status","boardRank"]).index("by_tenantId_and_status_and_rank",["tenantId","status","boardRank"]).index("by_tenantId_and_userId_and_status",["tenantId","userId","status"]).index("by_status_and_deadline",["status","deadline"]).index("by_status_and_assignee",["status","assigneeUserId"]).index("by_screenshotStorageId",["screenshotStorageId"]);import*as Rh from"node:child_process";function _q(e){return new Proxy(e,{apply(t,n,r){if(mt())throw new Error("plexus: this command requires a local machine and cannot run in a platform chat.");return Reflect.apply(t,n,r)}})}s(_q,"localOnly");var Nq=_q(Rh.spawnSync),$x=_q(Rh.execFileSync);var Ex="SmartKomm/plexus",Cq="feedback",$h=["bug","feature","task"],X8={bug:"d73a4a",feature:"0e8a16",task:"1d76db"};function Eh(e){return Math.trunc(e.number)}s(Eh,"issueNumber");function Dq(...e){try{return $x("gh",e,{encoding:"utf8"}).trim()}catch(t){throw Lt(t,n=>`gh ${e.join(" ")} failed: ${n}`)}}s(Dq,"gh");function Ix(e){try{return{ok:!0,stdout:$x("gh",e,{encoding:"utf8"}),stderr:""}}catch(t){let n=t;return{ok:!1,stdout:n.stdout?.toString()??"",stderr:n.stderr?.toString()??""}}}s(Ix,"ghRaw");function Fq(e,t){let n=(e||"").toUpperCase()==="CLOSED"?"closed":"open",r={COMPLETED:"completed",NOT_PLANNED:"not_planned",REOPENED:"reopened"}[(t||"").toUpperCase()];return{state:n,reason:r}}s(Fq,"mapGhState");async function Lq(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} ${t.statusText}`);return{bytes:new Uint8Array(await t.arrayBuffer()),contentType:t.headers.get("content-type")}}catch(t){throw Lt(t,n=>`Could not download feedback screenshot: ${n}`)}}s(Lq,"downloadScreenshot");function Mq(e,t,n){let{screenshotUrl:r,noScreenshot:i}=n;if(r!==void 0&&i)throw new g("Pass either --screenshot-url or --no-screenshot, not both.");if(!t){if(r!==void 0)throw new g(`Feedback ${e} has no screenshot \u2014 drop --screenshot-url.`);return null}if(i)return null;if(r===void 0)throw new g(`Feedback ${e} has a screenshot. Save it with \`plexus-cli feedback screenshot ${e} --out <file>\`, upload it with your environment's upload tool as an EXPIRING (presigned) link \u2014 feedback screenshots can show customer data \u2014 and pass --screenshot-url <url>. Or file without it: --no-screenshot.`);let o;try{o=new URL(r)}catch{throw new g(`--screenshot-url is not a URL: ${JSON.stringify(r)}`)}if(o.protocol!=="https:")throw new g(`--screenshot-url must be https: ${JSON.stringify(r)}`);return o.href}s(Mq,"screenshotForIssue");function qq(e){let t=new URL(e),n=t.hostname.split("."),r=n.indexOf("db");if(r===-1)throw new g(`Cannot derive the app URL from convexUrl ${JSON.stringify(e)} (expected a 'db.' host label).`);return n.splice(r,1),`${t.protocol}//${n.join(".")}`}s(qq,"appBaseUrl");function Kq(e,t,n){return`${e}/${t}/feedback?item=${encodeURIComponent(n)}`}s(Kq,"feedbackItemUrl");function eZ(e){let t=(e.name??"").trim(),n=(e.email??"").trim();return t&&n&&t!==n?`${t} (${n})`:n||t}s(eZ,"reportedBy");function Pq(e){return(e||"").split(`
11815
+ `),0}let n=await t.mutation(S.demoLinks.deleteLink,{code:this.code});return this.print(n,r=>[{gel\u00F6scht:r.code,empf\u00E4nger:r.recipientName}]),0}},Oq=[bx,vx,xx,Sx,Ax,Tx];var Is=["offen","todo","bearbeitung","klaerung","abgeschlossen","spaeter"],z8=m.union(m.literal("offen"),m.literal("todo"),m.literal("bearbeitung"),m.literal("klaerung"),m.literal("abgeschlossen"),m.literal("spaeter")),W8=z8,Y8=m.union(m.literal("open"),m.literal("closed")),H8=m.union(m.literal("completed"),m.literal("not_planned"),m.literal("reopened"),m.literal("duplicate"),m.null()),J8=m.object({repo:m.string(),number:m.number(),url:m.string(),state:Y8,stateReason:m.optional(H8),linkedAt:m.number(),lastSyncedAt:m.number()}),Q8=m.object({pathname:m.string(),search:m.string(),hash:m.string(),pageTitle:m.string(),selectedUnit:m.optional(m.object({id:m.string(),unitId:m.optional(ze.history(m.id("units"))),label:m.string(),kind:m.union(m.literal("tenant"),m.literal("unit"))})),viewport:m.object({width:m.number(),height:m.number(),devicePixelRatio:m.number()}),locale:m.string(),timezone:m.string()}),Z8={tenantId:ze.tenant(m.id("tenants")),userId:ze.history(m.id("users")),summary:m.string(),situation:m.optional(m.string()),goal:m.optional(m.string()),needToSee:m.optional(m.string()),needToDo:m.optional(m.string()),reason:m.optional(m.string()),currentWorkaround:m.optional(m.string()),status:W8,boardRank:m.number(),context:Q8,screenshotStorageId:m.optional(ze.owns(m.id("_storage"))),githubIssue:m.optional(J8),githubIssueKey:m.optional(m.string()),deadline:m.optional(m.number()),assigneeUserId:m.optional(ze.restrict(m.id("users"),{unindexed:"only by_status_and_assignee, which leads with status"})),lastActivityAt:m.number(),openReplaySessionURL:m.optional(m.string())},APe=Gn(Z8).index("by_tenantId",["tenantId"]).index("by_tenantId_and_userId",["tenantId","userId"]).index("by_tenantId_and_status",["tenantId","status"]).index("by_github_issue",["githubIssueKey"]).index("by_status_and_rank",["status","boardRank"]).index("by_tenantId_and_status_and_rank",["tenantId","status","boardRank"]).index("by_tenantId_and_userId_and_status",["tenantId","userId","status"]).index("by_status_and_deadline",["status","deadline"]).index("by_status_and_assignee",["status","assigneeUserId"]).index("by_screenshotStorageId",["screenshotStorageId"]);import*as Rh from"node:child_process";function _q(e){return new Proxy(e,{apply(t,n,r){if(mt())throw new Error("plexus: this command requires a local machine and cannot run in a platform chat.");return Reflect.apply(t,n,r)}})}s(_q,"localOnly");var Nq=_q(Rh.spawnSync),$x=_q(Rh.execFileSync);var Ex="SmartKomm/plexus",Cq="feedback",$h=["bug","feature","task"],X8={bug:"d73a4a",feature:"0e8a16",task:"1d76db"};function Eh(e){return Math.trunc(e.number)}s(Eh,"issueNumber");function Dq(...e){try{return $x("gh",e,{encoding:"utf8"}).trim()}catch(t){throw Lt(t,n=>`gh ${e.join(" ")} failed: ${n}`)}}s(Dq,"gh");function Ix(e){try{return{ok:!0,stdout:$x("gh",e,{encoding:"utf8"}),stderr:""}}catch(t){let n=t;return{ok:!1,stdout:n.stdout?.toString()??"",stderr:n.stderr?.toString()??""}}}s(Ix,"ghRaw");function Fq(e,t){let n=(e||"").toUpperCase()==="CLOSED"?"closed":"open",r={COMPLETED:"completed",NOT_PLANNED:"not_planned",REOPENED:"reopened"}[(t||"").toUpperCase()];return{state:n,reason:r}}s(Fq,"mapGhState");async function Lq(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} ${t.statusText}`);return{bytes:new Uint8Array(await t.arrayBuffer()),contentType:t.headers.get("content-type")}}catch(t){throw Lt(t,n=>`Could not download feedback screenshot: ${n}`)}}s(Lq,"downloadScreenshot");function Mq(e,t,n){let{screenshotUrl:r,noScreenshot:i}=n;if(r!==void 0&&i)throw new g("Pass either --screenshot-url or --no-screenshot, not both.");if(!t){if(r!==void 0)throw new g(`Feedback ${e} has no screenshot \u2014 drop --screenshot-url.`);return null}if(i)return null;if(r===void 0)throw new g(`Feedback ${e} has a screenshot. Save it with \`plexus-cli feedback screenshot ${e} --out <file>\`, upload it with your environment's upload tool as an EXPIRING (presigned) link \u2014 feedback screenshots can show customer data \u2014 and pass --screenshot-url <url>. Or file without it: --no-screenshot.`);let o;try{o=new URL(r)}catch{throw new g(`--screenshot-url is not a URL: ${JSON.stringify(r)}`)}if(o.protocol!=="https:")throw new g(`--screenshot-url must be https: ${JSON.stringify(r)}`);return o.href}s(Mq,"screenshotForIssue");function qq(e){let t=new URL(e),n=t.hostname.split("."),r=n.indexOf("db");if(r===-1)throw new g(`Cannot derive the app URL from convexUrl ${JSON.stringify(e)} (expected a 'db.' host label).`);return n.splice(r,1),`${t.protocol}//${n.join(".")}`}s(qq,"appBaseUrl");function Kq(e,t,n){return`${e}/${t}/feedback?item=${encodeURIComponent(n)}`}s(Kq,"feedbackItemUrl");function eZ(e){let t=(e.name??"").trim(),n=(e.email??"").trim();return t&&n&&t!==n?`${t} (${n})`:n||t}s(eZ,"reportedBy");function Pq(e){return(e||"").split(`
11816
11816
  `).map(t=>`> ${t}`).join(`
11817
11817
  `)}s(Pq,"blockquote");function jq(e,t){let n=`type:${t}`;return Ix(["label","create",n,"--repo",e,"--force","--color",X8[t]]),n}s(jq,"ensureTypeLabel");function Vq(e){return`[${e.tags?.[0]?.name||"feedback"}] ${(e.summary||"").slice(0,80)}`}s(Vq,"issueTitle");function Bq(e,t,n){let r=["## Feedback",n,"",`Mandant **${e.tenantSlug}**`,`Gemeldet von: ${eZ(e.submittedBy??{})}`,"","## Beschreibung",Pq(e.summary??"")],i=[["Situation","situation"],["Ziel","goal"],["Ben\xF6tigte Information","needToSee"],["Ben\xF6tigte Aktion","needToDo"],["Grund","reason"],["Aktueller Workaround","currentWorkaround"]];for(let[o,a]of i){let l=e[a];typeof l=="string"&&l.length>0&&r.push("",`## ${o}`,Pq(l))}return t&&r.push("","## Screenshot",`![screenshot](${t})`),r.filter(o=>o!==null).join(`
11818
11818
  `)}s(Bq,"issueBody");function ec(e){if(/^\d+$/.test(e))return Number.parseInt(e,10);let t=Date.parse(e);if(Number.isNaN(t))throw new g(`Invalid date ${JSON.stringify(e)} \u2014 use ISO (e.g. 2026-06-20) or epoch ms.`);return t}s(ec,"parseDateMs");async function Ih(e,t){if(t==="@me"||t==="me")return(await e.query(S.platformFeedback.whoAmI,{})).userId;if(!t.includes("@"))return ee(t,"user");let r=(await e.query(S.platformFeedback.listPlatformAdmins,{})).find(i=>i.email.toLowerCase()===t.toLowerCase());if(r===void 0)throw new g(`No platform admin with email ${JSON.stringify(t)}.`);return r.userId}s(Ih,"resolveAssigneeUserId");var tc=class extends P{static{s(this,"FeedbackListCommand")}static paths=[["feedback","list"]];static usage=E.Usage({category:"Feedback",description:"List feedback (active tenant, or --all-tenants for a platform admin)."});limit=f.String("--limit",{description:"Max rows (default 50)."});fetchAll=f.Boolean("--all",!1,{description:"Fetch every page."});allTenants=f.Boolean("--all-tenants",!1,{description:"Cross-tenant platform view (requires _platform.feedback.read)."});status=f.String("--status",{description:`Filter by status (${Is.join("|")}).`});withIssues=f.Boolean("--with-issues",!1,{description:"Only items linked to a GitHub issue."});withoutIssues=f.Boolean("--without-issues",!1,{description:"Only items NOT yet linked to a GitHub issue."});text=f.String("--text",{description:"Filter: summary or submitter name/email contains this text."});tagIds=f.Array("--tag",{description:"Filter: item carries any of these tag ids (repeatable)."});assignee=f.String("--assignee",{description:"Filter: assignee @me, userId, or email (platform; needs --all-tenants)."});deadlineFrom=f.String("--deadline-from",{description:"Filter: deadline >= ISO/epoch (platform; needs --all-tenants)."});deadlineTo=f.String("--deadline-to",{description:"Filter: deadline <= ISO/epoch (platform; needs --all-tenants)."});async execute(){let t=await this.caller(),n=this.limit===void 0?50:Number.parseInt(this.limit,10);if(Number.isNaN(n))throw new g(`feedback list: --limit must be an integer, got "${this.limit}".`);let r=this.fetchAll?void 0:n,i=this.assignee||this.deadlineFrom||this.deadlineTo;if(!this.allTenants){if(this.withIssues||this.withoutIssues||i)throw new g("--with-issues/--without-issues/--assignee/--deadline-* require --all-tenants (the GitHub link, assignee and deadline are platform-admin-only).");let d=this.requireTenant(t),c=await this.paginate(t,S.feedback.listTenant,{client:d},{max:r});return c=this.applyTextTagFilter(c),this.print(c),0}let o=this.parseStatus(),a={};o!==void 0&&(a.status=o),this.text!==void 0&&(a.text=this.text),this.tagIds&&this.tagIds.length>0&&(a.tagIds=this.tagIds),this.assignee!==void 0&&(a.assigneeUserId=await Ih(t,this.assignee)),this.deadlineFrom!==void 0&&(a.deadlineFrom=ec(this.deadlineFrom)),this.deadlineTo!==void 0&&(a.deadlineTo=ec(this.deadlineTo));let l=await this.paginate(t,S.platformFeedback.listAllPlatform,a,{max:r});return this.withIssues&&(l=l.filter(d=>d.githubIssue)),this.withoutIssues&&(l=l.filter(d=>!d.githubIssue)),this.print(l,d=>d.map(tZ),["id","tenant","status","tags","summary","issue","resolved"]),0}applyTextTagFilter(t){let n=this.text?.trim().toLowerCase(),r=this.tagIds&&this.tagIds.length>0?new Set(this.tagIds):null;return t.filter(i=>!(n&&!`${i.summary??""} ${i.submittedBy?.name??""} ${i.submittedBy?.email??""}`.toLowerCase().includes(n)||r&&!(i.tags??[]).some(o=>r.has(o.id))))}parseStatus(){if(this.status!==void 0){if(!Is.includes(this.status))throw new g(`feedback list: --status must be one of ${Is.join("|")}.`);return this.status}}};function tZ(e){let t=e.githubIssue;return{id:e.id,tenant:e.tenantSlug,status:e.status,tags:(e.tags??[]).map(n=>n.name).join(", "),summary:(e.summary??"").slice(0,50),issue:t?`#${Eh(t)} (${t.state})`:"",resolved:e.resolved?"\u2713":""}}s(tZ,"platformRow");var nc=class extends P{static{s(this,"FeedbackToIssueCommand")}static paths=[["feedback","to-issue"]];static usage=E.Usage({category:"Feedback",description:"Create + link a GitHub issue for a feedback item (idempotent)."});feedbackId=f.String({required:!0,name:"feedbackId"});repo=f.String("--repo",Ex,{description:`Default ${Ex}.`});issueType=f.String("--type",{description:`Triage type (${$h.join("|")}) \u2014 added as a 'type:<t>' label.`});dryRun=f.Boolean("--dry-run",!1,{description:"Render the issue without creating it."});screenshotUrl=f.String("--screenshot-url",{description:"Hosted (expiring) link to the item's screenshot \u2014 required when the item has one. Save it with `feedback screenshot <id> --out <file>` first."});noScreenshot=f.Boolean("--no-screenshot",!1,{description:"File an item that has a screenshot without it."});async execute(){let t=await this.caller(),n=ee(this.feedbackId,"feedback item"),r=await t.query(S.platformFeedback.getById,{feedbackItemId:n}),i=r.githubIssue;if(i&&!this.dryRun)return this.print({feedbackId:this.feedbackId,issue:i.url,alreadyLinked:!0},k=>[{field:"feedbackId",value:k.feedbackId},{field:"issue",value:k.issue},{field:"alreadyLinked",value:"\u2713"}]),0;if(this.issueType!==void 0&&!$h.includes(this.issueType))throw new g(`Invalid --type ${JSON.stringify(this.issueType)} \u2014 expected one of ${$h.join("|")}.`);let o=this.issueType,a=Vq(r),l=Kq(qq(t.convexUrl),r.tenantSlug,this.feedbackId),d=[Cq,...o?[`type:${o}`]:[]],c=Mq(this.feedbackId,!!r.screenshotUrl,{screenshotUrl:this.screenshotUrl,noScreenshot:this.noScreenshot}),u=Bq(r,c,l);if(this.dryRun)return this.print({repo:this.repo,title:a,labels:d,hasScreenshot:!!r.screenshotUrl,screenshotUrl:c,body:u}),0;o&&jq(this.repo,o);let p=d.flatMap(k=>["--label",k]),h=Dq("issue","create","--repo",this.repo,"--title",a,...p,"--body",u);if(!h.startsWith("https://github.com/"))throw new Error(`Unexpected gh output (not an issue URL): ${JSON.stringify(h)}`);let y=Number.parseInt(h.replace(/\/+$/,"").split("/").pop()??"",10);if(Number.isNaN(y))throw new Error(`Could not parse issue number from gh output: ${JSON.stringify(h)}`);let b=await t.mutation(S.platformFeedback.attachGithubIssue,{feedbackItemId:n,repo:this.repo,number:y,url:h,state:"open"});return this.print({feedbackId:this.feedbackId,issue:h,link:b},k=>[{field:"feedbackId",value:k.feedbackId},{field:"issue",value:k.issue}]),0}},rc=class extends P{static{s(this,"FeedbackSyncCommand")}static paths=[["feedback","sync"]];static usage=E.Usage({category:"Feedback",description:"Fetch GitHub issue state onto linked feedback (issue closed \u21D2 resolved)."});allTenants=f.Boolean("--all-tenants",!1);async execute(){let t=await this.caller();if(!this.allTenants)throw new g("feedback sync requires --all-tenants (the GitHub link is platform-admin-only).");let r=(await this.paginate(t,S.platformFeedback.listAllPlatform,{})).filter(o=>o.githubIssue),i=[];for(let o of r){let a=o.githubIssue;if(!a)continue;let l=Eh(a),d=`${a.repo}#${l}`,c=Ix(["issue","view",String(l),"--repo",a.repo,"--json","state,stateReason"]);if(!c.ok){i.push({id:o.id,issue:d,state:"error",resolved:""});continue}let u;try{u=JSON.parse(c.stdout)}catch{i.push({id:o.id,issue:d,state:"error",resolved:""});continue}let{state:p,reason:h}=Fq(u.state??"",u.stateReason??"");await t.mutation(S.platformFeedback.syncGithubIssueState,{feedbackItemId:o.id,state:p,...h!==void 0?{stateReason:h}:{}}),i.push({id:o.id,issue:d,state:p,resolved:p==="closed"?"\u2713":""})}return this.print(i,o=>o.map(a=>({...a})),["id","issue","state","resolved"]),0}};var ic=class extends P{static{s(this,"FeedbackSetStatusCommand")}static paths=[["feedback","set-status"]];static usage=E.Usage({category:"Feedback",description:"Manually move a feedback item to a board status."});feedbackId=f.String({required:!0,name:"feedbackId"});status=f.String({required:!0,name:"status"});async execute(){let t=await this.caller();if(!Is.includes(this.status))throw new g(`feedback set-status: status must be one of ${Is.join("|")}.`);return await t.mutation(S.platformFeedback.setFeedbackStatus,{feedbackItemId:ee(this.feedbackId,"feedback item"),status:this.status}),this.print({feedbackId:this.feedbackId,status:this.status},n=>[{field:"feedbackId",value:n.feedbackId},{field:"status",value:n.status}]),0}},oc=class extends P{static{s(this,"FeedbackReassignCommand")}static paths=[["feedback","reassign"]];static usage=E.Usage({category:"Feedback",description:"Move a feedback item to another tenant (by target tenant slug)."});feedbackId=f.String({required:!0,name:"feedbackId"});tenantSlug=f.String({required:!0,name:"tenantSlug"});async execute(){let t=await this.caller(),n=await t.query(S.platformFeedback.listAllTenantsForAssignment,{}),r=n.find(i=>i.slug===this.tenantSlug);if(r===void 0){let i=n.map(o=>o.slug).join(", ");throw new g(`feedback reassign: no tenant "${this.tenantSlug}". Available: ${i||"(none)"}.`)}return await t.mutation(S.platformFeedback.reassignTenant,{feedbackItemId:ee(this.feedbackId,"feedback item"),newTenantId:r.id}),this.print({feedbackId:this.feedbackId,tenantSlug:this.tenantSlug},i=>[{field:"feedbackId",value:i.feedbackId},{field:"tenantSlug",value:i.tenantSlug}]),0}},sc=class extends P{static{s(this,"FeedbackReplyCommand")}static paths=[["feedback","reply"]];static usage=E.Usage({category:"Feedback",description:"Post a platform reply on a feedback item (public by default; --internal for a platform-only note)."});feedbackId=f.String({required:!0,name:"feedbackId"});body=f.String({required:!0,name:"body"});internal=f.Boolean("--internal",!1,{description:"Post as an internal note (not visible to the tenant)."});async execute(){let n=await(await this.caller()).mutation(S.platformFeedback.addComment,{feedbackItemId:ee(this.feedbackId,"feedback item"),body:this.body,visibility:this.internal?"internal":"public"});return this.print(n,r=>[{field:"id",value:r.id},{field:"visibility",value:r.visibility},{field:"author",value:r.authorName}]),0}},ac=class extends P{static{s(this,"FeedbackCommentsCommand")}static paths=[["feedback","comments"]];static usage=E.Usage({category:"Feedback",description:"List the conversation (public replies + internal notes) on a feedback item."});feedbackId=f.String({required:!0,name:"feedbackId"});async execute(){let n=await(await this.caller()).query(S.platformFeedback.listComments,{feedbackItemId:ee(this.feedbackId,"feedback item")});return this.print(n,r=>r.map(i=>({id:i.id,visibility:i.visibility,author:i.authorName,body:i.body})),["id","visibility","author","body"]),0}},lc=class extends P{static{s(this,"FeedbackDeadlineCommand")}static paths=[["feedback","set-deadline"],["feedback","deadline"]];static usage=E.Usage({category:"Feedback",description:"Set or clear a feedback item's deadline (platform admin)."});feedbackId=f.String({required:!0,name:"feedbackId"});date=f.String({required:!1,name:"date"});clear=f.Boolean("--clear",!1,{description:"Clear the deadline."});async execute(){let t=await this.caller();if(!this.clear&&this.date===void 0)throw new g("feedback deadline: pass a date (ISO/epoch) or --clear.");let n=this.clear?null:ec(this.date);return await t.mutation(S.platformFeedback.setDeadline,{feedbackItemId:ee(this.feedbackId,"feedback item"),deadline:n}),this.print({feedbackId:this.feedbackId,deadline:n===null?"(cleared)":new Date(n).toISOString()},r=>[{field:"feedbackId",value:r.feedbackId},{field:"deadline",value:r.deadline}]),0}},dc=class extends P{static{s(this,"FeedbackAdminsCommand")}static paths=[["feedback","admins"]];static usage=E.Usage({category:"Feedback",description:"List platform admins (valid feedback assignees)."});async execute(){let n=await(await this.caller()).query(S.platformFeedback.listPlatformAdmins,{});return this.print(n,r=>r.map(i=>({userId:i.userId,name:i.name,email:i.email})),["userId","name","email"]),0}},cc=class extends P{static{s(this,"FeedbackAssignCommand")}static paths=[["feedback","assign"]];static usage=E.Usage({category:"Feedback",description:"Assign a feedback item to a platform admin (userId or email), or --clear."});feedbackId=f.String({required:!0,name:"feedbackId"});assignee=f.String({required:!1,name:"assignee"});clear=f.Boolean("--clear",!1,{description:"Unassign."});async execute(){let t=await this.caller();if(!this.clear&&this.assignee===void 0)throw new g("feedback assign: pass a userId/email or --clear.");let n=this.clear?null:await Ih(t,this.assignee);return await t.mutation(S.platformFeedback.assign,{feedbackItemId:ee(this.feedbackId,"feedback item"),assigneeUserId:n}),this.print({feedbackId:this.feedbackId,assignee:n??"(cleared)"},r=>[{field:"feedbackId",value:r.feedbackId},{field:"assignee",value:r.assignee}]),0}};function bc(e){return[{field:"id",value:e.id},{field:"name",value:e.name},{field:"color",value:e.color},{field:"scope",value:e.scope}]}s(bc,"tagRows");function Ox(e){if(e==="public"||e==="platform")return e;throw new g(`Invalid visibility "${e}" \u2014 expected "public" or "platform".`)}s(Ox,"parseTagScope");var uc=class extends P{static{s(this,"FeedbackTagsListCommand")}static paths=[["feedback","tags","list"]];static usage=E.Usage({category:"Feedback",description:"List the global feedback tag catalog (incl. platform-only tags)."});async execute(){let n=await(await this.caller()).query(S.feedbackTags.listAllTags,{});return this.print(n,r=>r.map(i=>({id:i.id,name:i.name,color:i.color,scope:i.scope})),["id","name","color","scope"]),0}},fc=class extends P{static{s(this,"FeedbackTagsCreateCommand")}static paths=[["feedback","tags","create"]];static usage=E.Usage({category:"Feedback",description:"Create a tag (platform admin). --color is a 6-hex code, e.g. d73a4a; --visibility is public (default) or platform."});name=f.String({required:!0,name:"name"});color=f.String("--color",{required:!0,description:"6-hex colour (no '#')."});visibility=f.String("--visibility",{description:"public (default) or platform (platform-admins only)."});async execute(){let n=await(await this.caller()).mutation(S.feedbackTags.createTag,{name:this.name,color:this.color,scope:this.visibility?Ox(this.visibility):"public"});return this.print(n,bc),0}},pc=class extends P{static{s(this,"FeedbackTagsSetCommand")}static paths=[["feedback","tags","set"]];static usage=E.Usage({category:"Feedback",description:"Change a tag's name, colour and/or visibility (platform admin).",examples:[["Rename and recolour","$0 --env staging feedback tags set <tagId> --name Bug --color d73a4a"]]});tagId=f.String({required:!0,name:"tagId"});name=f.String("--name",{description:"New name."});color=f.String("--color",{description:"New 6-hex colour (no '#')."});visibility=f.String("--visibility",{description:"public (everyone) or platform (platform-admins only)."});async execute(){if(this.name===void 0&&this.color===void 0&&this.visibility===void 0)throw new g("feedback tags set: pass at least one of --name, --color, --visibility.");let t=this.visibility===void 0?void 0:Ox(this.visibility),n=await this.caller(),r=ee(this.tagId,"feedback tag"),i,o=[];try{this.name!==void 0&&(i=await n.mutation(S.feedbackTags.renameTag,{tagId:r,name:this.name}),o.push("--name")),this.color!==void 0&&(i=await n.mutation(S.feedbackTags.recolorTag,{tagId:r,color:this.color}),o.push("--color")),t!==void 0&&(i=await n.mutation(S.feedbackTags.setTagVisibility,{tagId:r,scope:t}),o.push("--visibility"))}catch(a){throw o.length>0&&this.context.stderr.write(`feedback tags set: ${o.join(", ")} already applied.
@@ -11847,7 +11847,7 @@ ${i.map(d=>` ${Rc(d)}
11847
11847
  `:"";this.context.stdout.write(`${i}${t.label} \u2014 ${t.occasion[t.locale]}
11848
11848
  Platzhalter: ${r||"\u2014"}
11849
11849
 
11850
- `),this.print(t,o=>o.slots.map(a=>{let l=o.override?.[a.key];return{block:a.key,label:a.label,deviates:l===void 0?"":"yes",text:(l??a.default).replace(/\s+/g," ").slice(0,80)}}),["block","label","deviates","text"])}},bS=class extends P{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=E.Usage({category:"Notifications",description:"Reword one or more blocks of a letter for this school (merge \u2014 untouched blocks stay as they are).",details:"A block whose text EQUALS the platform default is dropped rather than stored: what is kept is the deviation, never a copy, so a later improvement to an untouched block still reaches this school. An unknown block or an undeclared {{placeholder}} is refused by the backend with every finding named \u2014 nothing is written.",examples:[["One paragraph",'$0 --tenant test notifications letters set applicant.welcome --locale de --slot intro="Sch\xF6n, dass Sie da sind."'],["The English letter",'$0 --tenant test notifications letters set applicant.welcome --locale en --slot intro="Lovely to have you."'],["From a file","$0 --tenant test notifications letters set applicant.tasksOpen --locale de --slot-file intro=./intro.txt"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${Ge.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=f.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let t=gZ(this.slot,this.slotFile);if(Object.keys(t).length===0)throw new g("notifications letters set: nothing to write \u2014 pass --slot <blockKey>=<text> or --slot-file <blockKey>=<path>");let n=await this.caller(),r=await n.mutation(S.notifications.saveLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:cK(this.locale,"letters set"),slots:t});return this.print({templateId:this.templateId,submitted:Object.keys(t),...r},i=>[{key:"letter",value:i.templateId},{key:"submitted",value:i.submitted.join(", ")},{key:"deviating blocks",value:i.overriddenSlotKeys.join(", ")||"\u2014 (back to the platform text)"}]),0}},vS=class extends P{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=E.Usage({category:"Notifications",description:"Drop this school's deviations \u2014 named blocks, or the whole letter with --all.",details:"--all is required to drop a whole letter: dropping everything must be typed, never be what happens when a --slot is forgotten.",examples:[["One block back to the platform text","$0 --tenant test notifications letters reset applicant.welcome --locale de --slot intro"],["The whole letter","$0 --tenant test notifications letters reset applicant.welcome --locale en --all"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${Ge.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"Block key to reset (repeatable)"});all=f.Boolean("--all",!1,{description:"Reset every block of this letter"});async execute(){let t=(this.slot??[]).map(i=>i.trim()).filter(Boolean);if(this.all&&t.length>0)throw new g("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&t.length===0)throw new g("notifications letters reset: name the blocks with --slot <blockKey>, or pass --all to reset the whole letter.");let n=await this.caller(),r=await n.mutation(S.notifications.resetLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:cK(this.locale,"letters reset"),...this.all?{}:{slotKeys:t}});return this.print({templateId:this.templateId,reset:this.all?"all":t.join(", "),...r},i=>[{key:"letter",value:i.templateId},{key:"reset",value:i.reset},{key:"still deviating",value:i.overriddenSlotKeys.join(", ")||"\u2014 (nothing)"}]),0}},Ic=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function Lh(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":Ic(t[r],""),...n===null?{}:{platform:Ic(n[r],"")}}))}s(Lh,"chromeTextRows");var xS=class extends P{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=E.Usage({category:"Notifications",description:"The school's letter frame (greeting and sign-off per language, sender name) and the platform wording each falls back to."});async execute(){let t=await this.caller(),n=await t.query(S.notifications.getTenantChrome,{tenantSlug:this.requireTenant(t)});return this.print(n,r=>[...Lh("greeting",r.greeting,r.defaults.greeting),...Lh("closing",r.closing,r.defaults.closing),{field:"senderName",school:Ic(r.senderName,"\u2014 (platform)"),platform:Ic(r.defaults.senderName,"")}],["field","school","platform"]),0}},SS=class extends P{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=E.Usage({category:"Notifications",description:"Set the school's letter frame. Greeting and sign-off are set in BOTH languages at once; both EMPTY clears that field back to the platform wording.",examples:[["Own sign-off",'$0 --tenant test notifications chrome set --closing-de="Herzliche Gr\xFC\xDFe, Ihr Grundschul-Team" --closing-en="Warm regards, your primary school team"'],["Back to the platform sign-off",'$0 --tenant test notifications chrome set --closing-de="" --closing-en=""']]});greetingDe=f.String("--greeting-de",{description:"Opening line, German"});greetingEn=f.String("--greeting-en",{description:"Opening line, English"});closingDe=f.String("--closing-de",{description:"Sign-off, German"});closingEn=f.String("--closing-en",{description:"Sign-off, English"});senderName=f.String("--sender-name",{description:"Name the school signs with (empty string clears it)"});async execute(){let t=s((l,d,c)=>{if(!(d===void 0&&c===void 0)){if(d===void 0||c===void 0)throw new g(`notifications chrome set: --${l}-de and --${l}-en go together \u2014 the frame is worded in every language`);return{de:d,en:c}}},"pair"),n=t("greeting",this.greetingDe,this.greetingEn),r=t("closing",this.closingDe,this.closingEn);if(n===void 0&&r===void 0&&this.senderName===void 0)throw new g("notifications chrome set: nothing to change \u2014 pass --greeting-de/--greeting-en, --closing-de/--closing-en or --sender-name");let i=await this.caller(),o=this.requireTenant(i);await i.mutation(S.notifications.saveTenantChrome,{tenantSlug:o,...n!==void 0?{greeting:n}:{},...r!==void 0?{closing:r}:{},...this.senderName!==void 0?{senderName:this.senderName}:{}});let a=await i.query(S.notifications.getTenantChrome,{tenantSlug:o});return this.print(a,l=>[...Lh("greeting",l.greeting,null),...Lh("closing",l.closing,null),{field:"senderName",school:Ic(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},fK=[pS,mS,hS,gS,yS,wS,kS,bS,vS,xS,SS];var kZ={capacity:null,isOpen:!1},bZ={capacity:null,isOpen:!0};function vZ(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(vZ,"isCapacity");function Mh(e,t){let n=[],r=t===void 0?void 0:new Set(t);return e.forEach((i,o)=>{if(i.capacities===void 0)return;let a=`program.runs[${o}] ("${i.key}")`;if(i.isOpen!==void 0&&n.push(`[capacity/runIsOpenWithCells] ${a}: \`isOpen\` on the run AND \`capacities\` \u2014 the open state lives on each cell; drop the run-level \`isOpen\``),i.capacities===null||typeof i.capacities!="object"||Array.isArray(i.capacities)){n.push(`[capacity/shape] ${a}: \`capacities\` must map stage keys to { isOpen, capacity }`);return}for(let[l,d]of Object.entries(i.capacities)){let c=`${a}.capacities.${l}`;r!==void 0&&!r.has(l)&&n.push(`[capacity/unknownStage] ${c}: no stage with key "${l}" in program.stages (have: ${[...r].join(", ")||"none"})`);let u=d;if(u===null||typeof u!="object"){n.push(`[capacity/shape] ${c}: expected { isOpen, capacity }`);continue}typeof u.isOpen!="boolean"&&n.push(`[capacity/isOpen] ${c}: \`isOpen\` must be true or false`),(!("capacity"in u)||!vZ(u.capacity))&&n.push(`[capacity/value] ${c}: \`capacity\` must be a whole number \u2265 0, "unlimited", or null (unconfigured) \u2014 got ${JSON.stringify(u.capacity)}`)}}),n}s(Mh,"capacitySpecIssues");function mK(e,t,n={stageKeys:[],runKeys:[]}){let r=e.programKey,i=new Map;if(r!==null)for(let c of e.stages)c.archived||i.set(ri(r,c.key),c.stageId);let o=new Set(n.stageKeys),a=new Set(n.runKeys),l=new Map(e.runStages.map(c=>[`${c.runId}|${c.stageId}`,c])),d=[];for(let c of t){if(c.capacities===void 0)continue;let u=r===null?void 0:e.runs.find(p=>p.key===lr(r,c.key));if(u===void 0&&!a.has(c.key))throw new g(`offer[admission]: run "${c.key}" does not exist and is not created by this apply`);for(let[p,h]of Object.entries(c.capacities)){let y=i.get(p);if(y===void 0&&!o.has(p))throw new g(`offer[admission]: capacities of run "${c.key}" name stage "${p}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let b={capacity:h.capacity,isOpen:h.isOpen},k=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,v=k!==void 0?{capacity:k.capacity,isOpen:k.isOpen}:u===void 0?kZ:bZ;v.capacity===b.capacity&&v.isOpen===b.isOpen||d.push({run:c.key,stageKey:p,from:v,to:b})}}return d}s(mK,"planRunCapacities");function pK(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(pK,"describeCell");function qh(e){return`~cap ${e.run}\xD7${e.stageKey} ${pK(e.from)} \u2192 ${pK(e.to)}`}s(qh,"describeCapacityStep");function hK(e){if(e.programKey===void 0)throw new Error("offer[admission]: the target backend predates stage keys \u2014 deploy it before running offer plan / apply / export with this CLI")}s(hK,"assertBackendHasStageKeys");async function AS(e,t,n,r){let i=await e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),o=i.stages.map(u=>({stageId:u.stageId,key:u.key,name:u.name,...u.gradeLevel!==void 0?{gradeLevel:u.gradeLevel}:{},sequence:u.sequence,archived:u.archived}));hK(i);let a=Sp(i.programKey,o,r),l=a.flatMap(u=>u.op==="archive"?[u.stageId]:[]);if(l.length===0)return a;let d=await e.query(S.programAdmin.getStageOccupancy,{client:t,offerKey:n,stageIds:l}),c=new Map(d.map(u=>[u.stageId,u]));return a.map(u=>{if(u.op!=="archive")return u;let p=c.get(u.stageId);if(p===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:p.activeApplications,openLeads:p.openLeads}}})}s(AS,"planStages");async function Kh(e,t,n,r){let i=r.program?.runs??[];if(!i.some(c=>c.capacities!==void 0))return[];let o=n===null?{programKey:null,stages:[],runs:[],runStages:[]}:await e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n});hK(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>ri(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return mK(o,i,{stageKeys:l.filter(c=>!a.has(c)),runKeys:i.map(c=>c.key).filter(c=>d===null||!o.runs.some(u=>u.key===lr(d,c)))})}s(Kh,"planCapacities");async function xZ(e,t,n,r){let i=(r.program?.runs??[]).map(d=>d.key);if(i.length===0)return;let o=await e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),a=o.programKey;if(a===null)return;let l=i.filter(d=>o.runs.some(c=>c.key===lr(a,d)&&c.status==="archived"));if(l.length>0)throw new g(`offer[admission]: run(s) ${l.map(d=>`"${d}"`).join(", ")} exist only ARCHIVED \u2014 restore with \`offer run restore --run <key>\` or drop the bundle entry`)}s(xZ,"assertNoArchivedRunKey");var TS={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...xp(o??[]),...vp(n.program?.runs??[])];if(a.length>0)throw new g(`offer[admission]: ${a.map(k=>k.message.de).join("; ")}`);let l=Mh(n.program?.runs??[],o?.map(k=>k.key));if(l.length>0)throw new g(`offer[admission]: ${l.join("; ")}`);await xZ(e,i,t,n);let d=await Kh(e,i,t,n),c=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=SZ(n);if(!u)throw new g("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let p=c.units.find(k=>k.key===u);if(!p)throw new g(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(k=>k.key===null?[]:[k.key]).join(", ")||"(none)"}`);let h=[];if(r.dryRun||(await e.mutation(S.programAdmin.ensurePedagogyUnit,{client:i,unitId:p.unitId}),await e.mutation(S.programAdmin.createProgramForAngebot,{client:i,offerKey:t,unitId:p.unitId,...n.program?.key!==void 0?{programKey:n.program.key}:{}})),h.push(`unit=${u}`),o!==void 0)if(r.dryRun){let k=await AS(e,i,t,o);h.push(...k.map(Ap))}else{let k=await e.mutation(S.programAdmin.reconcileProgramStages,{client:i,offerKey:t,stages:o.map(v=>({key:v.key,name:v.name,...v.gradeLevel!==void 0?{gradeLevel:v.gradeLevel}:{}}))});h.push(...k.steps,...k.warnings.map(v=>`warning ${v}`))}let y=r.dryRun?c:await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t});for(let k of n.program?.runs??[]){let v=y.programKey===null?void 0:y.runs.find(A=>A.key===lr(y.programKey,k.key));if(v!==void 0){sa(v.name,k.name)||(r.dryRun||await e.mutation(S.programAdmin.updateProgramRun,{client:i,offerKey:t,runId:v.runId,name:k.name}),h.push(`~run ${k.key} ("${Fe(v.name)}" \u2192 "${Fe(k.name)}")`));continue}r.dryRun||await e.mutation(S.programAdmin.addProgramRun,{client:i,offerKey:t,key:k.key,name:k.name,isOpen:k.capacities!==void 0?!1:k.isOpen??!0,...k.startDate?{startDate:k.startDate}:{},...k.endDate?{endDate:k.endDate}:{}}),h.push(`+run ${k.key} (${Fe(k.name)})`)}let b=r.dryRun?d:await Kh(e,i,t,n);if(!r.dryRun&&b.length>0){let k=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),v=k.programKey;if(v===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let A of b){let T=k.runs.find(C=>C.key===lr(v,A.run))?.runId,I=k.stages.find(C=>ri(v,C.key)===A.stageKey)?.stageId;if(T===void 0||I===void 0)throw new Error(`offer[admission]: cell ${A.run}\xD7${A.stageKey} vanished between plan and write`);await e.mutation(S.programAdmin.setRunStageCapacity,{client:i,offerKey:t,runId:T,stageId:I,capacity:A.to.capacity,isOpen:A.to.isOpen})}}return h.push(...b.map(qh)),h.join(", ")}};function SZ(e){let t=e.program?.unitKey,n=e.links?.unitKey;if(t!==void 0&&n!==void 0&&t!==n)throw new g(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${t}" and links.unitKey "${n}"; keep one`);return t??n}s(SZ,"bundleUnitKey");var gK={role:"control",effect:"pure",cardinality:"N-to-1"};var jh=["add","remove","replace"];function yK(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(yK,"roleAssignLiteral");var wK={role:"method",effect:"context-mutation",inputs:s(()=>[{id:"person",label:{de:"Person",en:"Person"},type:"personRef",required:!0},{id:"roleKey",label:{de:"Rolle",en:"Role"},type:"roleKey",required:!0,optionSource:"tenantRoles"},{id:"mode",label:{de:"Modus",en:"Mode"},type:"enum",defaultValue:"add",optionSource:"declared",enumOptions:[{value:"add",label:{de:"Rolle hinzuf\xFCgen",en:"Add role"}},{value:"remove",label:{de:"Rolle entziehen",en:"Remove role"}},{value:"replace",label:{de:"Alle Rollen ersetzen",en:"Replace all roles"}}]}],"inputs"),validate:s((e,t,n)=>{let r=[],i=yK(e,"roleKey")?.trim()??"",o=yK(e,"mode")??"add";return i===""?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/missingRoleKey] roleAssign-Knoten "${e.id}" nennt keine Rolle \u2014 welche Rolle vergeben wird, muss der Autor aus dem Rollenkatalog des Mandanten w\xE4hlen.`,en:`[roleAssign/missingRoleKey] roleAssign node "${e.id}" names no role \u2014 the author must choose which role is assigned from the school's role catalog.`},severity:"error"}):n?.roleKeys!==void 0&&!n.roleKeys.has(i)?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/unknownRoleKey] Rolle "${i}" existiert nicht im Rollenkatalog des Mandanten \u2014 der Knoten w\xFCrde bei jeder Ausf\xFChrung abbrechen. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[roleAssign/unknownRoleKey] Role "${i}" does not exist in the school's role catalog \u2014 the node would abort on every run. Known roles: ${[...n.roleKeys].sort().join(", ")}.`},severity:"error"}):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(i)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/nonLeafRoleKey] Rolle "${i}" hat untergeordnete Rollen und ist deshalb nicht vergebbar \u2014 eine Partei bekommt ein Blatt, keine Oberkategorie. Vergebbare Rollen: ${[...n.assignableRoleKeys].sort().join(", ")}.`,en:`[roleAssign/nonLeafRoleKey] Role "${i}" has sub-roles and therefore cannot be assigned \u2014 a party gets a leaf role, not a parent category. Assignable roles: ${[...n.assignableRoleKeys].sort().join(", ")}.`},severity:"error"}),jh.includes(o)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.mode`,reason:{de:`[roleAssign/unknownMode] roleAssign-Knoten "${e.id}" deklariert Modus "${o}" \u2014 erlaubt sind ${jh.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${jh.join(" | ")}.`},severity:"error"}),r},"validate")};var AZ=["event","effect","outcomes"],RS=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),kK={outcomes:[{id:zn,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of AZ)i in r&&n.push(RS(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${zn}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${zn}" itself.`));return Cn(t.nodes).some(i=>i.target===e.id)&&n.push(RS(`nodes.${e.id}`,`[eventTrigger/notStart] Knoten "${e.id}" ist ein Start-Knoten, hat aber eine eingehende Kante \u2014 nur der Start l\xF6st ihn aus, jeder Vorgang bliebe hier stehen.`,`[eventTrigger/notStart] Node "${e.id}" is a start node but has an incoming edge \u2014 only the start triggers it, every process would stop here.`)),e.next?.[zn]===void 0&&n.push(RS(`nodes.${e.id}.next.${zn}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${zn}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${zn}" nowhere.`)),n},"validate")};var TZ="submit",bK=[{id:TZ,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function vK(e){return e==="draft"}s(vK,"isWritableSmartFormState");var $S=["draft","committed"],xLe=$S.filter(e=>vK(e));async function xK(e,t,n){let r=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",i=>i.eq("applicationId",t).eq("formNodeId",n)).take(2);return r.length>1&&F(`application ${t}: two form instances for node "${n}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(xK,"getSmartFormInstance");var SK="form:fill",ES="request:collectPayment",IS="request:collectPaymentSeparate",Lr="confirmPayment";var RZ={key:SK,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},AK={key:"bearbeitung",label:ie("In Bearbeitung","In progress"),scope:"node"},TK={[Vw]:{label:ie("In Bearbeitung","In progress"),tone:"neutral",phase:AK,external:at(ie("Entwurf","Draft"),"neutral",ie("Bewerbung fortsetzen","Continue application"),ie("Sie haben die Bewerbung bereits begonnen. Schlie\xDFen Sie sie ab, um sie einzureichen.","You have already started the application. Complete it to submit it."),ie("Bewerbung fortsetzen","Continue application"),"continue-form")},[$p]:{label:ie("Eingereicht","Submitted"),tone:"blue",phase:AK,external:at(ie("Eingereicht","Submitted"),"blue",ie("Ihre Bewerbung ist eingereicht","Your application has been submitted"),ie("Ihre Bewerbung ist bei uns eingegangen. Wir melden uns mit den n\xE4chsten Schritten.","We have received your application. We will be in touch with the next steps."))}},RK={role:"user-action",effect:"side-effect",progressDefaults:TK,progressEvents:Yt(TK),entryProgressEvent:s(()=>Vw,"entryProgressEvent"),actions:s(()=>bK,"actions"),workItemTemplates:s(()=>[RZ],"workItemTemplates"),states:$S,currentState:s(async(e,t)=>{let n=await xK(e,t.applicationId,t.node.id);return n===null?"draft":n.state},"currentState"),inputs:s(e=>[{id:"smartForm",label:{de:"Formular",en:"Form"},type:"smartForm",optionSource:"offerSmartForms",required:e.adoptForm===void 0,inspector:"literal-only"}],"inputs"),outputs:s(e=>[{name:"admission",type:"admission",label:{de:"Anmeldung",en:"Application"},schema:[{key:"beneficiary",type:"personRef",label:{de:"Beschulte Person",en:"Student"}},{key:"signers",type:"personList",label:{de:"Unterzeichner",en:"Signers"}},...e.formExports??[]]}],"outputs"),notificationEvents:s(e=>Pn(e)?[]:[{id:Ep,label:{de:"Formular abgesendet",en:"Form submitted"},audience:"external",args:[{key:"applicationId",type:"string",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[],n=e.inputs?.smartForm,r=n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0,i=e.adoptForm!==void 0;return r&&i?t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.adoptForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" hat sowohl ein smartForm als auch adoptForm \u2014 genau eines ist erlaubt.`,en:`[form.adopt-xor-create] Form node "${e.id}" has both a smartForm and adoptForm \u2014 exactly one is allowed.`},severity:"error"}):!r&&!i&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.smartForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" braucht entweder ein smartForm (neu erzeugen) oder adoptForm (bestehende Instanz \xFCbernehmen).`,en:`[form.adopt-xor-create] Form node "${e.id}" needs either a smartForm (create new) or adoptForm (adopt an existing instance).`},severity:"error"}),t},"validate")};var $K={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Kt.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Kt.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Kt.value,label:{de:"Setzen oder zur\xFCcknehmen",en:"Raise or lower"},type:"boolean",defaultValue:!0,inspector:"literal-only",enumOptions:[{value:"true",label:{de:"Setzen",en:"Raise"}},{value:"false",label:{de:"Zur\xFCcknehmen",en:"Lower"}}]}],"inputs"),notificationEvents:s(e=>[{id:"unlocked",label:{de:"Abschnitt freigeschaltet",en:"Section unlocked"},audience:"external",required:uP(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[];e.inputs?.[Kt.flagKey]?.kind==="literal"&&Hp(e)===null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Kt.flagKey}`,reason:{de:`[setFlag/missingFlagKey] setFlag-Knoten "${e.id}" nennt kein Merkmal (Parameter \u201EMerkmal im Formular\u201C).`,en:`[setFlag/missingFlagKey] setFlag node "${e.id}" names no flag (parameter "Flag in the form").`},severity:"error"});let r=e.inputs?.[Kt.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Kt.value}`,reason:{de:`[setFlag/valueType] setFlag-Knoten "${e.id}": \u201ESetzen oder zur\xFCcknehmen\u201C ist ein Ja/Nein-Wert (true/false), kein Text.`,en:`[setFlag/valueType] setFlag node "${e.id}": "Raise or lower" is a yes/no value (true/false), not text.`},severity:"error"}),t},"validate")};var $Z="true",EZ="false",OS=[{id:$Z,label:{de:"Ja",en:"Yes"}},{id:EZ,label:{de:"Nein",en:"No"}}];var EK={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:OS,validate:s((e,t,n)=>IZ(e,t,n),"validate")};function IZ(e,t,n){let r=s(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${o.de}`,en:`[if/condition] Node "${e.id}": ${o.en}`},severity:"error"}),"issue"),i=OS.filter(o=>e.next?.[o.id]===void 0).map(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${o.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${o.label.de}\u201C (${o.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${o.label.en}" (${o.id}) leads nowhere.`},severity:"error"}));return typeof e.condition!="string"||e.condition.trim()===""?[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})]:[...i,...Im(e.condition,aN(t),n).map(r)]}s(IZ,"ifNodeIssues");var Gi="decision",OZ=new Set(["decision","review"]),zLe=new Set([...OZ,"governedDocument"]);var OK=[{id:"approved",label:{de:"Freigeben",en:"Approve"},semantic:"granted"},{id:"rejected",label:{de:"Ablehnen",en:"Reject"},semantic:"rejected"},{id:"waitlisted",label:{de:"Auf Warteliste",en:"Waitlist"},semantic:"waitlisted"}],IK={released:{label:ie("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:ie("Freigabe","Release"),scope:"node"},external:at(ie("Freigegeben","Released"),"green",ie("Ihre Bewerbung wurde freigegeben","Your application has been released"),ie("Wir haben Ihre Bewerbung freigegeben und melden uns mit den n\xE4chsten Schritten.","We have released your application and will be in touch with the next steps."))}},Ns={role:"user-action",effect:"side-effect",outcomes:OK,progressDefaults:IK,progressEvents:Yt(IK),entryProgressEvent:s(()=>"released","entryProgressEvent"),notificationEvents:s(e=>(e.outcomes??[]).map(t=>({id:t.id,label:t.label,audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"comment",type:"string"}]})),"notificationEvents"),actions:s(e=>[...(e.outcomes??[]).map(t=>({id:t.id,kind:"advance",outcome:t.id,label:t.label,...ho(t.semantic)?{semantic:t.semantic}:{}})),...YF(e)],"actions"),optionalActionKinds:["spawnTasks","skipRule"],workItemTemplates:s(e=>[{key:Gi,recipient:"internal",title:e.decisionAsTask?.title??{de:"Entscheidung",en:"Decision"},unlocks:(e.outcomes??[]).map(t=>t.id).filter(t=>typeof t=="string"&&t.length>0),gatesNode:!1,advancesNode:!0,dueInDays:e.decisionAsTask?.dueInDays}],"workItemTemplates"),taskDocuments:s((e,t)=>t===Gi&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),taskView:s((e,t)=>t===Gi?e.view:void 0,"taskView"),placelessTasks:{[Gi]:"Placed only by the node's authored `view`; a decision that names none is worked in its step wherever the decider opens it."},validate:_S};function _S(e,t,n){let r=[],i=e.outcomes??[];i.length===0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[decision/missingOutcomes] Entscheidungs-Knoten "${e.id}" hat keine Outcomes \u2014 die Entscheidung w\xE4re niemals aufl\xF6sbar.`,en:`[decision/missingOutcomes] Decision node "${e.id}" has no outcomes \u2014 the decision could never be resolved.`},severity:"error"});let o=new Set(i.map(l=>l.id));for(let l of i){let d=l.label;(typeof d=="string"?d.trim().length>0:d!=null&&typeof d=="object"&&Object.values(d).some(p=>typeof p=="string"&&p.trim().length>0))||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}`,reason:{de:`[decision/outcomeMissingLabel] Outcome "${l.id}" von "${e.id}" hat keine Beschriftung \u2014 sie ist der Text des Knopfs im Cockpit.`,en:`[decision/outcomeMissingLabel] Outcome "${l.id}" of "${e.id}" has no label \u2014 it is the text of the button in the cockpit.`},severity:"error"});let u=l.semantic;u===void 0?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticMissing] Outcome "${l.id}" von "${e.id}" sagt nicht, was es bedeutet \u2014 eines von ${Nn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${Nn.join(", ")}.`},severity:"error"}):ho(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" von "${e.id}" hat die Bedeutung "${String(u)}" \u2014 erlaubt: ${Nn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${Nn.join(", ")}.`},severity:"error"})}for(let l of Object.keys(e.commentRequired??{}))o.has(l)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.commentRequired.${l}`,reason:{de:`[decision/commentRequiredUnknownOutcome] Unbekanntes Outcome "${l}" in commentRequired; erlaubt: ${[...o].join(", ")}`,en:`[decision/commentRequiredUnknownOutcome] Unknown outcome "${l}" in commentRequired; allowed: ${[...o].join(", ")}`},severity:"error"});let a=e.decisionAsTask?.title;return a!==void 0&&(a!==null&&typeof a=="object"&&Object.values(a).some(d=>typeof d=="string"&&d.length>0)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.decisionAsTask.title`,reason:{de:"[decision/decisionTaskMissingTitle] decisionAsTask.title ist gesetzt, aber leer \u2014 entweder einen nicht-leeren lokalisierten Text angeben oder das Feld weglassen (dann greift der Standardtitel).",en:"[decision/decisionTaskMissingTitle] decisionAsTask.title is set but empty \u2014 either give a non-empty localized text or omit the field (the default title then applies)."},severity:"error"})),r}s(_S,"validateDecisionNode");var NS=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],_K=[{id:"complete",label:{de:"Vollst\xE4ndig",en:"Complete"}},{id:"acceptedIncomplete",label:{de:"Ohne Nachreichung abgeschlossen",en:"Closed without the missing documents"}},{id:"rejected",label:{de:"Abgelehnt",en:"Rejected"}},{id:"absage",label:{de:"Zur\xFCckgezogen",en:"Withdrawn"}}];var PS="promoted";var NK="promote",PK="Nachr\xFCcken",ll="promoteLabel";var _Z={de:PK,en:"Promote from waitlist"};function NZ(e){let t=e.inputs?.[ll];if(t===void 0||t.kind==="unset")return _Z;let n=t.kind==="literal"?t.value:void 0;return os(n)!==null&&F(`waitlist node ${e.id}: inputs.${ll} ${JSON.stringify(t)} is not a { de, en } literal`),n}s(NZ,"promoteLabelOf");var CS={key:"warteliste",label:ie("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},CK={waitlisted:{label:ie("Warteliste","Waitlisted"),tone:"amber",phase:CS,external:at(ie("Warteliste","Waiting list"),"amber",ie("Sie stehen auf der Warteliste","You are on the waiting list"),ie("Ihre Bewerbung wurde auf die Warteliste gesetzt. Wir informieren Sie, sobald ein Platz frei wird.","Your application has been placed on the waiting list. We will let you know as soon as a place becomes available."))},promoted:{label:ie("Nachger\xFCckt","Promoted"),tone:"green",phase:CS,external:at(ie("Nachger\xFCckt","Moved up"),"green",ie("Sie sind nachger\xFCckt","You have moved up"),ie("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:ie("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:CS,external:at(ie("Warteliste geschlossen","Waiting list closed"),"red",ie("Die Warteliste wurde geschlossen","The waiting list has been closed"),ie("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},DK={outcomes:NS,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:cr.map(e=>({value:e,label:kN[e]}))},{id:ll,label:{de:"Beschriftung \u201ENachr\xFCcken\u201C",en:"Label of \u201CPromote\u201D"},type:"localizedText",required:!1,inspector:"literal-only"}],"inputs"),validate:s((e,t)=>{let n=e.inputs?.[ll];if(n?.kind==="literal"){let a=os(n.value);if(a!==null)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${ll}`,reason:{de:`[waitlist/promoteLabelText] Die Beschriftung \u201ENachr\xFCcken\u201C von "${e.id}" braucht einen Text auf Deutsch und auf Englisch (${a}).`,en:`[waitlist/promoteLabelText] The "Promote" label of "${e.id}" needs a text in German and in English (${a}).`},severity:"error"}]}let r=ik(e);if(r===null)return[];let i=t.nodes.filter(a=>a.type==="waitlist"&&a.id!==e.id),o=t.nodes.indexOf(e);for(let a of i){if(t.nodes.indexOf(a)>o)continue;let l=ik(a);if(l!==null&&l.waitlistOrder!==r.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${a.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 alle Wartelisten eines Prozesses ordnen gleich.`,en:`[waitlist/policyConflict] Waiting lists "${a.id}" and "${e.id}" state different orders \u2014 all waiting lists of a process order alike.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:CK,progressEvents:Yt(CK),entryProgressEvent:s(()=>"waitlisted","entryProgressEvent"),notificationEvents:s(()=>[{id:"placed",label:{de:"Auf die Warteliste gesetzt",en:"Placed on the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]},{id:"promoted",label:{de:"Nachger\xFCckt",en:"Promoted from the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]}],"notificationEvents"),actions:s(e=>(e.outcomes!==void 0&&e.outcomes.length>0?e.outcomes:NS).some(n=>n.id===PS)?[{id:NK,kind:"advance",outcome:PS,semantic:"other",label:NZ(e),surface:gr,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var DS="complete",Oc="acceptedIncomplete",Vh="rejected",PZ="absage",FK="closeWithoutDocuments",LK="rejectAtCompleteness",MK="Ohne Nachreichung abschlie\xDFen",qK="Ablehnen",FS="awaitingDocuments",LS="documentsComplete",MS="closedWithoutDocuments",qS="rejected",KS="withdrawn",KK="requested",h0e={[DS]:{event:LS,status:"complete",endsRole:!0},[Oc]:{event:MS,status:"acceptedIncomplete",endsRole:!1},[Vh]:{event:qS,status:"rejected",endsRole:!0},[PZ]:{event:KS,status:"withdrawn",endsRole:!0}};var _c=s(()=>pd[0],"beneficiary"),jS=366;function CZ(e){let t=e.reads,n=md(e).flatMap(({address:r})=>gt(r)&&!pd.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(gt):[],...n]}s(CZ,"printedFields");function DZ(e,t){let n=de(t);return e.nodes.filter(r=>r.type==="governedDocument"&&CZ(r).some(i=>de(i)===n))}s(DZ,"documentsPrinting");function FZ(e,t){if(!gt(t)||t.path!==_c())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!Pn(n)}s(FZ,"isCreatedFormBeneficiary");function Ht(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Ht,"issue");function LZ(e,t,n){let r=new Map(e.nodes.map(l=>[l.id,l])),i=t.next??{},o=new Set,a=[DS,Oc].flatMap(l=>{let d=i[l]?.to;return d===void 0?[]:[d]});for(;a.length>0;){let l=a.pop();if(o.has(l))continue;o.add(l);let d=r.get(l);if(d!==void 0&&!(d.type==="review"&&ke(d.form)&&ur(d.form)&&d.form.owner===n)){if(d.type==="end"){if(ls(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(LZ,"reachesApprovedEndUnreviewed");var VS={key:"unterlagen",label:ie("Unterlagen nachreichen","Outstanding documents"),scope:"node"},jK={[FS]:{label:ie("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:VS,external:at(ie("Unterlagen fehlen","Documents missing"),"amber",ie("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),ie("Uns fehlen noch einige Angaben oder Unterlagen. Sie finden die Liste und die Frist in Ihren Aufgaben.","Some details or documents are still missing. You will find the list and the deadline in your tasks."))},[LS]:{label:ie("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:VS,external:at(ie("Unterlagen vollst\xE4ndig","Documents complete"),"green",ie("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),ie("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[MS]:{label:ie("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:VS,external:at(ie("Abgeschlossen","Closed"),"neutral",ie("Die Nachreichung ist abgeschlossen","The document request is closed"),ie("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[qS]:{label:ie("Abgelehnt","Rejected"),tone:"red",phase:wC,external:at(ie("Abgelehnt","Rejected"),"red",ie("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),ie("Wir bedauern, Ihnen mitteilen zu m\xFCssen, dass wir Ihre Bewerbung nicht ber\xFCcksichtigen konnten.","We regret to inform you that we were unable to accept your application."))},[KS]:{label:ie("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:mm,external:at(ie("Zur\xFCckgezogen","Withdrawn"),"red",ie("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),ie("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},VK={outcomes:_K,progressDefaults:jK,progressEvents:Yt(jK),entryProgressEvent:s(()=>FS,"entryProgressEvent"),notificationEvents:s(()=>[{id:KK,label:{de:"Unterlagen angefordert",en:"Documents requested"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"fieldLabels",type:"localizedText",required:!0},{key:"dueAt",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=s(r=>e.next?.[r]!==void 0,"wired"),n=[];return t(Oc)&&n.push({id:FK,kind:"advance",outcome:Oc,semantic:"other",label:{de:MK,en:"Close without documents"},surface:gr,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Es geht ohne die fehlenden Unterlagen weiter. Die Anfrage an die Familie wird geschlossen.",en:"The application continues without the missing documents. The request to the family is closed."},confirmLabel:{de:"Abschlie\xDFen",en:"Close"}}}),t(Vh)&&n.push({id:LK,kind:"advance",outcome:Vh,semantic:"rejected",label:{de:qK,en:"Reject application"},surface:gr,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Der Platz wird abgesagt und die Anfrage an die Familie geschlossen. Das l\xE4sst sich nicht r\xFCckg\xE4ngig machen.",en:"The application is rejected and the request to the family is closed. This cannot be undone."},confirmLabel:{de:"Ablehnen",en:"Reject"}}}),n},"actions"),inputs:s(()=>[{id:"person",label:{de:"Person (Gasth\xF6rer-Rolle)",en:"Person (guest role)"},type:"personRef",required:!1},{id:"guestRole",label:{de:"Gastrolle bis zur Nachreichung",en:"Guest role until submitted"},type:"roleKey",required:!1,inspector:"literal-only",optionSource:"tenantRoles"}],"inputs"),validate:s((e,t,n)=>{let r=[],i=`Vollst\xE4ndigkeitspr\xFCfung \u201E${e.label?.de??e.id}\u201C (${e.id})`,o=`Completeness check "${e.label?.en||e.id}" (${e.id})`,a=s(A=>Ue(t,A,"de"),"shown"),l=s(A=>Ue(t,A,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Ht(e,"requires",{de:`[completenessCheck/missingRequires] ${i} nennt keine Felder \u2014 \`requires\` muss mindestens ein Feld eines Formulars enthalten ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/missingRequires] ${o} names no fields \u2014 \`requires\` must contain at least one field of a form ($node.<form>.admission.<field>).`}));else{let A=new Set;for(let T of d){if(!ke(T))continue;let I=de(T);if(A.has(I)){r.push(Ht(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(T)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(T)} appears twice in \`requires\`.`}));continue}if(A.add(I),!gt(T)){r.push(Ht(e,"requires",{de:`[completenessCheck/unknownField] ${a(T)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(T)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let C=ai(n,T);if(C==null)continue;let L=Ra("requires",Ta(C));L==="computed"||L==="repeated"?r.push(Ht(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(T)} ist ${C.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(T)} is ${C.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(Ht(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(T)} (\u201E${wo(C,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 die Benachrichtigung \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l(T)} ("${wo(C,"de")}") has no English name (field or person/section) \u2014 the notification "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},p="inDays"in u,h="until"in u;if(p===h)r.push(Ht(e,"deadline",{de:`[completenessCheck/deadlineShape] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" braucht genau eine Frist: \`{ inDays: n }\` (Tage ab Eintritt) oder \`{ until: "JJJJ-MM-TT" }\`.`,en:`[completenessCheck/deadlineShape] Completeness check "${e.id}" needs exactly one deadline: \`{ inDays: n }\` (days after entry) or \`{ until: "YYYY-MM-DD" }\`.`}));else if(p){let A=u.inDays;(typeof A!="number"||!Number.isInteger(A)||A<0||A>jS)&&r.push(Ht(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(A)}" ist keine ganze Zahl von 0 bis ${jS} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(A)}" is not a whole number from 0 to ${jS} days.`}))}else typeof u.until!="string"||Xk(u.until)===null?r.push(Ht(e,"deadline.until",{de:`[completenessCheck/deadlineDate] Frist "${String(u.until)}" ist kein g\xFCltiges Datum (JJJJ-MM-TT).`,en:`[completenessCheck/deadlineDate] Deadline "${String(u.until)}" is not a valid date (YYYY-MM-DD).`})):u.until<rD(Date.now())&&r.push({...Ht(e,"deadline.until",{de:`[completenessCheck/deadlinePassed] Frist "${u.until}" liegt in der Vergangenheit \u2014 jede Anfrage bek\xE4me den Tag des Eintritts als Frist. Datum aktualisieren?`,en:`[completenessCheck/deadlinePassed] Deadline "${u.until}" is in the past \u2014 every request would get the day of entry as its deadline. Update the date?`}),severity:"warning"});if(Array.isArray(d)){let A=new Map(d.filter(gt).map(T=>[de(T),T]));for(let T of A.values())for(let I of DZ(t,T))r.push(Ht(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(T)} flie\xDFt in das Dokument \u201E${I.label?.de??I.id}" (${I.id}) ein \u2014 nach dessen Ausstellung kann die Familie es nicht mehr nachreichen. Feld aus \`requires\` oder aus dem Dokument nehmen.`,en:`[completenessCheck/requiresConsumedUpstream] Field ${l(T)} flows into the document "${I.label?.en||I.id}" (${I.id}) \u2014 once it is issued, the family can no longer submit it later. Remove the field from \`requires\` or from the document.`}))}if(Array.isArray(d)&&n!==void 0){let A=d.filter(gt).filter(C=>{let L=ai(n,C);return L!=null&&Om(L)}),I=[...new Set(A.map(C=>C.owner))].filter(C=>LZ(t,e,C));if(I.length>0){let C=A.filter(L=>I.includes(L.owner));r.push({...Ht(e,"next",{de:`[review/unreviewedAfterSupply] ${C.map(a).join(", ")} ist pr\xFCfpflichtig und wird hier nachgereicht, aber nach \u201Evollst\xE4ndig\u201C oder \u201Eohne Nachreichung\u201C f\xFChrt ein Weg ohne Pr\xFCfknoten dieses Formulars zur Aufnahme \u2014 niemand pr\xFCft das Nachgereichte. Dort einen Pr\xFCfknoten einf\xFCgen (z. B. \u201EWenn nichts zu pr\xFCfen ist: Durchreichen\u201C).`,en:`[review/unreviewedAfterSupply] ${C.map(l).join(", ")} requires review and is supplied here, but after "complete" or "accepted incomplete" a path without a review node of this form leads to admission \u2014 nobody reviews what was supplied. Insert a review node there (e.g. "When nothing is owed: pass through").`}),severity:"warning"})}}let y=e.inputs?.guestRole,b=y?.kind==="literal"?y.value:void 0,k=e.inputs?.person,v=k?.kind==="binding"?k.address:null;b!==void 0&&(typeof b!="string"||b.trim()===""?r.push(Ht(e,"inputs.guestRole",{de:"[completenessCheck/guestRoleEmpty] `guestRole` ist leer \u2014 Rollenschl\xFCssel angeben oder das Feld weglassen.",en:"[completenessCheck/guestRoleEmpty] `guestRole` is empty \u2014 give a role key or omit the field."})):n?.roleKeys!==void 0&&!n.roleKeys.has(b)?r.push(Ht(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${b}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${b}" does not exist in this school's role catalog. Known roles: ${[...n.roleKeys].sort().join(", ")}.`})):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(b)&&r.push(Ht(e,"inputs.guestRole",{de:`[completenessCheck/nonLeafRole] Rolle "${b}" hat untergeordnete Rollen und ist nicht vergebbar.`,en:`[completenessCheck/nonLeafRole] Role "${b}" has sub-roles and cannot be assigned.`})),v===null&&r.push(Ht(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(b)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${Wt}.${_c()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(b)}", but the input "person" is not bound (e.g. to $node.<form>.${Wt}.${_c()}).`}))),ke(v)&&!FZ(t,v)&&r.push(Ht(e,"inputs.person",{de:`[completenessCheck/personNotFormParty] Eingang \u201Eperson" ist an ${a(v)} gebunden \u2014 die Pr\xFCfung vergibt die Rolle der Person, f\xFCr die ein Formular abgeschickt wurde ($node.<anlegender Formularknoten>.${Wt}.${_c()}).`,en:`[completenessCheck/personNotFormParty] The input "person" is bound to ${l(v)} \u2014 the check assigns the role to the person a form was submitted for ($node.<creating form node>.${Wt}.${_c()}).`})),v!==null&&b===void 0&&r.push(Ht(e,"inputs.person",{de:'[completenessCheck/personWithoutRole] Eingang \u201Eperson" ist gebunden, aber es wird keine Rolle vergeben \u2014 die Bindung wirkt nicht.',en:'[completenessCheck/personWithoutRole] The input "person" is bound, but no role is assigned \u2014 the binding has no effect.'}));for(let A of["complete","rejected"])e.next?.[A]===void 0&&r.push(Ht(e,`next.${A}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${A}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${A}" nowhere.`}));return r},"validate")};var MZ=[{id:vN,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Bh=s(e=>e,"asDecision"),BK={[lk]:{label:ie("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:ie("In Pr\xFCfung","In review"),scope:"node"},external:at(ie("Eingereicht","Submitted"),"blue",ie("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),ie("Ihre Bewerbung ist bei uns eingegangen. Wir pr\xFCfen jetzt Ihre Unterlagen und melden uns, falls etwas fehlt.","We have received your application. We are now reviewing your documents and will get in touch if anything is missing."))}},UK={role:"user-action",effect:"side-effect",outcomes:MZ,progressDefaults:BK,progressEvents:Yt(BK),entryProgressEvent:s(()=>lk,"entryProgressEvent"),advancesAtEntry:s(e=>ov(e)==="advance","advancesAtEntry"),notificationEvents:s(e=>Ns.notificationEvents(Bh(e)),"notificationEvents"),inputs:s(()=>[{id:Qn,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Ss.map(e=>({value:e,label:r0[e]}))}],"inputs"),actions:s(e=>[...Ns.actions(Bh(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:ak,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Ns.optionalActionKinds,workItemTemplates:s(e=>Ns.workItemTemplates(Bh(e)).map(t=>t.key===Gi?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,ak]}:t),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),taskView:s((e,t)=>t===Gi&&e.form!==void 0&&ur(e.form)?{kind:"form",form:e.form.owner,view:gL}:void 0,"taskView"),placelessTasks:{[Gi]:"A review without a form has no checklist to tick; its row is finished in its step (\u201EPr\xFCfung abschlie\xDFen\u201C)."},validate:s((e,t,n)=>{let r=_S(Bh(e),t,n);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!jp.includes(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/rejectingOutcome] Pr\xFCf-Knoten "${e.id}" deklariert das Outcome "${c.id}" mit der Bedeutung "${String(u)}" \u2014 eine Pr\xFCfung lehnt nicht ab und setzt nicht auf die Warteliste; das ist die Entscheidung der Freigabe bzw. \u201EBewerbung ablehnen".`,en:`[review/rejectingOutcome] Review node "${e.id}" declares the outcome "${c.id}" meaning "${String(u)}" \u2014 a review neither rejects nor waitlists; that is the decision of the approval or "Reject application".`},severity:"error"})}let i={de:`\u201E${e.label?.de??e.id}\u201C (${e.id})`,en:`"${e.label?.en||e.id}" (${e.id})`},o=e.inputs?.[Qn],a=ov(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Qn}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${Ss.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${Ss.join(" or ")}.`},severity:"error"});let l=a==="advance",d=e.form;if(l&&d===void 0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:{de:`[review/advanceNeedsForm] Pr\xFCf-Knoten ${i.de} reicht durch, wenn nichts zu pr\xFCfen ist, nennt aber kein Formular \u2014 er w\xFCrde immer durchreichen. Nenne das Formular, dessen pr\xFCfpflichtige Felder er pr\xFCft.`,en:`[review/advanceNeedsForm] Review node ${i.en} passes through when nothing is owed but names no form \u2014 it would always pass through. Name the form whose review-required fields it checks.`},severity:"error"}),l&&(e.outcomes??[]).length!==1&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/advanceOneOutcome] Pr\xFCf-Knoten ${i.de} reicht durch, hat aber ${(e.outcomes??[]).length} Outcomes \u2014 durchgereicht wird \xFCber genau eines.`,en:`[review/advanceOneOutcome] Review node ${i.en} passes through but has ${(e.outcomes??[]).length} outcomes \u2014 it passes through over exactly one.`},severity:"error"}),ke(d)&&ur(d)){let c=n?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(Om)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${de(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt w\xFCrde jedes Mal durchreichen. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${de(d)}, but that form declares no field review-required \u2014 the step would pass through every time. Mark the fields "Review required" in the form.`}:{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${de(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt wartet, ohne dass etwas abzuhaken ist. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${de(d)}, but that form declares no field review-required \u2014 the step waits with nothing to tick. Mark the fields "Review required" in the form.`},severity:l?"error":"warning"})}return r},"validate")};var GK=["awaitingAnswer","answered"];async function zK(e,t){return(await Pa(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(zK,"externalRequestState");var HK=[{id:ss,label:{de:"Bezahlt",en:"Paid"}}],eMe=new Set(HK.map(e=>e.id));var qZ=ss,WK=[{id:qZ,kind:"advance",outcome:ss,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],KZ={id:Dk,kind:"advance",outcome:ss,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:gr,confirm:{title:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},body:{de:"Die Geb\xFChr ist au\xDFerhalb von Plexus eingegangen. Der Schritt wird als separat bezahlt abgeschlossen, die Aufgabe der Familie schlie\xDFt mit.",en:"The fee was received outside Plexus. The step is completed as paid separately; the family's task closes with it."},confirmLabel:{de:"Best\xE4tigen",en:"Confirm"}}},jZ={id:Ck,kind:"advance",outcome:ss,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:gr,superUserOnly:!0,confirm:{title:{de:"Zahlung \xFCberspringen",en:"Skip payment"},body:{de:"Die Geb\xFChr wird au\xDFerhalb von Plexus abgerechnet. Der Schritt wird ohne Zahlung abgeschlossen; es wird kein Betrag als bezahlt verbucht.",en:"The fee is billed outside Plexus. The step is completed without a payment; no amount is recorded as paid."},confirmLabel:{de:"\xDCberspringen",en:"Skip"}}},VZ={id:Ck,kind:"advance",outcome:ss,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:gr,superUserOnly:!0,availableIn:["awaitingAnswer"],confirm:{title:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},body:{de:"Die Familie hat nicht online \xFCber Plexus bezahlt. Der Schritt wird ohne Online-Zahlung abgeschlossen; eine offene Zahlungsseite wird geschlossen. Bitte den Grund angeben (z. B. bar bezahlt).",en:"The family did not pay online through Plexus. The step is completed without an online payment; an open payment page is closed. Please give the reason (e.g. paid in cash)."},confirmLabel:{de:"Abschlie\xDFen",en:"Complete"}},commentRequired:!0};function BS(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(BS,"literalOf");function Ro(e){let t=BS(e,on);return Zp(t)?t:null}s(Ro,"modeOrNull");function BZ(e){let t=BS(e,_i);return typeof t=="string"&&t.length>0?t:null}s(BZ,"articleKeyOrNull");function UZ(e){let t=BS(e,Wn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(UZ,"payeeKeyOrNull");var GZ={id:_i,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},zZ={id:on,label:{de:"Zahlungsweg",en:"Payment mode"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"manual",label:{de:"Manuell (\xDCberweisung an die Schule)",en:"Manual (transfer to the school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},WZ={id:Ni,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},YZ={id:Wn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function HZ(e){return[GZ,zZ,...Ro(e)==="online"?[YZ]:[],WZ]}s(HZ,"collectPaymentInputs");var JZ=["amount","currency","settlement"],QZ={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},ZZ={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function XZ(e,t){if(Ro(e)!=="online")return[];let n=UZ(e);if(n===null)return[];let r=`nodes.${e.id}.inputs.${Wn}`,i=s(o=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:o,severity:"error"}),"at");return t?.traeger!==void 0&&!t.traeger.has(n)?[i({de:`[collectPayment/unknownPayee] Zahlungsempf\xE4nger \u201E${n}" ist kein Tr\xE4ger dieses Mandanten \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[collectPayment/unknownPayee] Payee "${n}" is not a legal entity of this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})]:t?.stripeReadyTraegerKeys!==void 0&&!t.stripeReadyTraegerKeys.has(n)?[i({de:`[collectPayment/onlineWithoutStripe] Zahlungsweg \u201Eonline" an \u201E${n}" setzt voraus, dass dieser Tr\xE4ger ein einsatzbereites Stripe-Konto hat (Administration \u2192 Integrationen \u2192 Stripe, Tr\xE4ger \u201E${n}") \u2014 sonst kann keine Familie bezahlen. Bis dahin \u201Emanual" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Payment mode "online" to "${n}" requires this legal entity to have a ready Stripe account (Administration \u2192 Integrations \u2192 Stripe, legal entity "${n}") \u2014 otherwise no family can pay. Until then, choose "manual".`})]:[]}s(XZ,"payeeIssues");var YK={awaitingPayment:{label:ie("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:ie("Zahlung","Payment"),scope:"node"},external:at(ie("Zahlung offen","Payment due"),"amber",ie("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),ie("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},JK={outputs:s(()=>[{name:tP,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>HZ(e),"inputs"),outcomes:HK,progressDefaults:YK,progressEvents:Yt(YK),entryProgressEvent:s(()=>"awaitingPayment","entryProgressEvent"),notificationEvents:s(e=>Ro(e)!=="online"?[]:[{id:"requested",label:{de:"Zahlung angefordert",en:"Payment requested"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"amount",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=Ro(e);return t==="online"?[...WK,VZ]:t==="manual"?[KZ,jZ]:[]},"actions"),states:GK,currentState:s((e,t)=>zK(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:Ro(t.node)==="manual"?IS:ES}),"currentState"),placelessTasks:{[Lr]:"A payment has no document or form view; the team confirms it in its step's action bar."},workItemTemplates:s(e=>{let t=e,n=Ro(t);return n==="manual"?[{key:Lr,recipient:"internal",title:QZ,unlocks:[Dk],advancesNode:!0},{key:IS,recipient:"external",title:ZZ,unlocks:[],informational:!0,advancesNode:!1}]:n!=="online"?[]:[{key:ES,recipient:"external",title:t.label,unlocks:WK.map(r=>r.id),advancesNode:!0}]},"workItemTemplates"),validate:s((e,t,n)=>{let r=[],i=s((d,c)=>r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${d}`,reason:c,severity:"error"}),"push");for(let d of JZ)d in e&&i(d,{de:`[collectPayment/retiredField] \u201E${d}" steht nicht mehr am Zahlungsknoten \u2014 Betrag und W\xE4hrung kommen aus dem Artikel (Parameter \u201EArtikel"), der Zahlungsweg ist der Parameter \u201EZahlungsweg" (inputs.mode).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and the payment mode is the parameter "Payment mode" (inputs.mode).`});r.push(...XZ(e,n)),Ro(e)==="manual"&&e.assign?.[Lr]===void 0&&i("assign",{de:"[collectPayment/assign] Die Geb\xFChr wird manuell bezahlt, aber kein Team best\xE4tigt den Zahlungseingang \u2014 `assign.confirmPayment` nennt das Team.",en:"[collectPayment/assign] The fee is paid manually, but no team confirms the payment \u2014 `assign.confirmPayment` names the team."}),Ro(e)===null&&i(`inputs.${on}`,{de:`[collectPayment/invalidMode] Zahlungsweg muss einer von ${va.join(", ")} sein (online = die Familie zahlt im Portal, manual = die Schule erh\xE4lt das Geld au\xDFerhalb von Plexus); erhalten ${JSON.stringify(e.inputs?.[on])}.`,en:`[collectPayment/invalidMode] Payment mode must be one of ${va.join(", ")} (online = the family pays in the portal, manual = the school receives the money outside Plexus); received ${JSON.stringify(e.inputs?.[on])}.`});let o=e.inputs?.[Ni];if(o?.kind==="literal"){let d=os(o.value);d!==null&&i(`inputs.${Ni}`,{de:`[collectPayment/reasonText] Der Hinweis f\xFCr die Familie braucht einen Text auf Deutsch und auf Englisch (${d}).`,en:`[collectPayment/reasonText] The note for the family needs a text in German and in English (${d}).`})}let a=BZ(e);if(a===null)return i(`inputs.${_i}`,{de:'[collectPayment/missingArticle] Der Zahlungsknoten nennt keinen Artikel \u2014 unter \u201EParameter" einen einmaligen Artikel des Programms w\xE4hlen (Finanzen \u2192 Artikel).',en:'[collectPayment/missingArticle] The payment node names no article \u2014 under "Parameters" choose a one-time article of the program (Finance \u2192 Articles).'}),r;let l=`inputs.${_i}`;return n?.billingItemKeys!==void 0&&!n.billingItemKeys.has(a)?(i(l,{de:`[collectPayment/unknownArticle] Artikel \u201E${a}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel.`,en:`[collectPayment/unknownArticle] Article "${a}" \u2014 no article of this school has this key.`}),r):(n?.oneTimeBillingItemKeys!==void 0&&!n.oneTimeBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotOneTime] Artikel \u201E${a}" ist kein einmaliger Artikel \u2014 eine Geb\xFChr nimmt nur ${Fk.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${Fk.join(", ")}.`}),n?.offerProgram===null?i(l,{de:"[collectPayment/articleOfferWithoutProgram] Das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.",en:"[collectPayment/articleOfferWithoutProgram] The offer is not assigned to a program, so no article belongs to it; give the offer a program."}):n?.offerProgram?.directBillingItemKeys!==void 0&&!n.offerProgram.directBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotInProgram] Artikel \u201E${a}" ist dem Programm \u201E${n.offerProgram.nameDe}" des Angebots nicht direkt zugeordnet \u2014 unter Finanzen \u2192 Artikel zuordnen (ein Paket z\xE4hlt nicht: es kann den Artikel anders bepreisen).`,en:`[collectPayment/articleNotInProgram] Article "${a}" is not directly assigned to the offer's program "${n.offerProgram.nameDe}" \u2014 assign it under Finance \u2192 Articles (a package does not count: it can price the article differently).`}),r)},"validate")};function QK(e){return{de:`[governedDocument/localeFieldMissing] Die Vorlage "${e}" nennt kein Sprachfeld \u2014 ein Schreiben entsteht in genau einer Sprache. Ein Pflicht-Auswahlfeld mit den Optionen de/en unter den Parametern der Vorlage anlegen, es als localeField der Vorlage nennen und im Knoten an die Sprache des Benutzerkontos binden ($env.applicant.language); die Word-Datei h\xE4lt je Sprache einen Abschnitt <<#input.<feld>.de>> \u2026 <</input.<feld>.de>>.`,en:`[governedDocument/localeFieldMissing] The template "${e}" names no language field \u2014 a letter is written in exactly one language. Create a required choice field with the options de/en among the template's parameters, name it as the template's localeField and bind it in the node to the language of the user account ($env.applicant.language); the Word file holds one section per language <<#input.<field>.de>> \u2026 <</input.<field>.de>>.`}}s(QK,"localeFieldMissingText");var US=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),ZK=/^[a-z][a-z0-9_]*$/;function XK(e,t){let n=[],r=e?.fields;if(!Array.isArray(r))return[{path:"",reason:{de:`[governedDocument/missingTemplateFields] Die Vorlage "${t}" deklariert keine Parameter \u2014 erwartet wird { fields } (die Platzhalter input.<schl\xFCssel>, die ein Knoten f\xFCllt).`,en:`[governedDocument/missingTemplateFields] The template "${t}" declares no parameters \u2014 expected { fields } (the placeholders input.<key> a node fills).`}}];let i=r,o=new Set;for(let a of i){if(typeof a?.key!="string"||!ZK.test(a.key)||o.has(a.key)){n.push({path:`fields.${String(a?.key)}`,reason:{de:`[governedDocument/templateFieldKey] Feld "${String(a?.key)}" der Vorlage "${t}" ist ${o.has(a?.key)?"doppelt":"kein g\xFCltiger Schl\xFCssel"} \u2014 erlaubt sind eindeutige Kleinbuchstaben, Ziffern und _ (gedruckt als input.<schl\xFCssel>).`,en:`[governedDocument/templateFieldKey] Field "${String(a?.key)}" of the template "${t}" is ${o.has(a?.key)?"duplicated":"not a valid key"} \u2014 allowed are unique lower-case letters, digits and _ (printed as input.<key>).`}});continue}o.add(a.key);let l=`fields.${a.key}`;if(!yo(a.type)){n.push({path:l,reason:{de:`[governedDocument/unknownFieldType] Vorlage "${t}" typisiert das Feld "${a.key}" als "${String(a.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${ba.join(", ")}).`,en:`[governedDocument/unknownFieldType] Template "${t}" types the field "${a.key}" as "${String(a.type)}" \u2014 that is not part of the platform's value vocabulary (${ba.join(", ")}).`}});continue}if(US.has(a.type)||n.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${t}" hat den Typ "${a.type}" \u2014 ein Dokument aus einer Vorlage druckt nur ${[...US].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a document from a template only prints ${[...US].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!ZK.test(String(d.value)))&&n.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${t}" hat Optionen, die kein Platzhalter adressieren kann (${a.options.map(d=>d.value).join(", ")}) \u2014 Optionswerte sind Kleinbuchstaben, Ziffern und _ (gedruckt als input.${a.key}.<option>).`,en:`[governedDocument/templateFieldKey] Select field "${a.key}" of the template "${t}" has options no placeholder can address (${a.options.map(d=>d.value).join(", ")}) \u2014 option values are lower-case letters, digits and _ (printed as input.${a.key}.<option>).`}}),a.type==="enum"&&(!Array.isArray(a.options)||a.options.length===0)&&n.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${t}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${t}" names no options \u2014 without them there are no sections input.${a.key}.<option>.`}}),a.type==="pricedItem"){let d=i.find(c=>c.key===a.priceDate);(d===void 0||d.type!=="date")&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${t}" nennt kein Preisdatum \u2014 priceDate muss ein Datumsfeld derselben Vorlage sein (welche Preisversion gilt); genannt: ${JSON.stringify(a.priceDate)}.`,en:`[governedDocument/templateFieldPriceDate] Price field "${a.key}" of the template "${t}" names no price date \u2014 priceDate must be a date field of the same template (which price version applies); named: ${JSON.stringify(a.priceDate)}.`}})}else a.priceDate!==void 0&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Feld "${a.key}" setzt priceDate, ist aber kein Preisfeld (pricedItem).`,en:`[governedDocument/templateFieldPriceDate] Field "${a.key}" sets priceDate but is not a price field (pricedItem).`}});a.processSource==="countersignature"?n.push({path:l,reason:{de:`[governedDocument/countersignatureInTemplate] Feld "${a.key}" wird bei einer Gegenzeichnung gesetzt \u2014 ein Dokument aus einer Vorlage wird nicht gegengezeichnet.`,en:`[governedDocument/countersignatureInTemplate] Field "${a.key}" is set at a countersignature \u2014 a document from a template is not countersigned.`}}):a.processSource!==void 0&&!jm.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${jm.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${jm.join(", ")}.`}})}return n.push(...e9(e,t)),n}s(XK,"templateParameterIssues");function e9(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:QK(t)}];let n=e.fields.find(i=>i.key===e.localeField),r=n===void 0?{de:"nennt kein Feld der Vorlage",en:"names no field of the template"}:n.type!=="enum"?{de:`ist ${n.type}, erwartet wird ein Auswahlfeld (enum)`,en:`is ${n.type}, a select field (enum) is expected`}:n.required!==!0?{de:"ist kein Pflichtfeld \u2014 ohne Sprache gibt es keine Variante",en:"is not a required field \u2014 without a language there is no variant"}:(n.options??[]).length===0?{de:"hat keine Optionen",en:"has no options"}:(n.options??[]).some(i=>!Ge.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${Ge.join(", ")})`,en:`has options that are not a language (allowed: ${Ge.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${t}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${t}" ${r.en}.`}}]}s(e9,"localeFieldIssues");function ej(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(ej,"applyTemplateStamp");var GS=50;async function Uh(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take(GS+1);return n.length>GS&&F(`signing_returns: Vorgang ${t} has more than ${GS} returns`),n}s(Uh,"returnsOf");var zS=50;async function WS(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(zS+1);return n.length>zS&&F(`signing_returns: return ${t} has more than ${zS} files`),n.length===0&&F(`[signing/noDocument] return ${t} carries no file`),n}s(WS,"returnDocumentsOf");async function tj(e,t){let n=await WS(e,t);return n.length!==1&&F(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(tj,"soleReturnDocumentOf");var Gh=200,bMe=Gh*20;async function t9(e,t){let n=await e.db.get(t);return n===null&&F(`[process] application ${t} not found`),n.redactedAt!==void 0}s(t9,"processRedacted");async function YS(e,t){await t9(e,t)&&ue("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(YS,"assertProcessReadable");function n9(e){let t={_id:e._id,_creationTime:e._creationTime,owner:e.owner,key:e.key};return e.scope==="task"?{...t,scope:"task",result:{kind:"value",value:e.value},writtenByTaskId:e.writtenByTaskId}:{...t,scope:"node",result:e.result}}s(n9,"rowOf");async function nj(e,t,n){await YS(e,t);let r=await e.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",i=>i.eq("applicationId",t).eq("scope",n.scope).eq("owner",n.owner).eq("key",n.key)).order("desc").take(Gh+1);return r.length>Gh&&F(`[process] application ${t} has more than ${Gh} results of ${n.scope}.${n.owner}.${n.key}`),r.map(n9)}s(nj,"storeHistory");async function r9(e,t,n){if(n.key===Wt){await YS(e,t);let i=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",o=>o.eq("applicationId",t).eq("formNodeId",n.owner)).unique();return i===null||i.state!=="committed"?{state:"pending",reason:null}:{state:"present",result:{kind:"ref",ref:{kind:"form",formInstanceId:i._id}},row:null}}let[r]=await nj(e,t,{scope:"node",owner:n.owner,key:n.key});return r===void 0?{state:"pending",reason:null}:{state:"present",result:r.result,row:r}}s(r9,"nodeResultAt");async function zh(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return i9(await r9(e,t.applicationId,n),n,t.applicationId)}s(zh,"readOwnResult");function i9(e,t,n){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${de(t)} of application ${n} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(i9,"refOf");var HS={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},o9=Object.keys(HS),s9=o9.filter(e=>HS[e]==="open"),IMe=s9.filter(e=>e!=="pending");function rj(e){return HS[e]==="terminal"}s(rj,"isTerminalSigningStatus");var $o=["docusign","insign"];var Nc={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var l9=rj;function oj(e){return!l9(e.status)&&e.voidRequestedAt===void 0}s(oj,"holdsContract");async function sj(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(sj,"traegerLegalEntityOfParty");async function d9(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(d9,"isOrganizationParty");async function aj(e,t){return await sj(e,t)!==null?"traeger":await d9(e,t)?"organization":"person"}s(aj,"signerKindOf");async function lj(e,t){t.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await c9(e,n.partyId)==="family")return"family";return"traeger"}s(lj,"signingSideOf");async function c9(e,t){return await aj(e,t)==="traeger"?"traeger":"family"}s(c9,"sideOfParty");var pqe=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),cj=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var JS=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),Wh=m.object({period:JS,anchorDate:m.string()});var wqe=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),kqe=m.union(m.literal("line"),m.literal("aggregate")),Yh=m.record(m.string(),m.string());var u9=m.union(m.literal("active"),m.literal("ended")),QS=m.union(m.object({mode:m.literal("track")}),m.object({mode:m.literal("pin"),billingItemVersionId:ze.restrict(m.id("billing_item_versions"),{unindexed:"pinned price version inside the pricing union"})}),m.object({mode:m.literal("override"),amount:m.number()})),f9=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),p9={contractId:ze.belongsTo(m.id("contracts")),billingItemDefinitionId:ze.restrict(m.id("billing_item_definitions")),pricing:QS,pricingSelections:m.optional(Yh),paymentSchedule:m.optional(Wh),resolvedSnapshot:m.any(),feeGroup:m.optional(cj),generationRunId:m.optional(ze.history(m.id("contract_generation_runs")))},m9={...p9,period:f9,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:u9,enrollmentContextId:m.optional(ze.restrict(m.id("enrollments")))},$qe=Gn(m9).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var Mr=m.union(m.string(),m.null()),uj=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),h9=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string(),representative:m.optional(m.object({userId:m.id("users"),nameAtSigning:m.string(),email:m.string()}))}),fj=m.object({sourceAllocationId:m.id("payer_allocations"),scope:m.union(m.object({kind:m.literal("contract")}),m.object({kind:m.literal("contract_line"),contractLineId:m.id("contract_lines")})),payer:m.union(m.object({kind:m.literal("party"),partyId:m.id("parties"),nameAtSigning:m.string()}),m.object({kind:m.literal("payment_method"),paymentMethodId:m.id("payment_methods"),label:m.string(),ownersAtSigning:m.array(uj)})),sharePct:m.union(m.number(),m.null()),flatAmount:m.union(m.number(),m.null()),cap:m.union(m.number(),m.null()),activeFrom:m.string(),activeTo:Mr}),pj=m.object({sourceAppliedGrantId:m.string(),sourceGrantTemplateId:m.union(m.string(),m.null()),name:m.string(),reason:m.string(),kind:m.string(),value:m.number(),rule:m.optional(m.any()),scope:m.optional(m.union(m.literal("line"),m.literal("aggregate"))),floorTotal:m.optional(m.number()),pricePeriod:m.optional(JS),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:Mr,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),g9={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:Mr,pricing:QS,paymentSchedule:m.optional(Wh),pricingSelections:m.optional(Yh),billingItemDefinition:m.object({sourceBillingItemDefinitionId:m.id("billing_item_definitions"),name:m.string(),itemType:m.string(),configOpaque:m.any()}),resolvedSnapshotOpaque:m.any(),enrolment:m.union(m.object({sourceEnrolmentId:m.id("enrollments"),status:m.string(),startDate:Mr,endDate:Mr,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:Mr,programName:Mr,runName:Mr,groupName:Mr}),m.null()),grants:m.array(pj),payerAllocations:m.array(fj)},y9=m.object({...g9,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:Mr,sourceValidTo:Mr})}),w9=m.object({formatVersion:m.literal(2),contract:m.object({scope:m.string(),generator:m.object({sourceGeneratorDefinitionId:m.id("contract_generator_definitions"),sourceCreationTime:m.number(),name:m.string(),bodyOpaque:m.any()})}),parties:m.array(uj),declaredSigners:m.array(h9),payerAllocations:m.array(fj),aggregateGrants:m.optional(m.array(pj)),lines:m.array(y9)}),k9=w9;var b9=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),v9=m.object({pageCount:m.number(),spots:m.array(m.object({signer:m.union(m.object({kind:m.literal("party"),role:m.string(),ordinal:m.union(m.number(),m.null())}),m.object({kind:m.literal("named"),label:Ui})),caption:m.string(),page:m.number(),box:b9}))});var x9=m.object({storageId:ze.holds(m.id("_storage")),sourceArtifactId:m.optional(ze.history(m.id("admission_documents"))),sha256:m.string(),filename:m.string(),source:m.union(m.object({kind:m.literal("uploaded")}),m.object({kind:m.literal("machine_rendered"),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),signaturePlacement:m.optional(v9)}))}),S9=m.object({storageId:ze.holds(m.id("_storage")),sha256:m.string(),filename:m.string(),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),confirmationRequired:m.boolean()}),A9={importedTemplateSource:m.optional(m.object({id:m.string(),creationTime:m.number()})),tenantId:ze.tenant(m.id("tenants")),contractId:ze.restrict(m.id("contracts")),snapshotNumber:m.optional(m.number()),revisionNumber:m.optional(m.number()),supersedesSnapshotId:m.optional(ze.history(m.id("contract_snapshots"))),frozenAt:m.number(),frozenByUserId:m.optional(ze.history(m.id("users"))),document:x9,coverLetter:m.optional(S9),snapshot:ze.historyOf(k9),generation:m.optional(m.object({generatorVersionId:m.optional(ze.history(m.id("contract_generator_versions"))),generatorRevisionId:m.optional(m.string()),implementationKey:m.string(),implementationChecksum:m.string(),input:m.any(),output:m.any()}))},Fqe=Gn(A9).index("by_tenantId",["tenantId"]).index("by_document_storageId",["document.storageId"]).index("by_coverLetter_storageId",["coverLetter.storageId"]).index("by_contractId_and_snapshotNumber",["contractId","snapshotNumber"]).index("by_supersedesSnapshotId",["supersedesSnapshotId"]).index("by_generation_generatorVersionId",["generation.generatorVersionId"]);var Jqe=16*1024;var Qqe=15*6e4;var Zqe=10*6e4;var ZS={contractSnapshotId:ze.restrict(m.id("contract_snapshots")),storageId:ze.restrict(m.id("_storage")),sha256:m.string(),filename:m.string(),uploadedAt:m.number(),signers:m.array(m.object({partyId:ze.history(m.id("parties")),role:m.string()}))},hKe=Gn({tenantId:ze.tenant(m.id("tenants")),signingRequestDocumentId:ze.belongsTo(m.id("signing_request_documents")),...ZS}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var bKe=m.object(ZS);var XS=200;async function T9(e,t,n,r){t.length>XS&&F(`${r} is carried by more than ${XS} signing requests`);let i=[],o=new Set;for(let l of t){if(o.has(l.signingRequestId))continue;o.add(l.signingRequestId);let d=await e.db.get(l.signingRequestId);d===null&&F(`signing_request_documents ${l._id} names a missing signing request ${l.signingRequestId}`),i.push(d)}let a=n==="asc"?1:-1;return i.sort((l,d)=>a*(l._creationTime-d._creationTime))}s(T9,"requestsOfMembers");async function mj(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(XS+1);return await T9(e,r,n,`revision ${t}`)}s(mj,"requestsOfSnapshot");var hj=100;async function R9(e,t){let n=await mj(e,t);n.length>hj&&F(`requestsBySideOf: revision ${t} has more than ${hj} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await lj(e,i.signers)].push(i);return r}s(R9,"requestsBySideOf");async function eA(e,t){return(await R9(e,t)).family}s(eA,"familyRequestsOf");var tA=100;async function $9(e,t){let n=await e;return n.length>tA&&F(`contractChain: more than ${tA} ${t}`),n}s($9,"bounded");async function E9(e,t,n){let r=await zh(e,{applicationId:t,nodeId:n,key:Wp});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${n}.${Wp} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(E9,"nodeContractRef");async function gj(e,t){return await $9(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",n=>n.eq("contractId",t)).take(tA+1),`revisions on contract ${t}`)}s(gj,"snapshotsAsc");async function nA(e,t){let n=(await eA(e,t)).filter(oj);return n.length>1&&F(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s(nA,"openFamilyRequest");async function I9(e,t){for(let n of await gj(e,t))if((await eA(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(I9,"familyRoute");async function yj(e,t){for(let n of t)if(await I9(e,n)==="paper")return"paper";return"provider"}s(yj,"familyRouteOf");async function O9(e,t){let n=await tj(e,t._id),r=await e.db.system.get("_storage",n.storageId);return r===null&&F(`contractChain: return ${t._id} holds missing file ${n.storageId}`),{_id:t._id,_creationTime:t._creationTime,storageId:n.storageId,filename:n.filename,...r.contentType!==void 0?{mimeType:r.contentType}:{},round:t._id}}s(O9,"toReturn");function Hh(e){async function t(a,l){return await E9(a,l,e.id)}s(t,"contractOrNull");async function n(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),p=u===null?null:await a.db.get(u),h=await t(a,l);return(p===null||h===null||p.contractId!==h)&&F(`${c}: ${d} is no revision of node "${e.id}"'s contract ${h??"(none yet)"} \u2014 corrupt arc`),p}s(n,"snapshotOf");async function r(a,l){let d=await t(a,l);return d===null?null:(await gj(a,d)).at(-1)??null}return s(r,"newestSnapshot"),{reads:{kind:"contract",async returned(a,l,d){if(d.askedAbout===void 0){if(d.onUnpinned==="notReturned")return null;F(`returned(${d.where}): an ask of the contract chain is always pinned to its revision`)}let c=await n(a,l,d.askedAbout,`returned(${d.where})`),u=await nA(a,c._id);if(u===null)return null;let p=(await Uh(a,u._id)).filter(h=>h.review.status==="pending"&&h._id!==d.rejected);return p.length>1&&F(`returned(${d.where}): Vorgang ${u._id} has ${p.length} returns pending \u2014 one is checked at a time`),p[0]===void 0?null:await O9(a,p[0])},pinOf(a){return a.contractSnapshotId},returnPinOf(a){return a.signingReturnId}},contractOrNull:t,snapshotOf:n,newestSnapshot:r,contractsOf:{async contractsOf(a,l){let d=await t(a,l);return d===null?[]:[d]}}.contractsOf}}s(Hh,"contractNodeReads");async function _9(e,t){let n=await e.db.system.get("_storage",t);return n===null?null:{...n.contentType===void 0?{}:{mimeType:n.contentType},sizeBytes:n.size,sha256:DM(n.sha256)}}s(_9,"storedObjectMeta");async function rA(e,t){let n=(await _9(e,t))?.mimeType;return n===void 0?{}:{mimeType:n}}s(rA,"objectType");function Jh(e){return e.addedParts??[]}s(Jh,"addedPartsOf");var iA=50;async function N9(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(iA+1);return n.length>iA&&F(`groupRunsOf: generation group ${t} has more than ${iA} runs`),n.length===0&&F(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(N9,"groupRunsOf");async function wj(e,t){let n=await N9(e,t),r=n[0].packageRunId;if(r!==void 0){(n.some(l=>l.packageRunId!==r||l.partKey===void 0)||new Set(n.map(l=>l.partKey)).size!==n.length)&&F(`groupRunsInOrder: package group ${t} has inconsistent members`);let i=await e.db.get(r);i===null&&F(`groupRunsInOrder: package run ${t} is missing`);let o=await e.db.query("contract_package_parts").withIndex("by_packageVersionId_and_position",l=>l.eq("packageVersionId",i.packageVersionId)).take(51),a=[...o.map(l=>l.partKey),...Jh(i).map(l=>l.partKey)];return(o.length>50||n.some(l=>!a.includes(l.partKey)))&&F(`groupRunsInOrder: package group ${t} names an unknown part`),n.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}F(`Package run ${t} has no package reference.`)}s(wj,"groupRunsInOrder");function kj(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(kj,"isCompleteGroup");var oA=200;function P9(e){let t=e.generatorStamp?.parts;return t===void 0&&F(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),t.map(n=>n.partKey)}s(P9,"groupPartKeys");async function C9(e,t,n){let r=await e.db.query("contract_generation_runs").withIndex("by_applicationId_and_workflowNodeId",i=>i.eq("applicationId",t).eq("workflowNodeId",n)).take(oA+1);return r.length>oA&&F(`groupChain: more than ${oA} generation runs on node ${n}`),r}s(C9,"nodeRuns");async function D9(e,t,n){let r=P9(n),i=new Set;for(let a of await C9(e,t,n.id))a.packageRunId===void 0&&F(`groupChain: run ${a._id} on the combined node "${n.id}" carries no generation group`),i.add(a.packageRunId);let o=[];for(let a of i){let l=await wj(e,a);if(!kj(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(Jh(d).map(p=>p.partKey)),u=[];for(let p of l){!r.includes(p.partKey)&&!c.has(p.partKey)&&F(`groupChain: run ${p._id} renders part "${p.partKey}", which node "${n.id}"'s pin does not declare and nobody added`);let h=await e.db.get(p.contractSnapshotId);h===null&&F(`groupChain: run ${p._id} names revision ${p.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:p,snapshot:h})}o.push({packageRunId:a,startedAt:Math.min(...l.map(p=>p._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(D9,"groupRevisionRows");async function sA(e,t,n){let r=await zh(e,{applicationId:t,nodeId:n,key:Yp});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${n}.${Yp} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(sA,"nodeGroupContracts");async function F9(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await nA(e,r._id);i!==null&&n.set(i._id,i)}return n.size>1&&F(`groupChain: generation group ${t.packageRunId} is held by ${n.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...n.values()][0]??null}s(F9,"openGroupRequest");async function L9(e,t){let n=[];for(let i of await WS(e,t._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&F(`groupChain: return ${t._id} holds missing file ${i.storageId}`),n.push({contractSnapshotId:i.contractSnapshotId,storageId:i.storageId,filename:i.filename,...o.contentType!==void 0?{mimeType:o.contentType}:{}})}let r=n[0];return{_id:t._id,_creationTime:t._creationTime,storageId:r.storageId,filename:r.filename,...r.mimeType!==void 0?{mimeType:r.mimeType}:{},round:t._id,documents:n}}s(L9,"toGroupReturn");function bj(e){async function t(i,o,a,l){let d=(await D9(i,o,e)).find(c=>c.members[0]?.snapshot._id===a);return d===void 0&&F(`${l}: ${a} is no revision of node "${e.id}"'s generation groups \u2014 corrupt arc`),d}return s(t,"revisionRowOf"),{reads:{kind:"group",async returned(i,o,a){if(a.askedAbout===void 0){if(a.onUnpinned==="notReturned")return null;F(`returned(${a.where}): an ask of the group chain is always pinned to its lead revision`)}let l=await t(i,o,a.askedAbout,`returned(${a.where})`),d=await F9(i,l);if(d===null)return null;let c=(await Uh(i,d._id)).filter(u=>u.review.status==="pending"&&u._id!==a.rejected);return c.length>1&&F(`returned(${a.where}): Vorgang ${d._id} has ${c.length} returns pending \u2014 one is checked at a time`),c[0]===void 0?null:await L9(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await sA(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(bj,"groupNodeReads");async function M9(e,t){let n=t.lifecycle.kind==="draft"?void 0:t.lifecycle.kind;return{_id:t._id,_creationTime:t._creationTime,versionNumber:t.versionNumber,...n!==void 0?{status:n}:{},origin:t.origin.kind,storageId:t.storageId,...await rA(e,t.storageId),...t.filename!==void 0?{filename:t.filename}:{}}}s(M9,"toRevision");async function q9(e,t){let n=await M9(e,t);return{_id:n._id,_creationTime:n._creationTime,storageId:n.storageId,...n.filename!==void 0?{filename:n.filename}:{},...n.mimeType!==void 0?{mimeType:n.mimeType}:{},round:n.versionNumber}}s(q9,"toReturn");function vj(e){let t=Gm(e);async function n(o,a){return await o.db.query("admission_documents").withIndex("by_applicationId_and_slotKey_and_versionNumber",l=>l.eq("applicationId",a).eq("slotKey",t)).collect()}return s(n,"contentRowsAsc"),{reads:{kind:"artifact",async returned(o,a,l){if(l.askedAbout===void 0){if(l.onUnpinned==="notReturned")return null;ue("CONFLICT",{de:"Die offene Antwort-Aufgabe ist an keine Dokumentversion gebunden, daher l\xE4sst sich die unterschriebene Fassung nicht vom versandten Dokument unterscheiden. Stellen Sie das Dokument neu aus (Zur\xFCckziehen & neu ausstellen).",en:"The open response task is not bound to a document version, so the signed copy cannot be told apart from the document that was sent. Issue the document again (withdraw and reissue)."})}let d=await n(o,a),c=d[d.length-1];if(c===void 0||c._id===l.askedAbout||c.origin.kind!=="uploaded")return null;if(l.rejected!==void 0){let u=d.find(p=>p._id===l.rejected);if(u===void 0&&F(`returned(${l.where}): the handed-back scan ${l.rejected} is no version of slot "${t}"`),c.versionNumber<=u.versionNumber)return null}return await q9(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(vj,"artifactNodeReads");function Qh(e){return e.production==="none"&&F(`documentChainKind: node "${e.id}" has production 'none' \u2014 it keeps no document`),e.production!=="resolver"?"artifact":e.generatorStamp?.parts!==void 0?"group":"contract"}s(Qh,"documentChainKind");function xj(e){switch(Qh(e)){case"contract":return Hh(e).reads;case"group":return bj(e).reads;case"artifact":return vj(e).reads}}s(xj,"documentReadsFor");var K9={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Pc(e){let t=e.responseStrategy;return typeof t=="string"&&t in Ki?Ki[t].producesResponseArtifact:!1}s(Pc,"returnsSignedCopy");function j9(e){return Pc(e)&&e.confirmContractTerms!==!1}s(j9,"asksContractTerms");function Sj(e){return j9(e)?{title:e.contractTermsQuestionText??K9,body:{de:"Die unterschriebene Fassung wird erst nach Ihrer Best\xE4tigung hochgeladen. Die Best\xE4tigung wird mit Zeitpunkt und Person festgehalten.",en:"The signed copy is uploaded only after you confirm. The confirmation is recorded with time and person."},confirmLabel:{de:"OK",en:"OK"}}:null}s(Sj,"contractTermsConfirm");function Aj(e){let t=V9(e);return t.length>0&&t.every(n=>n.status==="blocked")}s(Aj,"producerWindowHeld");function V9(e){return e.filter(t=>t.isOpen&&t.kind==="admission"&&t.templateKey!==void 0&&Dd.has(t.templateKey))}s(V9,"openProducerRows");async function B9(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:cb(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==ui||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${ui} row`),a}s(B9,"rejectedReturnOfAsk");async function Tj(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await B9(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(Tj,"returnedCopyOfAsk");var aA=new Set([...Dd,Cr,gs,To,ui,gn]),Oj={id:en,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},_j={id:Qo,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function U9(e){let t=[],n=[{slot:Oj,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:_j,production:"template",de:{a:"eine",the:"die",it:"sie"}}];for(let{slot:r,production:i,de:o}of n){let a=e.inputs?.[r.id];if(a===void 0||a.kind==="unset")continue;let l=`inputs.${r.id}`;if(e.production!==i){t.push(Te(e,l,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber ${o.a} ${r.label.de} \u2014 nur production '${i}' verwendet sie.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a ${r.label.en.toLowerCase()} \u2014 only production '${i}' uses it.`}));continue}if(a.kind==="binding"){t.push(Te(e,l,{de:`[governedDocument/referenceNotLiteral] Knoten "${e.id}": ${o.the} ${r.label.de} ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ${o.it} aus.`,en:`[governedDocument/referenceNotLiteral] Node "${e.id}": the ${r.label.en.toLowerCase()} is a fixed value of the node, not a binding \u2014 choose it from the list.`}));continue}if(a.kind!=="literal")continue;let d=hd(a.value,{type:r.type});d!==null&&t.push(Te(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return t}s(U9,"referenceInputIssues");var G9={id:qi,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},z9={id:za,type:"boolean",label:{de:"Anschreiben best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},W9={id:Jn,type:"legalEntity",label:SL,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function Y9(e,t){let n=`inputs.${Jn}`,r=e.inputs?.[Jn];if(r!==void 0&&r.kind==="binding")return[Te(e,n,{de:`[governedDocument/traegerNotLiteral] Knoten "${e.id}": der Tr\xE4ger ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ihn aus.`,en:`[governedDocument/traegerNotLiteral] Node "${e.id}": the legal entity is a fixed value of the node, not a binding \u2014 choose it from the list.`})];let i=Ga(e),o=t?.resolverPrintsTraegerAddress?.get(e.id)??new Set,a=[];for(let l of new Set([...i===null?[]:[i],...o])){let d=t?.traeger?.get(l);t?.traeger!==void 0&&d===void 0?a.push(Te(e,n,{de:`[governedDocument/unknownTraeger] Knoten "${e.id}" nennt den Tr\xE4ger "${l}", den es in diesem Mandanten nicht gibt \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[governedDocument/unknownTraeger] Node "${e.id}" names the legal entity "${l}", which does not exist in this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})):d!==void 0&&!d.hasAddress&&o.has(l)&&a.push(Te(e,n,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Cm.address}), aber "${l}" hat keine \u2014 in der Konfiguration des Mandanten nachtragen (foundation.legalEntities[].address).`,en:`[governedDocument/traegerAddressMissing] The generator template on node "${e.id}" prints the legal entity's address (${Cm.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(Y9,"traegerIssues");function Zh(e){if(e.production==="template"){let n=e.templateStamp?.fields;return Array.isArray(n)?n:[]}if(e.production!=="resolver")return[];let t=e.generatorStamp?.inputSchema?.fields;return Array.isArray(t)?t.map(n=>{let{label:r}=n;return r===void 0?{...n,label:{de:n.key,en:n.key}}:(co(r)||F(`governedDocument "${e.id}": the stamped generator parameter "${n.key}" has no { de, en } label (${JSON.stringify(r)}) \u2014 rebuild local fixtures or obtain a reviewed repair of this retained workflow stamp.`),{...n,label:r})}):[]}s(Zh,"generatorFields");function H9(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(H9,"deferredToCockpit");function J9(e){return yo(e.type)?e.type:void 0}s(J9,"resolverSlotType");function Q9(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=Ha(e);return{confirm:{title:{de:`\u201E${t.de}\u201C jetzt senden?`,en:`Send "${t.en}" now?`},body:{de:"Das Dokument wird danach f\xFCr die Familie sichtbar.",en:"The family will be able to see the document afterwards."},confirmLabel:{de:"Senden",en:"Send"}}}}s(Q9,"issueConfirmation");function Te(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Te,"issue");function Xh(e){return Km.includes(e.production)&&vs.includes(e.approval)&&Vm.includes(e.responseStrategy)}s(Xh,"hasValidModes");async function lA(e,t){let n=await Pa(e,{applicationId:t.applicationId,nodeId:t.node.id});if(n.length===0)return"pending";let r=n.filter(a=>a.isOpen&&a.kind==="admission");if(Aj(r))return"producingHeld";if(r.some(a=>a.templateKey!==void 0&&Dd.has(a.templateKey)))return"producing";if(r.some(a=>a.templateKey===To))return"awaitingCoverLetter";let i=r.find(a=>a.templateKey===Cr);if(i!==void 0)return i.status==="blocked"?"deferred":"awaitingApproval";if(r.some(a=>a.templateKey===gn))return"signatureStalled";let o=r.find(a=>a.templateKey===gs);if(o!==void 0){if(ji(t.node).issuesBy==="provider"){let l=Qh(t.node)==="group"?(await sA(e,t.applicationId,t.node.id)).map(d=>d.contractId):[await Hh(t.node).contractOrNull(e,t.applicationId)].flatMap(d=>d===null?[]:[d]);if(l.length===0&&F(`governedDocCurrentState: eSignature node "${t.node.id}" has an open ask but no contract`),await yj(e,l)==="provider")return"awaitingSignature"}return ji(t.node).producesResponseArtifact?await Tj(e,{chain:xj(t.node),applicationId:t.applicationId,ask:o,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${t.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(a=>a.templateKey===ui)?"responseInCheck":"done"}s(lA,"governedDocCurrentState");function Rj(e){return e.production!=="none"&&Qh(e)!=="artifact"}s(Rj,"keepsDocumentInContractDomain");function Z9(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!ke(r)||r.scope!=="env"||!dr(r.key))return[];let i=Jo(r.key);if(t.type!==i.type)return[Te(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" ist ${t.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${de(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${t.key}" is ${t.type}, the environment variable "${i.label.en}" (${de(r)}) supplies ${i.type}.`})];let o=new Set((t.options??[]).map(l=>l.value)),a=(i.enumOptions??[]).filter(l=>!o.has(l.value));return a.length===0?[]:[Te(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" kennt ${a.map(l=>`\u201E${l.label.de}\u201C (${l.value})`).join(", ")} nicht \u2014 die Umgebungsvariable \u201E${i.label.de}\u201C kann diese Werte liefern. Jeder Wert braucht eine Option.`,en:`[governedDocument/envNotCovered] Field "${t.key}" does not know ${a.map(l=>`"${l.label.en}" (${l.value})`).join(", ")} \u2014 the environment variable "${i.label.en}" can supply these values. Every value needs an option.`})]}s(Z9,"envCoverageIssues");function Nj(e,t){let n=[];for(let r of Zh(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...Z9(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${ke(a.address)?de(a.address):JSON.stringify(a.address)}`,en:`a binding to ${ke(a.address)?de(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:H9(e,r.key)?{de:"eine Erg\xE4nzung im Cockpit",en:"a completion in the cockpit"}:null;l!==null&&n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/processSourceConflict] "${r.label.de}" wird vom Vorgang selbst gef\xFCllt (${r.processSource}), daneben steht ${l.de}. Eine der beiden Quellen bliebe wirkungslos \u2014 entferne die Verdrahtung.`,en:`[governedDocument/processSourceConflict] "${r.label.en}" is filled by the case itself (${r.processSource}), and ${l.en} is set as well. One of the two sources would have no effect \u2014 remove the wiring.`},severity:"error"});continue}if(r.required!==!0)continue;let i=e.inputs?.[r.key];i?.kind==="binding"||i?.kind==="literal"||i?.kind==="cockpit"||r.defaultValue!==void 0||n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/unsourcedRequiredField] Pflichtfeld "${r.label.de}" des Generators ${t.de} hat keine Quelle \u2014 binde es an ein Formular-Export-Feld, setze einen festen Wert oder lass es ausdr\xFCcklich im Cockpit erg\xE4nzen.`,en:`[governedDocument/unsourcedRequiredField] Required field "${r.label.en}" of the generator ${t.en} has no source \u2014 bind it to a form export field, set a fixed value or leave it explicitly to the cockpit.`},severity:"error"})}return n}s(Nj,"fieldSourceIssues");function X9(e){let t=_r(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=XK(e.templateStamp,t).map(({path:r,reason:i})=>Te(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...Nj(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(X9,"templateIssues");function eX(e,t){return(t?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(n=>{if(n.documentAnchors===null)return[Te(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage des Generators "${n.pin}" wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the generator template "${n.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})];let r=n.signerAnchors.filter(i=>!n.documentAnchors.has(i));return r.length===0?[]:[Te(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage von "${n.pin}" tr\xE4gt keinen Anker f\xFCr ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 der Anbieter f\xE4nde f\xFCr diese Personen kein Unterschriftsfeld.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the template of "${n.pin}" has no anchor for ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 the provider would find no signature field for these people.`})]})}s(eX,"eSignatureAnchorIssues");function tX(e,t){return t===void 0||t.sendable?[]:ji(e).issuesBy!=="provider"?[]:[Te(e,"responseStrategy",{de:`[signing/noActiveProvider] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[signing/noActiveProvider] Node "${e.id}" is signed electronically, but the school cannot send: ${t.reason.en}`})]}s(tX,"eSignatureProviderIssues");var $j={key:"dokument",label:ie("Dokument","Document"),scope:"node"},Ej={producing:{label:ie("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:$j,external:at(ie("In Vorbereitung","In preparation"),"blue",ie("Ihr Dokument wird vorbereitet","Your document is being prepared"),ie("Die Schule erstellt Ihr Dokument. Sie erhalten es in K\xFCrze im Portal.","The school is preparing your document. You will receive it in the portal shortly."))},issued:{label:ie("Dokument bereitgestellt","Document issued"),tone:"blue",phase:$j,external:at(ie("Dokument bereit","Document ready"),"amber",ie("Ihr Dokument liegt bereit","Your document is ready"),ie("Bitte beantworten Sie das Dokument innerhalb der Frist. Sie finden es in Ihren Aufgaben.","Please respond to the document within the deadline. You will find it in your tasks."),ie("Dokument beantworten","Respond to the document"))}};function Ij(e,t){return!Xh(e)||e.production==="none"?null:t===To||Um(e).some(r=>r.key===t)?Gm(e):null}s(Ij,"governedDocRowSlot");var Pj={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>hs,"processHoldTemplate"),progressDefaults:Ej,progressEvents:Yt(Ej),entryProgressEvent:s(e=>e.production==="none"?"issued":"producing","entryProgressEvent"),notificationEvents:s(e=>[{id:"issued",label:{de:"Dokument bereitgestellt",en:"Document issued"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number"}]},{id:"responded",label:{de:"Antwort eingegangen",en:"Response received"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]},{id:"coverLetterAsked",label:{de:"Anschreiben zur Best\xE4tigung",en:"Cover letter to confirm"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number",required:!1}]},{id:"responseRejected",label:{de:"R\xFCcklauf zur\xFCckgegeben",en:"Returned copy handed back"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"reason",type:"string",required:!0}]}],"notificationEvents"),strictActionCoverage:!0,actions:s(e=>{if(!Xh(e))return[];let t=ji(e),n=[],r=t.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=t.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...bs(e)?["awaitingCoverLetter"]:[],...i,...t.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(n.push({id:Lb(e),kind:"internal",surface:Wa,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...e.approval==="release"?{handsTo:Cr}:{},...Q9(e)??{}}),n.push({id:$L,kind:"internal",surface:Wa,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:EL,kind:"internal",surface:Wa,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:Lm,kind:"internal",label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"documentReturned"}}:{id:t.acceptOutcomeId,kind:"advance",outcome:t.acceptOutcomeId,semantic:t.outcomeSemantics.accept,label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"userTaskResolved"}},{id:t.declineOutcomeId,kind:"advance",outcome:t.declineOutcomeId,semantic:t.outcomeSemantics.decline,label:e.responseLabels?.decline??t.defaultLabels.decline,availableIn:bs(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),bs(e)&&(n.push({id:Dm,kind:"internal",label:{de:"Angebot best\xE4tigen",en:"Confirm offer"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),n.push({id:Fm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),t.producesResponseArtifact&&n.push({id:Mm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:qm,kind:"internal",surface:Wa,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:ys,kind:"internal",surface:Wa,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:IL,currentState:lA,workItemTemplates:s(e=>{let t=e;return Xh(t)?Um(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e,r=Ij(n,t);return r===null?[]:Um(n).find(o=>o.key===t)?.recipient==="internal"?[{kind:"artifact",key:r}]:[]},"taskDocuments"),taskView:s((e,t)=>{let n=Ij(e,t);if(n!==null)return t===To?{kind:"artifact",slot:n,part:"coverLetter"}:{kind:"artifact",slot:n}},"taskView"),inputs:s(e=>[...e.production==="resolver"?[Oj,W9]:[],...e.production==="template"?[_j]:[],G9,...e.generatorStamp?.coverLetter===!0?[z9]:[],...Zh(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=J9(t);return n===void 0?[]:[{field:t,type:n}]}).map(({field:t,type:n})=>({id:t.key,type:n,label:t.label,required:t.required===!0&&t.processSource===void 0,...t.processSource===void 0?{deferrable:!0}:{},...t.defaultValue!==void 0&&(typeof t.defaultValue=="string"||typeof t.defaultValue=="number"||typeof t.defaultValue=="boolean"||t.defaultValue===null||n==="pricedItem"&&go(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:Sk,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===gs||t===To||t===Cd||t===ui||t===gn){let n=t===gs?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===ui?{de:"die Pr\xFCfung des R\xFCcklaufs entsteht erst mit dem R\xFCcklauf der Familie",en:"the check of the returned copy only arises once the family returns it"}:t===gn?{de:"die Kl\xE4rung der elektronischen Unterschrift entsteht erst, wenn sie nicht zustande kommt",en:"resolving the electronic signature only arises when it does not come about"}:{de:"die \xDCberarbeitungs-Aufgabe entsteht nur durch eine Ablehnung",en:"the revision task only arises from a rejection"};return{de:`[governedDocument/blocksTarget] 'blocks' auf "${t}" (Knoten "${e.id}") ist verboten \u2014 ${n.de}; zul\xE4ssige intrinsische Ziele: ${hs}${e.approval==="release"?`, ${Cr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${hs}${e.approval==="release"?`, ${Cr}`:""}.`}}return t===Cr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Cr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Cr}" on node "${e.id}" \u2014 with approval 'none' this template does not exist; the blocker would postpone a phantom.`}:null},"refuseBlocksTarget"),userUploadGate:s(async(e,t)=>{if(Rj(t.node))return!1;let n=await lA(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&ji(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=Sj(t.node);if(n===null||Rj(t.node))return null;let r=await lA(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Xh(e))return r.push(Te(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${Km.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${vs.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Vm.join(", ")}} (ist: ${JSON.stringify(e.responseStrategy)}). Eine Betriebsart ist eine erkl\xE4rte Entscheidung, nie aus der Verdrahtung abgeleitet.`,en:`[governedDocument/unknownMode] Node "${e.id}" declares no valid mode \u2014 required: production \u2208 {${Km.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${vs.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Vm.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=Ki[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Te(e,"production",{de:`[governedDocument/modeContract] Knoten "${e.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben und nichts zu unterschreiben: approval muss 'none' sein (ist: '${e.approval}') und responseStrategy 'confirm' (ist: '${e.responseStrategy}').`,en:`[governedDocument/modeContract] Node "${e.id}" has production 'none' \u2014 with no document there is nothing to release and nothing to sign: approval must be 'none' (is: '${e.approval}') and responseStrategy 'confirm' (is: '${e.responseStrategy}').`}));let o=e.artifacts??[];if(e.production==="none")o.length!==0&&r.push(Te(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" hat production 'none', deklariert aber ${o.length} Artefakt-Slot(s) \u2014 ein dokumentloser Best\xE4tigungs-Knoten verwaltet keinen Slot.`,en:`[governedDocument/slotContract] Node "${e.id}" has production 'none' but declares ${o.length} artifact slot(s) \u2014 a confirmation node without a document manages no slot.`}));else{o.length!==1&&r.push(Te(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" deklariert ${o.length} Artefakt-Slots \u2014 genau EINER (das verwaltete Dokument) ist erforderlich.`,en:`[governedDocument/slotContract] Node "${e.id}" declares ${o.length} artifact slots \u2014 exactly ONE (the managed document) is required.`}));for(let A of o)A.visibility!=="external"&&r.push(Te(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${A.key}" auf Knoten "${e.id}" hat visibility "${A.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${A.key}" on node "${e.id}" has visibility "${A.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(A=>A.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(A=>l.includes(A)))&&r.push(Te(e,"outcomes",{de:`[governedDocument/outcomeContract] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') muss genau ZWEI Outcomes deklarieren \u2014 das Accept-Terminal "${i.acceptOutcomeId}" und das Decline-Terminal "${i.declineOutcomeId}" (deklariert: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"keine"}). Beide sind Pflicht: der Knoten besitzt die Antwort, nicht nur die Freigabe.`,en:`[governedDocument/outcomeContract] Node "${e.id}" (responseStrategy '${e.responseStrategy}') must declare exactly TWO outcomes \u2014 the accept terminal "${i.acceptOutcomeId}" and the decline terminal "${i.declineOutcomeId}" (declared: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(A=>{let T=c?.[A];return T===null||typeof T!="object"||!Object.values(T??{}).some(I=>typeof I=="string"&&I.length>0)},"missingTitle"),p=[];e.production!=="none"&&p.push("prepare","revise"),e.approval==="release"&&p.push("approve"),i.checksReturn&&p.push("check");let h=p.filter(u);h.length>0&&r.push(Te(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${h.join(", ")} \u2014 der Knotentyp ist dokument-agnostisch, die Betitelung ist Pflicht-Konfiguration seiner Betriebsart.`,en:`[governedDocument/missingTitles] Node "${e.id}" is missing the task titles ${h.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let y=e.assign??{};if(e.production!=="none"&&y.prepareDocument===void 0&&r.push(Te(e,"assign.prepareDocument",{de:`[governedDocument/productionAssign] Knoten "${e.id}" (production '${e.production}') verdrahtet kein Produzenten-Team (assign.prepareDocument) \u2014 ohne Producer-Aufgabe g\xE4be es die Submit-Aktion ohne freischaltendes Work-Item.`,en:`[governedDocument/productionAssign] Node "${e.id}" (production '${e.production}') wires no producer team (assign.prepareDocument) \u2014 without a producer task there would be the submit action without an enabling work item.`})),e.approval==="none"&&(y.releaseApproval!==void 0&&r.push(Te(e,"assign.releaseApproval",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', verdrahtet aber assign.releaseApproval \u2014 tote Verdrahtung darf nicht als konfiguriert durchgehen (Betriebsart explizit \xE4ndern statt Gruppen zuweisen).`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but wires assign.releaseApproval \u2014 dead wiring must not pass as configured (change the mode explicitly instead of assigning groups).`})),c?.approve!==void 0&&r.push(Te(e,"titles.approve",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', deklariert aber titles.approve \u2014 es gibt keine Freigabe-Aufgabe, die diesen Titel tr\xFCge.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but declares titles.approve \u2014 there is no release task that would carry this title.`}))),i.checksReturn)y.responseCheck===void 0&&r.push(Te(e,"assign.responseCheck",{de:`[governedDocument/checkAssign] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') verdrahtet kein Team f\xFCr die Pr\xFCfung des R\xFCcklaufs (assign.responseCheck) \u2014 ohne Team l\xE4ge jeder R\xFCcklauf bei niemandem.`,en:`[governedDocument/checkAssign] Node "${e.id}" (responseStrategy '${e.responseStrategy}') wires no team for checking the returned copy (assign.responseCheck) \u2014 without a team every returned copy would lie with nobody.`})),e.production!=="resolver"&&i.issuesBy==="provider"?r.push(Te(e,"responseStrategy",{de:`[governedDocument/eSignatureNeedsResolver] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben (eSignature), erzeugt das Dokument aber mit production '${e.production}' \u2014 der Anbieter bekommt eine eingefrorene Vertragsrevision mit Unterschriftsankern und deklarierten Unterzeichnern, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/eSignatureNeedsResolver] Node "${e.id}" is signed electronically (eSignature) but produces the document with production '${e.production}' \u2014 the provider gets a frozen contract revision with signature anchors and declared signatories, and that only exists with production 'resolver'.`})):e.production!=="resolver"&&r.push(Te(e,"responseStrategy",{de:`[governedDocument/checkNeedsContract] Knoten "${e.id}" pr\xFCft den R\xFCcklauf (signedUploadChecked), erzeugt das Dokument aber mit production '${e.production}' \u2014 die Pr\xFCfung hakt die unterzeichnenden Personen einer eingefrorenen Vertragsrevision ab, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/checkNeedsContract] Node "${e.id}" checks the returned copy (signedUploadChecked) but produces the document with production '${e.production}' \u2014 the check ticks off the signatories of a frozen contract revision, and that only exists with production 'resolver'.`}));else{e.production==="resolver"&&r.push(Te(e,"responseStrategy",{de:`[governedDocument/contractNeedsCheckedReturn] Knoten "${e.id}" erzeugt einen Vertrag (production 'resolver'), beantwortet ihn aber mit '${e.responseStrategy}' \u2014 ein Vertrag gilt erst als unterschrieben, wenn die Schule den R\xFCcklauf gepr\xFCft hat oder ein Anbieter die Unterschrift belegt: responseStrategy muss 'signedUploadChecked' oder 'eSignature' sein (mit assign.responseCheck und titles.check).`,en:`[governedDocument/contractNeedsCheckedReturn] Node "${e.id}" produces a contract (production 'resolver') but answers it with '${e.responseStrategy}' \u2014 a contract only counts as signed once the school has checked the returned copy or a provider proves the signature: responseStrategy must be 'signedUploadChecked' or 'eSignature' (with assign.responseCheck and titles.check).`}));for(let[A,T]of[["assign.responseCheck",y.responseCheck!==void 0],["titles.check",c?.check!==void 0]])T&&r.push(Te(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 eine Pr\xFCfung des R\xFCcklaufs gibt es nur mit responseStrategy 'signedUploadChecked' oder 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"?y.signingRecovery===void 0&&r.push(Te(e,"assign.signingRecovery",{de:`[governedDocument/recoveryAssign] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, verdrahtet aber kein Team f\xFCr die Kl\xE4rung einer Unterschrift, die nicht zustande kommt (assign.signingRecovery) \u2014 \u201EErneut senden" und \u201EAuf Papier umstellen" l\xE4gen bei niemandem.`,en:`[governedDocument/recoveryAssign] Node "${e.id}" is signed electronically but wires no team for resolving a signature that does not come about (assign.signingRecovery) \u2014 "Send again" and "Switch to paper" would lie with nobody.`})):y.signingRecovery!==void 0&&r.push(Te(e,"assign.signingRecovery",{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert assign.signingRecovery \u2014 eine Kl\xE4rung der elektronischen Unterschrift gibt es nur mit responseStrategy 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares assign.signingRecovery \u2014 resolving an electronic signature only exists with responseStrategy 'eSignature'.`})),i.issuesBy==="provider"&&r.push(...eX(e,n),...tX(e,n?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Te(e,"confirmBeforeIssue",{de:`[governedDocument/confirmBeforeIssue] Knoten "${e.id}" setzt confirmBeforeIssue auf ${JSON.stringify(e.confirmBeforeIssue)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmBeforeIssue] Node "${e.id}" sets confirmBeforeIssue to ${JSON.stringify(e.confirmBeforeIssue)} \u2014 only true or false is allowed.`})):e.confirmBeforeIssue===!0&&e.approval==="release"&&r.push(Te(e,"confirmBeforeIssue",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'release', deklariert aber confirmBeforeIssue \u2014 \u201EFreigabe anfordern" schickt noch nichts an die Familie, und die Freigabe selbst ist die bewusste Pr\xFCfung vor dem Versand. Die R\xFCckfrage gibt es nur mit approval 'none'.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'release' but declares confirmBeforeIssue \u2014 "Request release" sends nothing to the family yet, and the release itself is the deliberate check before sending. The confirmation prompt only exists with approval 'none'.`})),e.confirmContractTerms!==void 0&&typeof e.confirmContractTerms!="boolean"&&r.push(Te(e,"confirmContractTerms",{de:`[governedDocument/confirmContractTerms] Knoten "${e.id}" setzt confirmContractTerms auf ${JSON.stringify(e.confirmContractTerms)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmContractTerms] Node "${e.id}" sets confirmContractTerms to ${JSON.stringify(e.confirmContractTerms)} \u2014 only true or false is allowed.`})),Pc(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Te(e,"contractTermsQuestionText",{de:`[governedDocument/deadWiring] Knoten "${e.id}" schaltet die Best\xE4tigung der Vertragsbedingungen ab (confirmContractTerms: false), formuliert aber die Frage um \u2014 ohne Best\xE4tigung wird sie nie gestellt.`,en:`[governedDocument/deadWiring] Node "${e.id}" switches off the confirmation of the contract terms (confirmContractTerms: false) but rewords the question \u2014 without the confirmation it is never asked.`}));else for(let[A,T]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])T&&r.push(Te(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 die Best\xE4tigung der Vertragsbedingungen geh\xF6rt zum Hochladen der unterschriebenen Fassung, das es nur mit responseStrategy 'signedUpload' oder 'signedUploadChecked' gibt.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 the confirmation of the contract terms belongs to uploading the signed copy, which only exists with responseStrategy 'signedUpload' or 'signedUploadChecked'.`}));if(e.production==="none")for(let[A,T]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",y.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])T&&r.push(Te(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${A} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${A} \u2014 without a production phase there is nothing to carry it.`}));for(let A of e.tasks??[])aA.has(A.key)&&r.push(Te(e,`tasks.${A.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${A.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...aA].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${A.key}" on node "${e.id}" collides with an intrinsic template (${[...aA].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...Y9(e,n)):e.inputs?.[Jn]!==void 0&&r.push(Te(e,`inputs.${Jn}`,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber einen Tr\xE4ger \u2014 nur ein erzeugter Vertrag hat eine Vertragspartei der Schule.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a legal entity \u2014 only a generated contract has a contracting party on the school's side.`})),r.push(...U9(e)),e.production==="resolver"){let A=Ti(e);if(A!==null){let T=mN(A);for(let I of Zh(e)){if(!yo(I.type)){r.push(Te(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/unknownFieldType] Generator "${T}" typisiert das Feld "${I.key}" als "${String(I.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${ba.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${T}" types the field "${I.key}" as "${String(I.type)}" \u2014 that is not part of the platform's value vocabulary (${ba.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(I.type==="personList"){r.push(Te(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${T}" deklariert das Feld "${I.key}" als personList \u2014 daf\xFCr gibt es keine Platzhalter-Heimat im Dokument und keine Eingabe. Eine Liste von Personen geh\xF6rt als Rolle mit Kapazit\xE4t deklariert oder als berechneter Textwert.`,en:`[governedDocument/partyListUnsupported] Generator "${T}" declares the field "${I.key}" as personList \u2014 there is no placeholder home for it in the document and no input. A list of people belongs declared as a role with capacity or as a computed text value.`}));continue}I.type==="party"&&(I.key.endsWith("PartyId")||r.push(Te(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${I.key}" endet nicht auf "PartyId" \u2014 aus diesem Suffix wird der Platzhalter-Pr\xE4fix im Dokument abgeleitet (emergencyContactPartyId \u2192 emergency_contact).`,en:`[governedDocument/partyFieldKey] Party field "${I.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...Nj(e,{de:`"${T}"`,en:`"${T}"`}))}}else e.generatorStamp!==void 0&&r.push(Te(e,"generatorStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber den Stempel eines Generators \u2014 ohne maschinelle Produktion l\xE4uft keiner.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a generator stamp \u2014 without machine production none runs.`}));e.production==="template"?r.push(...X9(e)):e.templateStamp!==void 0&&r.push(Te(e,"templateStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber die Parameter einer Vorlage \u2014 ohne Vorlagen-Produktion wird sie nie gef\xFCllt.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a template's parameters \u2014 without template production it is never filled.`}));let b=e.inputs?.[za];b!==void 0&&b.kind!=="unset"&&!(b.kind==="literal"&&typeof b.value=="boolean")&&r.push(Te(e,`inputs.${za}`,{de:`[governedDocument/coverLetterInput] Knoten "${e.id}": Die Best\xE4tigung des Anschreibens ist ein fester Wert ja oder nein.`,en:`[governedDocument/coverLetterInput] Node "${e.id}": the cover letter's confirmation is a fixed yes or no.`})),bs(e)&&(n!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Te(e,`inputs.${za}`,{de:`[governedDocument/coverLetterNotDeclared] Knoten "${e.id}" l\xE4sst ein Anschreiben best\xE4tigen, sein Generator erzeugt aber keines.`,en:`[governedDocument/coverLetterNotDeclared] Node "${e.id}" asks to confirm a cover letter, but its generator produces none.`})),e.approval!=="release"&&r.push(Te(e,"approval",{de:`[governedDocument/coverLetterNeedsRelease] Knoten "${e.id}": Ein Anschreiben mit Best\xE4tigung braucht die Freigabe, denn Vertrag und Anschreiben werden zusammen freigegeben.`,en:`[governedDocument/coverLetterNeedsRelease] Node "${e.id}": a cover letter with confirmation needs the release, because contract and letter are released together.`})),ji(e).producesResponseArtifact||r.push(Te(e,"responseStrategy",{de:`[governedDocument/coverLetterNeedsSigning] Knoten "${e.id}": Ein Anschreiben steht vor einer Unterschrift; dieser Knoten l\xE4sst nicht unterschreiben.`,en:`[governedDocument/coverLetterNeedsSigning] Node "${e.id}": a cover letter comes before a signature; this node takes none.`})));let k=e.inputs?.[qi],v=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return v!==void 0&&!Ld(v)&&r.push(Te(e,`inputs.${qi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(v)} \u2014 erlaubt ist eine ganze Zahl von ${ws} bis ${ks} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(v)} \u2014 a whole number from ${ws} to ${ks} days is allowed.`})),v===void 0&&Zh(e).some(A=>A.processSource==="responseDueInDays")&&r.push(Te(e,`inputs.${qi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" druckt die Antwortfrist (processSource 'responseDueInDays'), setzt aber kein responseDueInDays \u2014 das Dokument nennte eine Frist, die es nicht gibt.`,en:`[governedDocument/dueInDays] Node "${e.id}" prints the response deadline (processSource 'responseDueInDays') but sets no responseDueInDays \u2014 the document would name a deadline that does not exist.`})),r},"validate")};var Cj={addPupil:{method:"POST",path:"/api/v1/admissions/AddPrPupilBasic/{schoolid}",kind:"create",body:"PrPupilBasicCreate",required:["forename","surname","genderId"],maxLength:{titleId:4,forename:50,surname:50,middleName:50,preferredForename:50,preferredSurname:50,genderId:4,firstLanguage:4}},addAdmissionDetails:{method:"POST",path:"/api/v1/admissions/AddAdmissionDetails/{schoolid}/{pupilid}",kind:"create",body:"AddPrPupilAdmissionDetails",required:[],maxLength:{boarderStatusId:4,ageAdjust:4,entryYear:4,entryTerm:4,entryYearGroup:4,currentSchoolId:20,enquirySource:4,currentAdmissionStageId:25}},addNationality:{method:"POST",path:"/api/v1/admissions/AddNationlityInfo/{schoolid}/{pupilid}",kind:"create",body:"NationalityInfoCreate",required:["nationalityId"],maxLength:{nationalityId:4,countryOfBirth:4}},addVisa:{method:"POST",path:"/api/v1/admissions/AddVisaInfo/{schoolid}/{pupilid}",kind:"create",body:"CreateVisaInfo",required:[],maxLength:{placeOfBirth:50,passportCountry:4,passportNumber:50,residenceVisaNumber:50,healthCardNumber:50}},addMedical:{method:"POST",path:"/api/v1/admissions/AddMedicalInfo/{schoolid}/{pupilid}",kind:"create",body:"MedicalInfoCreate",required:[],maxLength:{}},addContact:{method:"POST",path:"/api/v1/admissions/AddContactBasicInfo/{schoolid}/{pupilid}",kind:"create",body:"AddContactBasicInfo",required:["titleId","firstName","lastName","genderId"],maxLength:{relationshipId:4,titleId:4,firstName:50,middleName:50,lastName:50,contactName:200,greeting:200,languageId:4,secondLanguageId:4,genderId:4,professionId:4,companyName:50,jobTitle:50}},linkExistingContact:{method:"POST",path:"/api/v1/admissions/LinkExistingContact/{schoolid}/{pupilid}/{contactid}",kind:"create",body:"LinkContact",required:["relationshipId"],maxLength:{relationshipId:4}},addContactAddress:{method:"POST",path:"/api/v1/admissions/AddContactAddressNew/{schoolid}/{contactid}/{addressformatid}",kind:"create",body:"AddAddressVM",required:["countryId"],maxLength:{addressTypeId:4,countryId:4,addressLine1:100,addressLine2:100,addressLine3:100,addressLine4:100,addressLine5:100,addressLine6:100,lookup1:4,lookup2:4,lookup3:4,lookup4:4,lookup5:4}},addContactEmail:{method:"POST",path:"/api/v1/admissions/AddContactEmail/{schoolid}/{contactid}",kind:"create",body:"AddEmailAddress",required:["emailTypeId","email"],maxLength:{emailTypeId:4,email:254}},addContactTelephone:{method:"POST",path:"/api/v1/admissions/AddContactTelephone/{schoolid}/{contactid}",kind:"create",body:"AddTelephoneNumber",required:["typeId","number"],maxLength:{typeId:4}},linkAddressToPupil:{method:"PUT",path:"/api/v1/admissions/LinkAddressToPupil/{schoolId}/{pupilId}/{addressId}",kind:"update",required:[],maxLength:{}},updatePupilAif:{method:"POST",path:"/api/v1/additionalinformation/UpdatePupilAIF/{schoolid}/{pupilid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},updateContactAif:{method:"POST",path:"/api/v1/additionalinformation/UpdateContactAIF/{schoolid}/{contactid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},listPupils:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfo/{schoolid}",kind:"read",required:[],maxLength:{}},getPupil:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfoById/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},listContactsOfPupil:{method:"GET",path:"/api/v1/admissions/GetContactBasicInfoByPupilId/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},getContact:{method:"GET",path:"/api/v1/admissions/GetContactByContactId/{schoolid}/{contactid}",kind:"read",required:[],maxLength:{}},readPupilAifFields:{method:"GET",path:"/api/v1/additionalinformation/ReadPupilAIFFields/{schoolid}",kind:"read",required:[],maxLength:{}},readContactAifFields:{method:"GET",path:"/api/v1/additionalinformation/ReadContactAIFFields/{schoolid}",kind:"read",required:[],maxLength:{}}};function tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(tr,"isRecord");var dA=["field","join","literal","address","payment","contract"],nX=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),rX=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function br(e){return typeof e=="string"&&e.trim().length>0}s(br,"nonEmptyString");function eg(e,t,n,r,i="value"){if(!tr(e)||!tr(e.from)){r.push({path:t,code:"mappingShape",message:{de:`${t}: eine Zuordnung braucht \`from\`.`,en:`${t}: a mapping needs \`from\`.`}});return}let o=e.from,a=dA.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${dA.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${dA.join(" | ")}).`}});return}let[l]=a;l==="field"&&!br(o.field)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.field\` ist leer.`,en:`${t}: \`from.field\` is empty.`}}),l==="join"&&!(Array.isArray(o.join)&&o.join.length>=2&&o.join.every(br))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.join\` nennt mindestens zwei Formularfelder.`,en:`${t}: \`from.join\` names at least two form fields.`}}),e.whenEmpty!==void 0&&(i==="condition"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nicht f\xFCr eine Bedingung (\`unless\`, \`linkAddressToPupilIf\`).`,en:`${t}: \`whenEmpty\` does not apply to a condition (\`unless\`, \`linkAddressToPupilIf\`).`}}):l!=="field"&&l!=="join"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nur f\xFCr eine Formularantwort (\`field\`, \`join\`).`,en:`${t}: \`whenEmpty\` applies only to a form answer (\`field\`, \`join\`).`}}):typeof e.whenEmpty=="boolean"||Number.isFinite(e.whenEmpty)||br(e.whenEmpty)||r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` ist ein Engage-Wert (Text, Zahl oder ja/nein).`,en:`${t}: \`whenEmpty\` is an Engage value (text, number or yes/no).`}})),l==="address"&&!(ke(o.address)&&o.address.scope==="env"&&dr(o.address.key))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.address\` ist eine Umgebungsvariable (\`{ scope: 'env', key: 'stage.key' }\`).`,en:`${t}: \`from.address\` is an environment value (\`{ scope: 'env', key: 'stage.key' }\`).`}}),l==="payment"&&o.payment!=="amount"&&o.payment!=="settledAt"&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.payment\` ist amount oder settledAt.`,en:`${t}: \`from.payment\` is amount or settledAt.`}}),l==="contract"&&!["startDate","signedAt","createdAt"].includes(String(o.contract))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.contract\` ist startDate, signedAt oder createdAt.`,en:`${t}: \`from.contract\` is startDate, signedAt or createdAt.`}}),l==="literal"&&!["string","number","boolean"].includes(typeof o.literal)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.literal\` ist Text, Zahl oder ja/nein.`,en:`${t}: \`from.literal\` is text, a number or yes/no.`}}),e.format!==void 0&&!nX.has(String(e.format))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekanntes Format \u201E${String(e.format)}".`,en:`${t}: unknown format "${String(e.format)}".`}}),e.lookup!==void 0&&!(br(e.lookup)&&tr(n[e.lookup]))&&r.push({path:t,code:"unknownLookup",message:{de:`${t}: die Lookup-Tabelle \u201E${String(e.lookup)}" fehlt in \`lookups\`.`,en:`${t}: the lookup table "${String(e.lookup)}" is missing from \`lookups\`.`}});let d=e.pick;d!==void 0&&(d==="firstWord"||d==="restWords"||d==="year"||tr(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||tr(d)&&rX.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(eg,"checkMapping");function Eo(e,t,n,r,i){if(!tr(e)){i.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet ein Objekt Feld \u2192 Zuordnung.`,en:`${t}: expects an object field \u2192 mapping.`}});return}let o=Cj[n];for(let a of o.required)a in e||i.push({path:`${t}.${a}`,code:"missingRequired",message:{de:`${t}: Engage verlangt \u201E${a}" (${o.body}) \u2014 es fehlt eine Zuordnung.`,en:`${t}: Engage requires "${a}" (${o.body}) \u2014 a mapping is missing.`}});for(let[a,l]of Object.entries(e))eg(l,`${t}.${a}`,r,i)}s(Eo,"checkBody");function Dj(e,t,n,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet eine Liste.`,en:`${t}: expects a list.`}});return}let i=new Set;e.forEach((o,a)=>{let l=`${t}[${a}]`;if(!tr(o)||!br(o.fieldId)){r.push({path:l,code:"aifShape",message:{de:`${l}: \`fieldId\` fehlt.`,en:`${l}: \`fieldId\` is missing.`}});return}i.has(o.fieldId)&&r.push({path:l,code:"aifDuplicate",message:{de:`${l}: \u201E${o.fieldId}" doppelt.`,en:`${l}: "${o.fieldId}" appears twice.`}}),i.add(o.fieldId),eg(o.value,`${l}.value`,n,r),o.unless!==void 0&&eg(o.unless,`${l}.unless`,n,r,"condition")})}s(Dj,"checkAif");function cA(e){let t=[];if(!tr(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=tr(e.lookups)?e.lookups:{};tr(e.lookups)||t.push({path:"engage.lookups",code:"bodyShape",message:{de:"`engage.lookups` fehlt (Tabellen Name \u2192 Plexus-Wert \u2192 Engage-Id).",en:"`engage.lookups` is missing (tables name \u2192 Plexus value \u2192 Engage id)."}});for(let[r,i]of Object.entries(n))(!tr(i)||!Object.values(i).every(br))&&t.push({path:`engage.lookups.${r}`,code:"lookupShape",message:{de:`Lookup \u201E${r}": jede Engage-Id ist ein nicht leerer Text.`,en:`Lookup "${r}": every Engage id is a non-empty text.`}});if(br(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Eo(e.pupil,"engage.pupil","addPupil",n,t),Eo(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&Eo(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&Eo(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&Eo(e.medical,"engage.medical","addMedical",n,t),Dj(e.pupilAif,"engage.pupilAif",n,t),!Array.isArray(e.contacts))t.push({path:"engage.contacts",code:"bodyShape",message:{de:"`engage.contacts` fehlt (Liste der Kontakte).",en:"`engage.contacts` is missing (list of contacts)."}});else{let r=new Set;e.contacts.forEach((i,o)=>{let a=`engage.contacts[${o}]`;if(!tr(i)||!br(i.key)||!br(i.presentIf)){t.push({path:a,code:"contactShape",message:{de:`${a}: \`key\` und \`presentIf\` fehlen.`,en:`${a}: \`key\` and \`presentIf\` are missing.`}});return}r.has(i.key)&&t.push({path:a,code:"contactDuplicate",message:{de:`${a}: Kontakt \u201E${i.key}" doppelt.`,en:`${a}: contact "${i.key}" appears twice.`}}),r.add(i.key),Eo(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&Eo(i.address,`${a}.address`,"addContactAddress",n,t);for(let[l,d]of[["emails","addContactEmail"],["telephones","addContactTelephone"]]){let c=i[l];if(c!==void 0){if(!Array.isArray(c)){t.push({path:`${a}.${l}`,code:"bodyShape",message:{de:`${a}.${l}: erwartet eine Liste.`,en:`${a}.${l}: expects a list.`}});continue}c.forEach((u,p)=>Eo(u,`${a}.${l}[${p}]`,d,n,t))}}Dj(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&eg(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!tr(r)||!br(r.repeated)||!br(r.field)||!br(r.equals))&&t.push({path:"engage.siblingsAttending",code:"bodyShape",message:{de:"`engage.siblingsAttending` braucht repeated, field und equals.",en:"`engage.siblingsAttending` needs repeated, field and equals."}})}return t}s(cA,"engagePushConfigIssues");function*uA(e){let t=[e.pupil,e.admission,e.nationality,e.visa,e.medical];for(let n of t)for(let r of Object.values(n??{}))yield{mapping:r};for(let n of e.pupilAif??[])yield{mapping:n.value},n.unless!==void 0&&(yield{mapping:n.unless});for(let n of e.contacts){let r=[n.basic,n.address,...n.emails??[],...n.telephones??[]];for(let i of r)for(let o of Object.values(i??{}))yield{mapping:o,contactKey:n.key};for(let i of n.aif??[])yield{mapping:i.value,contactKey:n.key},i.unless!==void 0&&(yield{mapping:i.unless,contactKey:n.key});n.linkAddressToPupilIf!==void 0&&(yield{mapping:n.linkAddressToPupilIf,contactKey:n.key})}}s(uA,"mappingsOf");function Fj(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of uA(e))for(let i of iX(n.from))t.add(oX(i,r));return[...t]}s(Fj,"configFieldKeys");function iX(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(iX,"formFieldsOf");function oX(e,t){return e.startsWith(".")?(t===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(oX,"resolveFieldKey");function Lj(e,t){for(let{mapping:n}of uA(e))if(t in n.from)return!0;return!1}s(Lj,"configReadsSource");function Mj(e){let t=new Set;for(let{mapping:n}of uA(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(Mj,"configEnvLeaves");var qj="done",Kj=["sandbox","production"];var tg="engagePush",bVe=660*1e3;function Io(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(Io,"issue");function fA(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(fA,"literal");function jj(e){return cA(e.engage).length===0?e.engage:null}s(jj,"validConfig");function sX(e,t){let n=new Map(e.nodes.map(a=>[a.id,a])),r=e.nodes.filter(a=>a.type==="eventTrigger"),i=new Set,o=r.map(a=>a.id);for(;o.length>0;){let a=o.pop();if(a===t||i.has(a))continue;i.add(a);let l=n.get(a);if(l!==void 0){if(l.type==="end"){let d=l.inputs?.applicationOutcome;if(d?.kind==="literal"&&d.value==="approved")return!0;continue}for(let d of Object.values(l.next??{})){let c=d?.to;typeof c=="string"&&o.push(c)}}}return!1}s(sX,"bypassingPath");var Vj={role:"system-action",effect:"side-effect",outcomes:[{id:qj,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=jj(e);return t===null?[]:Mj(t)},"envReads"),inputs:s(()=>[{id:"target",label:{de:"Ziel-Engage",en:"Target Engage"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"sandbox",label:{de:"Sandbox",en:"Sandbox"}},{value:"production",label:{de:"Produktion",en:"Production"}}]},{id:"contractFields",label:{de:"Vertragsfelder F01\u2013F25",en:"Contract fields F01\u2013F25"},type:"enum",required:!1,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"off",label:{de:"Nicht \xFCbertragen (Bedeutung offen)",en:"Do not transfer (meaning open)"}},{value:"on",label:{de:"\xDCbertragen",en:"Transfer"}}]}],"inputs"),validate:s((e,t,n)=>{let r=e.label?.de??e.id,i=e.label?.en||e.id,o=[],a=fA(e,"target");Kj.includes(a)||o.push(Io(e,"inputs.target",{de:`[engagePush/invalidTarget] \u201E${r}": das Ziel ist sandbox oder production.`,en:`[engagePush/invalidTarget] "${i}": the target is sandbox or production.`}));let l=fA(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(Io(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`})),e.assign?.[tg]===void 0&&o.push(Io(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${tg}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${tg}\` names the team.`}));for(let b of cA(e.engage))o.push(Io(e,b.path,{de:`[engagePush/config] \u201E${r}": ${b.message.de}`,en:`[engagePush/config] "${i}": ${b.message.en}`}));let d=t.nodes.filter(b=>b.id!==e.id&&b.type==="engagePush"&&fA(b,"target")===a);d.length>0&&o.push(Io(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${d.map(b=>`"${b.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${d.map(b=>`"${b.id}"`).join(", ")} already transfers to the same target.`})),sX(t,e.id)&&o.push(Io(e,"next",{de:`[engagePush/bypassed] \u201E${r}": ein Weg erreicht ein \u201Eangenommen"-Ende, ohne durch die Engage-\xDCbertragung zu laufen \u2014 was dort angenommen wird, k\xE4me nie in Engage an.`,en:`[engagePush/bypassed] "${i}": a path reaches an "accepted" end without passing through the Engage transfer \u2014 what is accepted there would never reach Engage.`}));let c=jj(e),u=e;for(let[b,k,v,A]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])c===null||!Lj(c,b)||u[k]!==void 0||o.push(Io(e,k,{de:Sa("address/missing",{where:`\u201E${r}\u201C \u203A ${v}`},"de"),en:Sa("address/missing",{where:`"${i}" \u203A ${A}`},"en")}));let p=u.form,h=ke(p)&&p.scope==="node"?p.owner:void 0,y=h===void 0?void 0:n?.readinessFormFieldsByFormNode?.get(h);if(c!==null&&y!==void 0){let b=new Set(y.keys()),k=Fj(c).filter(v=>!b.has(v)&&!/\[\d+\]\./.test(v));if(k.length>0){let v=t.nodes.find(A=>A.id===h);o.push(Io(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${v?.label?.de??h}" nicht \u2014 sie werden nicht \xFCbertragen: ${k.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${v?.label?.en||h}" does not know these fields \u2014 they are not transferred: ${k.join(", ")}.`},"warning"))}}return o},"validate")};var Oo={join:gK,end:bC,roleAssign:wK,eventTrigger:kK,waitlist:DK,completenessCheck:VK,form:RK,setFlag:$K,if:EK,decision:Ns,review:UK,collectPayment:JK,governedDocument:Pj,countersign:VL,engagePush:Vj};JN(Oo);function Bj(e,t){let n=e;if(n==null||!Array.isArray(n.nodes))throw new g(`offer plan: the ${t} carries no workflow graph with nodes`);return e}s(Bj,"graphOf");function Uj(e){let t=new Map;for(let n of e.nodes)for(let r of oi(e,n))t.set(de(r.address),r.nodeId);return t}s(Uj,"producedOf");function Gj(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(rs(e,n).map(r=>de(r.address))));return t}s(Gj,"readsOf");function zj(e,t){let n=Bj(e,"bundle"),r=Bj(t.graph,"live head"),i=Uj(n),o=Uj(r),a={added:[],removed:[],moved:[]};for(let[u,p]of i){let h=o.get(u);h===void 0?a.added.push({address:u,nodeId:p}):h!==p&&a.moved.push({address:u,from:h,to:p})}for(let[u,p]of o)i.has(u)||a.removed.push({address:u,nodeId:p});let l=Gj(n),d=Gj(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let p=l.get(u)??new Set,h=d.get(u)??new Set,y=[...p].filter(k=>!h.has(k)),b=[...h].filter(k=>!p.has(k));(y.length>0||b.length>0)&&c.push({nodeId:u,added:y,removed:b})}return{headRevision:t.revision,pinnedApplications:t.pinnedApplications,produced:a,reads:c}}s(zj,"planAddresses");function Wj(e){let t=[...e.produced.moved.map(i=>({icon:"~",target:`address:${i.address}`,status:`Knoten ${i.from} \u2192 ${i.to}`})),...e.produced.added.map(i=>({icon:"+",target:`address:${i.address}`,status:`neu (${i.nodeId})`})),...e.produced.removed.map(i=>({icon:"-",target:`address:${i.address}`,status:`entfernt (${i.nodeId})`})),...e.reads.map(i=>({icon:"~",target:`reads:${i.nodeId}`,status:[i.added.length>0?`+${i.added.join(", ")}`:"",i.removed.length>0?`\u2212${i.removed.join(", ")}`:""].filter(Boolean).join(" ")}))];if(t.length===0)return[];let{real:n,test:r}=e.pinnedApplications;return t.push({icon:"!",target:"pinned",status:`${n+r} Anmeldungen (${n} echt, ${r} Test) auf Fassung ${e.headRevision} bleiben auf ihrer Version \u2014 Umpinnen nur per Migration mit Abbildung`}),t}s(Wj,"addressPlanRows");function Yj(e,t){return t==null?!0:Ce(e)!==Ce(t)}s(Yj,"changed");async function Hj(e,t,n){if(t.index.module!==TS.name)throw new g(`offer: unknown module "${t.index.module}"`);return S0(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return TS.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(Hj,"applyOffer");async function Jj(e,t,n,r="published"){let i=await e.query(S.setup.offerBundle.exportOfferBundle,{client:t,offerKey:n,generation:r});return{bundle:i.bundle,generation:i.generation,revision:i.revision}}s(Jj,"exportOffer");async function pA(e,t){let{index:n}=t,i=(await e.query(S.workflow.listManifests,{client:n.tenant})).find(y=>y.offerKey===n.slugs.manifest),o="create";i&&(o="same");let a={};for(let[y,b]of Object.entries(t.smartforms??{})){let k=i?await e.query(S.forms.getSmartFormBySlug,{client:n.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=k?.def?Yj(b,{label:k.def.label,...k.def.definition})?"change":"same":"create"}let l="absent",d=null;if(t.workflow!==void 0){if(l="create",i?.workflowDefinitionId){let y=await e.query(S.workflow.getWorkflowDef,{workflowDefinitionId:i.workflowDefinitionId}),b=y?.publishedVersion??y?.draftVersion;l=Yj(b&&{graph:ua(t.workflow.graph),progressLayout:t.workflow.progressLayout??b.progressLayout,progressWiring:t.workflow.progressWiring??b.progressWiring},b&&{graph:ua(b.graph),progressLayout:b.progressLayout,progressWiring:b.progressWiring})?"change":"same"}if(i){let y=await e.query(S.workflow.getOfferHeadPins,{client:n.tenant,offerKey:n.slugs.manifest});y!==null&&(d=zj(t.workflow.graph,y))}}let c=n.program?.stages,u=c===void 0?[]:i?await AS(e,n.tenant,n.slugs.manifest,c):Sp(null,[],c),p=await Kh(e,n.tenant,i?n.slugs.manifest:null,n),h=i?await e.query(S.workflow.getOfferPublishState,{client:n.tenant,offerKey:n.slugs.manifest}):null;return{manifest:o,smartforms:a,workflow:l,addresses:d,stages:u,capacities:p,publishPending:h?.draftDiffersFromExternal??null,draftRevision:h?.draftRevision??null,externalHeadRevision:h?.externalHeadRevision??null}}s(pA,"diffOffer");function ng(e){if(e.type==="governedDocument"){let t=e.production;return t==="resolver"?"resolver":t==="template"?"template":t==="upload"||t==="none"?"manual":"unauthored"}return null}s(ng,"contractProductionModeOf");function Qj(e){return ng(e)==="resolver"}s(Qj,"isResolverCarrierNode");function rg(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=Ti(n);return!Qj(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(rg,"authoredPins");var Zj={type:"address",dataType:"composite"};var Xj={type:"boolean",dataType:"boolean"};var eV={type:"consent",dataType:"boolean"};var tV={type:"date",dataType:"date"};var nV={type:"docRef",dataType:"file"};var rV={type:"email",dataType:"text"};var iV={type:"string",dataType:"text"};var oV={type:"tel",dataType:"text"};var ig={address:Zj.dataType,boolean:Xj.dataType,consent:eV.dataType,date:tV.dataType,docRef:nV.dataType,email:rV.dataType,enum:rC.dataType,string:iV.dataType,tel:oV.dataType};function mA(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(mA,"shapeOf");function sV(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,mA(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,mA(l)))),o.repeated?.forEach(a=>n.push({key:a.key,itemTemplate:a.itemTemplate,effects:a.effects??[]})),o.subsections?.forEach(r)},"visit");e.sections.forEach(r);let i=[{pathPrefix:"",effects:e.effects??[],shapes:t}];for(let o of n){let a=new Map(t);o.itemTemplate.forEach(l=>a.set(`$item.${l.key}`,mA(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(sV,"fieldMapScopes");function aX(e){let t=new Set,n=s(r=>{r.computed?.forEach(i=>t.add(i.key)),r.subsections?.forEach(n)},"visit");return e.sections.forEach(n),t}s(aX,"computedKeysOf");function aV(e){let t=[],n=aX(e);for(let r of sV(e))r.effects.forEach((i,o)=>{if(i.kind!=="fieldMap")return;let a=new Map;i.mappings.forEach((l,d)=>{let c=`${r.pathPrefix}effects[${o}].mappings[${d}]`;n.has(l.from)&&t.push({severity:"error",path:`${c}.from`,code:"fieldmap.computed-source",message:`Effect '${i.id}' fieldMap '${l.from}' \u2192 '${l.to}': '${l.from}' is a computed field. Its value is derived, never stored, and would never reach the party.`});let u=a.get(l.to);u!==void 0&&u!==l.from?t.push({severity:"error",path:`${c}.to`,code:"fieldmap.duplicate-target",message:`Effect '${i.id}' maps both '${u}' and '${l.from}' onto custom field '${l.to}'. One party field holds one value \u2014 the write would keep one and drop the other.`}):a.set(l.to,l.from)})});return t}s(aV,"validateFieldMapSources");function lV(e){let t=[],n=new Set;for(let o of sV(e))for(let a of o.effects)if(a.kind==="fieldMap")for(let l of a.mappings)n.add(l.from);let r=s((o,a)=>{let l=a.some(d=>n.has(d));o.kind==="cf_value"&&!l?t.push({severity:"error",path:`field '${o.key}'`,code:"persist.cf-unmapped",message:`Field '${o.key}' declares kind 'cf_value' but is not the source of any fieldMap mapping. Either wire a fieldMap ('${o.key}' \u2192 a custom-field key) or set kind: 'control'.`}):o.kind==="control"&&l&&t.push({severity:"error",path:`field '${o.key}'`,code:"persist.control-mapped",message:`Field '${o.key}' declares kind 'control' but is used as a fieldMap source, which would persist it. Set kind: 'cf_value', or remove the fieldMap mapping (a control field may still feed OutcomeDef.output.fields).`})},"check"),i=s(o=>{o.fields.forEach(a=>r(a,[a.key])),o.groups?.forEach(a=>a.fields.forEach(l=>r(l,[l.key]))),o.repeated?.forEach(a=>a.itemTemplate.forEach(l=>r(l,[`$item.${l.key}`,l.key]))),o.subsections?.forEach(i)},"visit");return e.sections.forEach(i),t}s(lV,"validateFieldPersistence");var lX="$";function dX(e){return typeof e=="string"&&e.startsWith(lX)}s(dX,"isRef");function og(e){return e.slice(1)}s(og,"stripRef");function*cX(e){switch(e.kind){case"relationship":if(yield e.from,yield e.to,e.meta)for(let t of Object.values(e.meta))yield t;return;case"fieldMap":yield e.target;return;case"shareValue":yield e.from,yield e.to;return;case"person":case"organization":return}}s(cX,"refSlots");function uX(e){let t=new Set;for(let n of cX(e))dX(n)&&t.add(og(n));return[...t]}s(uX,"collectRefs");function fX(e){let t=new Set(e.map(o=>o.id)),n=new Map,r=new Map,i=new Map;for(let o of e)i.set(o.id,o),n.set(o.id,[]),r.set(o.id,[]);for(let o of e)for(let a of uX(o))t.has(a)&&(n.get(o.id).push(a),r.get(a).push(o.id));for(let o of e){if(o.kind!=="shareValue")continue;let a=og(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&og(l.target)===a||l.kind==="shareValue"&&og(l.to)===a)||n.get(o.id).includes(l.id)||(n.get(o.id).push(l.id),r.get(l.id).push(o.id))}return{refsOf:n,successors:r,byId:i}}s(fX,"buildAdjacency");function dV(e){let{refsOf:t}=fX(e),r=Ym(e.map(i=>i.id),i=>(t.get(i)??[]).map(o=>({target:o,edge:null})))[0];return r===void 0?{hasCycle:!1}:{hasCycle:!0,cycle:r.cycle}}s(dV,"detectCycle");function cV(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(cV,"escapeRegExp");function _o(e){return new RegExp(`^${cV(e)}\\[(\\d+)\\]\\.(.+)$`)}s(_o,"repeatedRowKeyPattern");function hA(e,t){let n=_o(t),r=0;for(let i of Object.keys(e)){let o=i.match(n);if(!o)continue;let a=Number(o[1]);Number.isInteger(a)&&a+1>r&&(r=a+1)}return r}s(hA,"countRepeatedRows");function uV(e,t,n){let r=_o(t);for(let[i,o]of Object.entries(e)){let a=i.match(r);if(!(!a||Number(a[1])!==n)&&o!=null&&!(typeof o=="string"&&o.trim()==="")&&!(Array.isArray(o)&&o.length===0))return!0}return!1}s(uV,"repeatedRowHasData");function fV(e){return e.endsWith(".count")?e.slice(0,-6):e}s(fV,"readKeyOf");function gA(e){return{sections:e,fields:[]}}s(gA,"hiddenSectionsOnly");function pV(e,t,n){for(let r of e.fields)t.add(r.key);for(let r of e.groups??[])for(let i of r.fields)t.add(i.key);for(let r of e.computed??[])t.add(r.key);for(let r of e.repeated??[])n.add(r.key);for(let r of e.subsections??[])pV(r,t,n)}s(pV,"collectKeys");function mV(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;pV(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(_o)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(mV,"restrictedSectionsOf");function hV(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(hV,"matchesKey");function pX(e,t){return t.find(n=>hV(e,n))??null}s(pX,"hiddenSectionOfKey");function mX(e,t){for(let n=e;;){if(hV(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(mX,"fieldOwnsKey");function hX(e,t){return t.find(n=>mX(e,n))??null}s(hX,"restrictedFieldOfKey");function gX(e,t){let n=pX(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=hX(e,t.fields);return r===null?null:{kind:"field",field:r}}s(gX,"hiddenOwnerOfKey");function sg(e,t){return gX(e,t)!==null}s(sg,"isKeyHidden");function yX(e,t,n,r,i){let o=[];r&&o.push({severity:"error",path:n,code:"section.visibleTo-nested",message:{de:`Abschnitt '${e}' liegt in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) und darf selbst keine tragen.`,en:`Section '${e}' sits inside a section with restricted visibility (visibleTo) and may not carry one itself.`}});let a=s(l=>typeof l!="string"||l.trim()==="","isBlank");if((t.length===0||t.some(a)||new Set(t).size!==t.length)&&o.push({severity:"error",path:n,code:"section.visibleTo-invalid",message:{de:`Abschnitt '${e}': visibleTo braucht mindestens ein Team, ohne leere oder doppelte Eintr\xE4ge.`,en:`Section '${e}': visibleTo needs at least one team, with no blank or repeated entries.`}}),i===void 0)return o;for(let l of t)a(l)||i.has(l)||o.push({severity:"error",path:n,code:"section.visibleTo-unknown",message:{de:`Abschnitt '${e}': '${l}' ist weder ein Team noch eine Rechtegruppe dieser Schule.`,en:`Section '${e}': '${l}' is neither a team nor a permission group of this school.`}});return o}s(yX,"visibleToListIssues");function gV(e,t,n){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...yX(c.id,h,`${u}.visibleTo`,p,n));let y=p||h!==void 0;if(y){let b=[...c.fields,...(c.groups??[]).flatMap(k=>k.fields),...(c.repeated??[]).flatMap(k=>k.itemTemplate)];for(let k of b)k.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${k.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${k.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((b,k)=>i(b,`${u}.subsections[${k}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=mV(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=gA(p);for(let y of qt(c)){let b=fV(y);(sg(y,h)||sg(b,h))&&r.push({severity:"error",path:u,code:"section.visibleTo-read-outside",message:{de:`${u} liest '${y}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) \u2014 wer den Abschnitt nicht sieht, bek\xE4me hier ein anderes Ergebnis.`,en:`${u} reads '${y}' from a section with restricted visibility (visibleTo) \u2014 whoever cannot see the section would get a different result here.`}})}},"checkAst"),l=s((c,u,p)=>{a(c.visibleIf,`${u}.visibleIf`,p),a(c.requiredIf,`${u}.requiredIf`,p),a(c.disabledIf,`${u}.disabledIf`,p),a(c.defaultValue,`${u}.defaultValue`,p),c.sameAs!==void 0&&sg(c.sameAs.source,gA(p))&&r.push({severity:"error",path:`${u}.sameAs`,code:"section.visibleTo-read-outside",message:{de:`${u} \xFCbernimmt '${c.sameAs.source}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo).`,en:`${u} copies '${c.sameAs.source}' from a section with restricted visibility (visibleTo).`}})},"checkField"),d=s((c,u,p)=>{let h=c.visibleTo!==void 0?c.id:p,y=o.filter(b=>b.sectionId!==h);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((b,k)=>l(b,`${u}.fields[${k}]`,y)),c.groups?.forEach((b,k)=>{a(b.visibleIf,`${u}.groups[${k}].visibleIf`,y),b.fields.forEach((v,A)=>l(v,`${u}.groups[${k}].fields[${A}]`,y))}),c.repeated?.forEach((b,k)=>{a(b.itemVisibleIf,`${u}.repeated[${k}].itemVisibleIf`,y),b.itemTemplate.forEach((v,A)=>l(v,`${u}.repeated[${k}].itemTemplate[${A}]`,y))}),c.computed?.forEach((b,k)=>a(b.expression,`${u}.computed[${k}]`,y)),c.subsections?.forEach((b,k)=>d(b,`${u}.subsections[${k}]`,h))},"visitCompiled");return t.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(gV,"sectionVisibilityIssues");var hi="#";var yV=s(e=>{let t=Kv.find(n=>n.systemColumn===e);return t===void 0&&F(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),qr={firstName:yV("persons.firstName"),lastName:yV("persons.lastName")};function wV(e,t){let n={firstName:[],lastName:[]},r=`$${e}`;for(let i of t)if(!(i.kind!=="fieldMap"||i.target!==r))for(let{from:o,to:a}of i.mappings??[])a===qr.firstName?n.firstName.push(o):a===qr.lastName&&n.lastName.push(o);return n}s(wV,"personNameKeys");function kV(e){return[...e.firstName,...e.lastName]}s(kV,"personNameKeyList");function bV(e){return e.firstName.length>0||e.lastName.length>0}s(bV,"hasPersonName");function dl(e,t=[],n){let r=[];return e.forEach((i,o)=>{let a=[...t,o];r.push({section:i,path:a,parentId:n});for(let l of dl(i.subsections??[],a,i.id))r.push(l)}),r}s(dl,"walkSections");function wX(e,t){for(let n of e.fields)if(n.key===t)return n;for(let n of e.groups??[])for(let r of n.fields)if(r.key===t)return r;for(let n of e.repeated??[])for(let r of n.itemTemplate)if(r.key===t)return r;return null}s(wX,"findFieldInSection");function vV(e,t){for(let n of dl(e.sections)){let r=wX(n.section,t);if(r)return{section:n.section,field:r}}return null}s(vV,"findField");var kX=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],bX=["blue","rose","amber","violet","teal","emerald","slate"];function xV(e){return kX.includes(e)}s(xV,"isBucketIconName");function SV(e){return bX.includes(e)}s(SV,"isBucketColorName");var vX="__clear__";function AV(e){return e===""?"empty":e===vX?"reserved":null}s(AV,"selectOptionValueDefect");var yA=CM.docRef.allowedMime;function OV(e,t={}){let n=Ka(e).compiled,r=[],i=new Set,o=new Map,a=new Set,l=new Set,d=new Set,c=new Map,u=new Map;function p(O,_){if(i.has(O))return;i.add(O);let V=o.get(O.id);V&&V!==O?r.push({severity:"error",path:`sections[${_.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${O.id}' ist mehrfach deklariert.`,en:`Section id '${O.id}' is declared more than once.`}}):o.set(O.id,O);let M=`sections[${_.join(".")}]`;O.fields.forEach((W,ce)=>{cl(a,W.key,`${M}.fields[${ce}]`,"duplicate.field-key",r),l.add(W.key),u.set(W.key,W),c.set(W.key,kA(W)),W.externalFlag&&(W.type!=="boolean"&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${W.key}' muss den Typ 'boolean' haben (ist '${W.type}').`,en:`External flag '${W.key}' must be type 'boolean' (got '${W.type}').`}}),W.reviewRequired!==void 0&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"review.on-flag",message:{de:`Externes Flag '${W.key}' ist als pr\xFCfpflichtig markiert \u2014 ein Flag setzt der Prozess, die Familie reicht nichts ein, was jemand pr\xFCfen k\xF6nnte.`,en:`External flag '${W.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),W.notice!==void 0&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${W.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${W.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),W.defaultValue==null&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"flag.missing-default",message:{de:`Externes Flag '${W.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${W.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...RV(W,`${M}.fields[${ce}]`)),r.push(...TV(W,`${M}.fields[${ce}]`))}),O.groups?.forEach((W,ce)=>{W.fields.forEach((fe,Le)=>{cl(a,fe.key,`${M}.groups[${ce}].fields[${Le}]`,"duplicate.field-key",r),l.add(fe.key),u.set(fe.key,fe),c.set(fe.key,kA(fe)),fe.externalFlag&&r.push({severity:"error",path:`${M}.groups[${ce}].fields[${Le}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${fe.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${fe.key}' must be a direct section field, not a group field.`}}),r.push(...RV(fe,`${M}.groups[${ce}].fields[${Le}]`)),r.push(...TV(fe,`${M}.groups[${ce}].fields[${Le}]`))})}),O.repeated?.forEach((W,ce)=>{W.itemTemplate.forEach((fe,Le)=>{cl(a,fe.key,`${M}.repeated[${ce}].itemTemplate[${Le}]`,"duplicate.field-key",r),c.set(fe.key,kA(fe)),fe.externalFlag&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${fe.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${fe.key}' must be a direct section field, not a repeated item field.`}}),fe.export&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"export.in-repeated",message:{de:`Feld '${fe.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${fe.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),fe.sameAs&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${fe.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${fe.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),fe.reviewRequired!==void 0&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"review.in-repeated",message:{de:`Feld '${fe.key}' ist in einem itemTemplate einer Wiederholung als pr\xFCfpflichtig markiert \u2014 ein Zeilenfeld hat je Zeile einen Wert, kein Feld der Bewerbung, das man einmal abhaken k\xF6nnte.`,en:`Field '${fe.key}' is marked as requiring review inside a repeated itemTemplate \u2014 a row field has one value per row, no field of the application to tick once.`}}),fe.notice!==void 0&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"config.notice-in-repeated",message:{de:`Feld '${fe.key}' tr\xE4gt einen Hinweis (notice) in einem itemTemplate einer Wiederholung \u2014 dort wird er nicht angezeigt. Den Hinweis an den Abschnitt setzen.`,en:`Field '${fe.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),fe.type==="docRef"&&fe.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${fe.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${fe.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),O.computed?.forEach(W=>{d.add(W.key),cl(a,W.key,`${M}.computed[${W.key}]`,"duplicate.field-key",r),W.exportType==="consent"&&r.push({severity:"error",path:`${M}.computed[${W.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${W.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${W.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),W.export===!0&&W.exportType===void 0&&r.push({severity:"error",path:`${M}.computed[${W.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${W.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${W.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),O.subsections?.forEach((W,ce)=>p(W,[..._,ce]))}s(p,"visitRawSection"),e.sections.forEach((O,_)=>p(O,[_]));let h=new Set;n.effects.forEach((O,_)=>{cl(h,O.id,`effects[${_}]`,"duplicate.effect-id",r)});let y=new Set;n.outcomes.forEach((O,_)=>{cl(y,O.id,`outcomes[${_}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((O,_)=>{O.output.effectRefs?.forEach((V,M)=>{h.has(V.effect)||r.push({severity:"error",path:`outcomes[${_}].output.effectRefs[${M}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${O.id}' verweist auf den unbekannten Effekt '${V.effect}'.`,en:`Outcome '${O.id}' references unknown effect '${V.effect}'.`}})})}),n.outcomes.forEach((O,_)=>{O.output.fields?.forEach((V,M)=>{vV(n,V.path)||r.push({severity:"error",path:`outcomes[${_}].output.fields[${M}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${O.id}' verweist auf das unbekannte Feld '${V.path}'.`,en:`Outcome '${O.id}' references unknown field '${V.path}'.`}})})});let b=new Set;for(let O of dl(n.sections))for(let _ of O.section.repeated??[])b.add(`${_.key}.count`);for(let O of b)(a.has(O)||d.has(O))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${O}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${O}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let k={known:new Set([...a,...d,...b]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...PF(e)),r.push(...gV(e,n,t.visibleToKeys)),r.push(...bL(e));for(let O of dl(n.sections)){let _=O.section,V=`sections[${O.path.join(".")}]`;_.visibleIf&&(Kr(_.visibleIf,`${V}.visibleIf`,k,!1,r),ul(_.visibleIf,`${V}.visibleIf`,c,r)),_.fields.forEach((M,W)=>wA(M,`${V}.fields[${W}]`,k,!1,c,r)),_.groups?.forEach((M,W)=>{M.visibleIf&&(Kr(M.visibleIf,`${V}.groups[${W}].visibleIf`,k,!1,r),ul(M.visibleIf,`${V}.groups[${W}].visibleIf`,c,r)),M.fields.forEach((ce,fe)=>wA(ce,`${V}.groups[${W}].fields[${fe}]`,k,!1,c,r))}),_.repeated?.forEach((M,W)=>{M.itemVisibleIf&&(Kr(M.itemVisibleIf,`${V}.repeated[${W}].itemVisibleIf`,k,!0,r),ul(M.itemVisibleIf,`${V}.repeated[${W}].itemVisibleIf`,c,r)),M.itemTemplate.forEach((ce,fe)=>wA(ce,`${V}.repeated[${W}].itemTemplate[${fe}]`,k,!0,c,r)),M.effects?.forEach((ce,fe)=>{ce.when&&Kr(ce.when,`${V}.repeated[${W}].effects[${fe}].when`,k,!0,r)})}),_.computed?.forEach((M,W)=>Kr(M.expression,`${V}.computed[${W}].expression`,k,!1,r))}n.effects.forEach((O,_)=>{O.when&&Kr(O.when,`effects[${_}].when`,k,!1,r)}),n.outcomes.forEach((O,_)=>{Kr(O.when,`outcomes[${_}].when`,k,!1,r)});let v=new Set(n.outcomes.map(O=>O.id));function A(O,_){O.requiredFor&&O.requiredFor.forEach((V,M)=>{v.has(V)||r.push({severity:"error",path:`${_}.requiredFor[${M}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${O.key}": requiredFor verweist auf das unbekannte Ergebnis "${V}"`,en:`field "${O.key}": requiredFor references unknown outcome "${V}"`}})})}s(A,"checkRequiredFor");for(let O of dl(n.sections)){let _=O.section,V=`sections[${O.path.join(".")}]`;_.fields.forEach((M,W)=>A(M,`${V}.fields[${W}]`)),_.groups?.forEach((M,W)=>{M.fields.forEach((ce,fe)=>A(ce,`${V}.groups[${W}].fields[${fe}]`))}),_.repeated?.forEach((M,W)=>{M.itemTemplate.forEach((ce,fe)=>A(ce,`${V}.repeated[${W}].itemTemplate[${fe}]`))})}function T(O,_){let V=s((M,W)=>{let ce=(M.type==="docRef"?M.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!yA.includes(Ee));ce.length>0&&r.push({severity:"error",path:W,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${M.key}' erlaubt ${ce.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${yA.join(", ")}).`,en:`Field '${M.key}' allows ${ce.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${yA.join(", ")}).`}});let fe=M.type==="docRef"?M.docRefConstraints?.minFiles:void 0;if(fe!==void 0){let Ee=M.docRefConstraints?.multiple===!0,wt=typeof fe=="number"&&Number.isInteger(fe)&&fe>=2;(!Ee||!wt)&&r.push({severity:"error",path:W,code:"config.docref-min-files",message:Ee?{de:`Feld '${M.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(fe)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${M.key}' sets docRefConstraints.minFiles to ${JSON.stringify(fe)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${M.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${M.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}M.multiple===!0&&M.type!=="enum"&&r.push({severity:"error",path:W,code:"config.multiple-non-enum",message:{de:`Feld '${M.key}' setzt multiple: true, hat aber den Typ '${M.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(M.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${M.key}' sets multiple: true but is type '${M.type}' \u2014 only 'enum' supports multi-select.`+(M.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),M.presentation==="yesNo"&&M.type!=="boolean"&&r.push({severity:"error",path:W,code:"config.yesno-non-boolean",message:{de:`Feld '${M.key}' setzt presentation: 'yesNo', hat aber den Typ '${M.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${M.key}' sets presentation: 'yesNo' but is type '${M.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),M.presentation==="yesNo"&&M.defaultValue!=null&&r.push({severity:"error",path:W,code:"config.yesno-default",message:{de:`Feld '${M.key}' ist eine Ja | Nein-Frage (presentation: 'yesNo') mit einem defaultValue \u2014 die Familie muss die Antwort selbst w\xE4hlen. Den defaultValue entfernen.`,en:`Field '${M.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...SX(M,W)),typeof M.minSelections=="number"&&typeof M.maxSelections=="number"&&M.minSelections>M.maxSelections&&r.push({severity:"error",path:W,code:"config.min-gt-max-selections",message:{de:`Feld '${M.key}' hat minSelections (${M.minSelections}) > maxSelections (${M.maxSelections}).`,en:`Field '${M.key}' has minSelections (${M.minSelections}) > maxSelections (${M.maxSelections}).`}}),r.push(...AX(M,W));let Le=M.enumRef;Le!==void 0&&r.push({severity:"error",path:`${W}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${M.key}' nennt den entfernten Options-Katalog (enumRef '${String(Le)}'). Die Optionen im Formular angeben (enumOptions + enumOptionLabels) oder eine Liste des Mandanten binden (enumListKey).`,en:`Field '${M.key}' names the removed option catalog (enumRef '${String(Le)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(M.enumOptions??[]).forEach((Ee,wt)=>{let nt=AV(Ee);nt!==null&&r.push({severity:"error",path:`${W}.enumOptions[${wt}]`,code:"config.enum-option-value",message:{de:nt==="empty"?`Feld '${M.key}' hat einen leeren Enum-Optionswert \u2014 das Steuerelement kann ihn nicht tragen. Der Option einen Wert geben oder sie streichen: Ein Feld, das unbeantwortet bleiben darf, bietet bereits eine eigene Zeile zum Leeren.`:`Feld '${M.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:nt==="empty"?`Field '${M.key}' has an empty enum option value \u2014 the control cannot carry it. Give the option a value, or drop it: a field that may be left unanswered already offers its own clear row.`:`Field '${M.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(M.attachments??[]).forEach((Ee,wt)=>{if("storageId"in Ee){r.push({severity:"error",path:`${W}.attachments[${wt}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${M.key}' tr\xE4gt eine rohe 'storageId' \u2014 Anh\xE4nge nennen eine Bibliotheksdatei jetzt per 'fileKey' (plexus-cli files put, dann field attach --file-key).`,en:`Field '${M.key}' attachment carries a raw 'storageId' \u2014 attachments name a library file by 'fileKey' now (plexus-cli files put, then field attach --file-key).`}});return}let nt=Ee.fileKey!==void 0&&Ee.fileKey!=="",$t=Ee.url!==void 0&&Ee.url!=="";nt===$t&&r.push({severity:"error",path:`${W}.attachments[${wt}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${M.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${nt&&$t?"beide":"keines"}).`,en:`Field '${M.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${nt&&$t?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${W}.attachments[${wt}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${M.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${M.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");O.fields.forEach((M,W)=>V(M,`${_}.fields[${W}]`)),O.groups?.forEach((M,W)=>{M.fields.forEach((ce,fe)=>V(ce,`${_}.groups[${W}].fields[${fe}]`))}),O.repeated?.forEach((M,W)=>{M.itemTemplate.forEach((ce,fe)=>{let Le=`${_}.repeated[${W}].itemTemplate[${fe}]`;V(ce,Le),ce.type==="consent"&&r.push({severity:"error",path:Le,code:"config.consent-in-repeated",message:{de:`Feld '${ce.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${ce.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),O.subsections?.forEach((M,W)=>T(M,`${_}.subsections[${W}]`))}s(T,"visitFieldConfig"),e.sections.forEach((O,_)=>T(O,`sections[${_}]`)),e.effects.forEach((O,_)=>{if(O.kind==="person"){r.push(...IV(O,e.effects,`effects[${_}]`,V=>l.has(V)));return}O.kind==="organization"&&O.nameFrom?.forEach((V,M)=>{l.has(V)||r.push({severity:"error",path:`effects[${_}].nameFrom[${M}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${O.id}': nameFrom verweist auf das unbekannte Feld '${V}'.`,en:`Effect '${O.id}' nameFrom references unknown field '${V}'.`}})})});let I=s((O,_)=>{if(O.kind!=="person"&&O.kind!=="organization")return;let V=O.display;if(!V){r.push({severity:"error",path:`${_}.display`,code:"display.missing",message:{de:`Effekt '${O.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${O.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}xV(V.icon)||r.push({severity:"error",path:`${_}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${O.id}': display.icon '${V.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${O.id}' display.icon '${V.icon}' is not a known bucket icon.`}}),SV(V.color)||r.push({severity:"error",path:`${_}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${O.id}': display.color '${V.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${O.id}' display.color '${V.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((O,_)=>I(O,`effects[${_}]`));let C=new Set,L=s(O=>{O.kind==="person"?C.add(O.bucket):O.kind==="organization"&&C.add(O.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(L);let N=new Set,x=s(O=>{for(let _ of O)_.repeated?.forEach(V=>V.effects?.forEach(M=>L(M))),x(_.subsections??[])},"collectRepeatedBuckets");x(e.sections);let D=s((O,_)=>{C.size!==0&&O.forEach((V,M)=>{V.bucket===void 0||C.has(V.bucket)||r.push({severity:"error",path:`${_}[${M}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${V.key}' geh\xF6rt zum Bucket '${V.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${V.key}' belongs to bucket '${V.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),R=s((O,_)=>{if(N.has(O))return;N.add(O);let V=`sections[${_.join(".")}]`;D(O.fields,`${V}.fields`),O.groups?.forEach((M,W)=>D(M.fields,`${V}.groups[${W}].fields`)),O.repeated?.forEach((M,W)=>D(M.itemTemplate,`${V}.repeated[${W}].itemTemplate`)),O.subsections?.forEach((M,W)=>R(M,[..._,W]))},"visitBucketSection");e.sections.forEach((O,_)=>R(O,[_]));let q=e.effects.flatMap((O,_)=>O.kind==="person"&&O.subject===!0?[{e:O,i:_}]:[]);q.length>1&&q.slice(1).forEach(({e:O,i:_})=>{r.push({severity:"error",path:`effects[${_}].subject`,code:"subject.duplicate",message:{de:`Effekt '${O.id}' deklariert subject:true, aber '${q[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${O.id}' declares subject:true, but '${q[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((O,_)=>{if(!(O.kind!=="person"||O.nationalityFrom===void 0)){if(O.subject!==!0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${O.id}' deklariert nationalityFrom, ist aber nicht das Subjekt der Bewerbung \u2014 die Staatsangeh\xF6rigkeit wird nur f\xFCr das Subjekt der Bewerbung gelesen.`,en:`Effect '${O.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(O.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${O.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${O.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}O.nationalityFrom.forEach((V,M)=>{l.has(V)||r.push({severity:"error",path:`effects[${_}].nationalityFrom[${M}]`,code:"nationality.unknown-field",message:{de:`Effekt '${O.id}': nationalityFrom verweist auf das unbekannte Feld '${V}'.`,en:`Effect '${O.id}' nationalityFrom references unknown field '${V}'.`}})})}});let G=e.effects.flatMap((O,_)=>O.kind==="person"&&O.contractParty!==void 0?[{e:O,i:_,decl:O.contractParty}]:[]);if(G.length>0){let O=new Map;G.forEach(({e:V,i:M})=>{let W=O.get(V.bucket);if(W===void 0){O.set(V.bucket,V.id);return}r.push({severity:"error",path:`effects[${M}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${V.id}' deklariert eine Vertragspartei auf Bucket '${V.bucket}', aber '${W}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${V.id}' declares a contract party on bucket '${V.bucket}', but '${W}' already does. A bucket is at most one contract party.`}})});let _=G.filter(({decl:V})=>V.role==="beneficiary");_.slice(1).forEach(({e:V,i:M})=>{r.push({severity:"error",path:`effects[${M}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${V.id}' deklariert contractParty.role 'beneficiary', aber '${_[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${V.id}' declares contractParty.role 'beneficiary', but '${_[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),_.forEach(({e:V,i:M})=>{V.subject!==!0&&r.push({severity:"error",path:`effects[${M}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${V.id}' ist der Leistungsempf\xE4nger des Vertrags, aber nicht das Subjekt der Bewerbung. Leistungsempf\xE4nger und Subjekt der Bewerbung sind dieselbe Person \u2014 subject:true auf '${V.id}' setzen.`,en:`Effect '${V.id}' is the contract beneficiary but not the application subject. The beneficiary and the application subject are the same person \u2014 set subject:true on '${V.id}'.`}})}),q.forEach(({e:V,i:M})=>{let W=V.contractParty?.role;W!==void 0&&W!=="beneficiary"&&r.push({severity:"error",path:`effects[${M}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${V.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${W}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${V.id}' is the application subject but declares contractParty.role '${W}'. The application subject is the contract beneficiary.`}})}),G.some(({decl:V})=>V.signs===!0)||r.push({severity:"error",path:"effects",code:"contractParty.no-signer",message:{de:"Das Formular deklariert Vertragsparteien, aber keine unterschreibt (contractParty.signs). Ein Vertrag ohne Unterzeichner kann nicht erzeugt werden.",en:"The form declares contract parties, but none signs (contractParty.signs). A contract without a signatory cannot be generated."}})}e.effects.forEach((O,_)=>{O.kind==="fieldMap"&&O.mappings.forEach((V,M)=>{a.has(V.from)||r.push({severity:"error",path:`effects[${_}].mappings[${M}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${O.id}': fieldMap from '${V.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${O.id}' fieldMap from '${V.from}' references unknown field.`}})})});for(let[O,_]of u){if(!_.sameAs)continue;let V=`fields[${O}].sameAs`,M=u.get(_.sameAs.source);M===void 0||_.sameAs.source===O?r.push({severity:"error",path:`${V}.source`,code:"ref.unknown-sameas-source",message:{de:_.sameAs.source===O?`Feld '${O}': sameAs.source verweist auf sich selbst.`:`Feld '${O}': sameAs.source verweist auf das unbekannte Feld '${_.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:_.sameAs.source===O?`Field '${O}' sameAs.source references itself.`:`Field '${O}' sameAs.source references unknown field '${_.sameAs.source}' (must be a top-level or group field).`}}):M.type!==_.type?r.push({severity:"error",path:`${V}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}' (${_.type}): sameAs.source '${_.sameAs.source}' hat einen anderen Typ (${M.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${O}' (${_.type}) sameAs.source '${_.sameAs.source}' has a different type (${M.type}) \u2014 the mirror must be shape-identical.`}}):M.sameAs&&r.push({severity:"error",path:`${V}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}': sameAs.source '${_.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${O}' sameAs.source '${_.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let W=u.get(_.sameAs.toggle);(W===void 0||W.type!=="boolean")&&r.push({severity:"error",path:`${V}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:W===void 0?`Feld '${O}': sameAs.toggle verweist auf das unbekannte Feld '${_.sameAs.toggle}'.`:`Feld '${O}': sameAs.toggle '${_.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${W.type}').`,en:W===void 0?`Field '${O}' sameAs.toggle references unknown field '${_.sameAs.toggle}'.`:`Field '${O}' sameAs.toggle '${_.sameAs.toggle}' must be type 'boolean' (got '${W.type}').`}}),_.required===!0&&r.push({severity:"error",path:`fields[${O}].required`,code:"config.sameas-static-required",message:{de:`Feld '${O}' deklariert sameAs, ist aber statisch Pflicht \u2014 solange es gespiegelt ist, hat es keinen eigenen Wert, die Slice-Validierung beim Commit w\xFCrde immer scheitern. required: false + requiredIf: "${_.sameAs.toggle} != true" verwenden.`,en:`Field '${O}' declares sameAs but is statically required \u2014 while mirrored it holds no own value, so commit-time slice validation would always fail. Use required: false + requiredIf: "${_.sameAs.toggle} != true".`}})}{let O=new Map;e.effects.forEach(_=>O.set(_.id,_.kind)),e.effects.forEach((_,V)=>{if(_.kind!=="shareValue")return;[["from",_.from],["to",_.to]].forEach(([ce,fe])=>{let Le=O.get(fe.slice(1));Le!==void 0&&Le!=="person"&&Le!=="organization"&&r.push({severity:"error",path:`effects[${V}].${ce}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${_.id}': shareValue ${ce} '${fe}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${Le}').`,en:`Effect '${_.id}' shareValue ${ce} '${fe}' must reference a person/organization effect (got '${Le}').`}})});let M=_.from.slice(1);e.effects.some(ce=>ce.kind==="fieldMap"&&ce.target.slice(1)===M&&ce.mappings.some(fe=>fe.to===_.field)||ce.kind==="shareValue"&&ce.id!==_.id&&ce.to.slice(1)===M&&ce.field===_.field)||r.push({severity:"error",path:`effects[${V}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${_.id}' teilt das Feld '${_.field}' aus '${_.from}', aber kein fieldMap mit Ziel '${_.from}' bildet auf '${_.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${_.id}' shares field '${_.field}' from '${_.from}', but no fieldMap targeting '${_.from}' maps to '${_.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((O,_)=>{O.kind==="person"&&O.bucket.includes(hi)&&r.push({severity:"error",path:`effects[${_}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': bucket '${O.bucket}' darf '${hi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' bucket '${O.bucket}' must not contain '${hi}' (reserved for the per-row namespace).`}}),O.kind==="organization"&&O.orgKind.includes(hi)&&r.push({severity:"error",path:`effects[${_}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': orgKind '${O.orgKind}' darf '${hi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' orgKind '${O.orgKind}' must not contain '${hi}' (reserved for the per-row namespace).`}})});let ae=new Set;function Z(O,_){O.repeated?.forEach((V,M)=>{let W=V.effects??[];if(W.length>0){let ce=`${_}.repeated[${M}]`,fe=new Set(W.map(le=>le.id)),Le=new Set(V.itemTemplate.map(le=>le.key)),Ee=(V.uniqueBy?.length??0)>0,wt=s(le=>le.startsWith("$item.")?Le.has(le.slice(6)):l.has(le),"resolvesName"),nt=s(le=>le.startsWith("$item.")?Le.has(le.slice(6)):a.has(le),"resolvesFrom"),$t=s(le=>{let Qt=le.slice(1);return fe.has(Qt)||h.has(Qt)},"resolvesRef");W.forEach((le,Qt)=>{let kt=`${ce}.effects[${Qt}]`;if(h.has(le.id)||ae.has(le.id)?r.push({severity:"error",path:kt,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${le.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${le.id}' is declared more than once.`}}):ae.add(le.id),le.kind==="person"||le.kind==="organization"){I(le,kt),le.kind==="person"&&le.subject===!0&&r.push({severity:"error",path:`${kt}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${le.id}' der Wiederholung deklariert subject:true \u2014 eine Zeile gilt je Zeile, das Subjekt der Bewerbung je Bewerbung. Das Subjekt an einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${le.id}' declares subject:true \u2014 a repeated row is per-row, the application subject is per-application. Declare the subject on a top-level effect.`}}),le.kind==="person"&&le.nationalityFrom!==void 0&&r.push({severity:"error",path:`${kt}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${le.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${le.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),le.kind==="person"&&le.contractParty!==void 0&&r.push({severity:"error",path:`${kt}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${le.id}' der Wiederholung deklariert contractParty \u2014 wer unterschreibt, wird einmal je Bewerbung deklariert, nicht je Zeile. An einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${le.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ee||r.push({severity:"error",path:ce,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${V.key}' hat einen Parteien erzeugenden Effekt '${le.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${V.key}' has a party-creating effect '${le.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Me=le.kind==="person"?le.bucket:le.orgKind;Me.includes(hi)&&r.push({severity:"error",path:`${kt}.${le.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${le.id}' der Wiederholung: ${le.kind==="person"?"bucket":"orgKind"} '${Me}' darf '${hi}' nicht enthalten.`,en:`Repeated effect '${le.id}' ${le.kind==="person"?"bucket":"orgKind"} '${Me}' must not contain '${hi}'.`}}),le.kind==="person"&&r.push(...IV(le,W,kt,wt)),le.kind==="organization"&&le.nameFrom?.forEach((We,Bn)=>{wt(We)||r.push({severity:"error",path:`${kt}.nameFrom[${Bn}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${le.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${We}'.`,en:`Repeated effect '${le.id}' nameFrom references unknown field '${We}'.`}})}),le.identity?.strategy==="keyed"&&le.identity.keyFrom.forEach((We,Bn)=>{nt(We)||r.push({severity:"error",path:`${kt}.identity.keyFrom[${Bn}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${le.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${We}'.`,en:`Repeated effect '${le.id}' identity.keyFrom references unknown field '${We}'.`}})})}else if(le.kind==="relationship"){if([["from",le.from],["to",le.to]].forEach(([Me,We])=>{$t(We)||r.push({severity:"error",path:`${kt}.${Me}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${le.id}' der Wiederholung: ${Me} verweist auf den unbekannten Effekt '${We}'.`,en:`Repeated relationship '${le.id}' ${Me} references unknown effect '${We}'.`}})}),le.meta)for(let[Me,We]of Object.entries(le.meta))typeof We=="string"&&We.startsWith("$")&&!$t(We)&&r.push({severity:"error",path:`${kt}.meta.${Me}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${le.id}' der Wiederholung: meta.${Me} verweist auf den unbekannten Effekt '${We}'.`,en:`Repeated relationship '${le.id}' meta.${Me} references unknown effect '${We}'.`}})}else le.kind==="fieldMap"?($t(le.target)||r.push({severity:"error",path:`${kt}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${le.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${le.target}'.`,en:`Repeated fieldMap '${le.id}' target references unknown effect '${le.target}'.`}}),le.mappings.forEach((Me,We)=>{nt(Me.from)||r.push({severity:"error",path:`${kt}.mappings[${We}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${le.id}' der Wiederholung: from '${Me.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${le.id}' from '${Me.from}' references unknown field.`}})})):le.kind==="shareValue"&&r.push({severity:"error",path:kt,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${le.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${le.id}': shareValue is not supported inside repeated row effects.`}})})}}),O.subsections?.forEach((V,M)=>Z(V,`${_}.subsections[${M}]`))}s(Z,"visitRepeatedEffects"),e.sections.forEach((O,_)=>Z(O,`sections[${_}]`));let oe=dV(n.effects);return oe.hasCycle&&r.push({severity:"error",path:"effects",code:"graph.effect-cycle",message:{de:`Der Effektgraph enth\xE4lt einen Zyklus: ${oe.cycle?.join(" \u2192 ")??"?"}`,en:`Effect graph contains a cycle: ${oe.cycle?.join(" \u2192 ")??"?"}`}}),r.push(...xX(e)),r}s(OV,"validateForm");function xX(e){let t={...e,effects:e.effects.map(_V),sections:e.sections.map(NV),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return Nm(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:Ab(n)}))}s(xX,"missingTranslationIssues");function _V(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(_V,"withoutSubjectFlag");function NV(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(_V)})),subsections:e.subsections?.map(NV)}}s(NV,"withoutRowSubjectFlags");function TV(e,t){let n=e.reviewRequired;return n===void 0||n===!0?[]:[{severity:"error",path:t,code:"review.shape",message:{de:`Feld '${e.key}' setzt reviewRequired auf ${JSON.stringify(n)} \u2014 erlaubt ist nur true; ein nicht pr\xFCfpflichtiges Feld l\xE4sst die Angabe weg.`,en:`Field '${e.key}' sets reviewRequired to ${JSON.stringify(n)} \u2014 only true is allowed; a field that needs no review omits it.`}}]}s(TV,"reviewRequiredShapeIssues");function RV(e,t){if(!e.export)return[];let n=[];return e.type==="docRef"&&n.push({severity:"error",path:t,code:"export.invalid-type",message:{de:`Feld '${e.key}' (docRef) kann nicht exportiert werden \u2014 ein Speicher-Handle ist kein bindbarer Dokumentwert.`,en:`Field '${e.key}' (docRef) cannot be exported \u2014 a storage handle is not a bindable document value.`}}),e.multiple===!0&&n.push({severity:"error",path:t,code:"export.multiple-enum",message:{de:`Feld '${e.key}' ist eine Mehrfachauswahl \u2014 N gew\xE4hlte Optionen sind kein einzelnes zusammengesetztes Blatt, deshalb nicht exportierbar.`,en:`Field '${e.key}' is a multi-select \u2014 N picked options are not one compound leaf, so it cannot be exported.`}}),n}s(RV,"exportGateIssues");function cl(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${$V(r,"de")} '${t}'`,en:`Duplicate ${$V(r,"en")}: '${t}'`}}):e.add(t)}s(cl,"reportIfDup");function $V(e,t){let n=s((r,i)=>t==="de"?r:i,"label");switch(e){case"duplicate.section-id":return n("Abschnitts-ID","section id");case"duplicate.field-key":return n("Feldschl\xFCssel","field key");case"duplicate.effect-id":return n("Effekt-ID","effect id");case"duplicate.outcome-id":return n("Ergebnis-ID","outcome id");case"ref.unknown-required-for-outcome":return n("requiredFor-Ergebnis","requiredFor outcome");default:return e}}s($V,"labelForCode");function wA(e,t,n,r,i,o){e.visibleIf&&(Kr(e.visibleIf,`${t}.visibleIf`,n,r,o),ul(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(Kr(e.requiredIf,`${t}.requiredIf`,n,r,o),ul(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(Kr(e.disabledIf,`${t}.disabledIf`,n,r,o),ul(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&Kr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(wA,"checkFieldAsts");function kA(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(kA,"gatingMeta");function ul(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(EV(o.left,o.right,o.op,t,n,r),EV(o.right,o.left,o.op,t,n,r)),i(o.left),i(o.right);return}case"unary":i(o.operand);return;case"if":i(o.cond),i(o.then),i(o.else);return;case"call":o.args.forEach(i);return;case"arr":o.items.forEach(i);return;default:return}}s(i,"walk"),i(e)}s(ul,"checkGatingExpr");function EV(e,t,n,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);if(a){if(a.isConsent&&t.kind==="bool"&&t.value===!1){o.push({severity:"error",path:r,code:"expr.consent-compare-false",message:{de:`Gating-Ausdruck vergleicht die Zustimmung '${e.path}' mit false \u2014 eine Zustimmung ist true oder leer, nie false. '${e.path} != true' verwenden.`,en:`Gating expression compares the consent '${e.path}' to false \u2014 a consent is true or empty, never false. Use '${e.path} != true'.`}});return}a.isBoolean&&(a.hasDefault||t.kind!=="null"&&t.kind==="bool"&&(a.isYesNo&&n==="=="||o.push({severity:"error",path:r,code:"expr.gating-compare-undefaulted-field",message:{de:`Gating-Ausdruck vergleicht das Boolean-Feld '${e.path}' ohne Standardwert per '${n}' mit einem Bool-Literal. In dreiwertiger Logik ist 'undefined ${n} ${t.value}' ${n==="=="?"false":"true"} \u2014 das Gate greift stillschweigend bei ungesetzten Werten. Dem Feld '${e.path}' einen 'defaultValue' geben (oder den Ausdruck umschreiben \u2014 z. B. '${e.path} != null' als ausdr\xFCckliche Gesetzt-Pr\xFCfung).`,en:`Gating expression compares undefaulted boolean field '${e.path}' to a bool literal via '${n}'. In three-valued logic, 'undefined ${n} ${t.value}' is ${n==="=="?"false":"true"} \u2014 the gate fires silently for unset values. Add a 'defaultValue' to field '${e.path}' (or rewrite the expression \u2014 e.g. '${e.path} != null' for an explicit set-check).`}})))}}s(EV,"inspectEqualityOperand");function Kr(e,t,n,r,i){i.push(...NF(e,n.declaredContext,t)),i.push(...Em(e,n.stageKeys,t));for(let o of qt(e))n.known.has(o)||bb(o)||r&&o.startsWith("$item.")||i.push({severity:"error",path:t,code:"ref.unknown-ident",message:{de:o.startsWith("$")?`Bezeichner '${o}' ist kein Geltungsbereich, den ein Formular liest \u2014 Umgebungsvariablen sind '$env.<key>.<field>', Wiederholungszeilen '$item.*'.`:`Bezeichner '${o}' ist weder als Feld, berechneter Schl\xFCssel noch als $item-Slot deklariert.`,en:o.startsWith("$")?`Identifier '${o}' is no scope a form reads \u2014 environment variables are '$env.<key>.<field>', repeated rows '$item.*'.`:`Identifier '${o}' is not declared as a field, computed key, or $item slot.`}})}s(Kr,"checkAst");function IV(e,t,n,r){let i=[];e.nameFrom!==void 0&&i.push({severity:"error",path:`${n}.nameFrom`,code:"person.name-from-removed",message:{de:`Effekt '${e.id}': eine Person hat kein nameFrom mehr \u2014 ihr Name ist die Feldzuordnung (fieldMap) auf ${qr.firstName} / ${qr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${qr.firstName} / ${qr.lastName}. Remove nameFrom.`}});let o=wV(e.id,t);bV(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${qr.firstName} oder ${qr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${qr.firstName} or ${qr.lastName} \u2014 the person would get no name.`}});for(let a of kV(o))r(a)||i.push({severity:"error",path:n,code:"ref.unknown-name-field",message:{de:`Effekt '${e.id}': der Name wird aus '${a}' gelesen, das kein eingegebenes Feld ist.`,en:`Effect '${e.id}': its name is read from '${a}', which is not an entered field.`}});return i}s(IV,"personNameIssues");function SX(e,t){let n=[],r=e.required===!0||e.requiredIf!==void 0;return e.type==="consent"&&(e.defaultValue!=null&&n.push({severity:"error",path:t,code:"config.consent-default",message:{de:`Feld '${e.key}' ist eine Zustimmung mit einem defaultValue \u2014 zustimmen muss die Familie selbst. Den defaultValue entfernen.`,en:`Field '${e.key}' is a consent with a defaultValue \u2014 the family must give it themselves. Remove the defaultValue.`}}),e.sameAs!==void 0&&n.push({severity:"error",path:t,code:"config.consent-computed",message:{de:`Feld '${e.key}' ist eine Zustimmung, die ein anderes Feld spiegelt (sameAs) \u2014 zustimmen muss die Familie selbst. sameAs entfernen.`,en:`Field '${e.key}' is a consent mirroring another field (sameAs) \u2014 the family must give it themselves. Remove sameAs.`}}),r||n.push({severity:"error",path:t,code:"config.consent-not-required",message:{de:`Feld '${e.key}' ist eine Zustimmung, die nie verlangt wird \u2014 required: true oder requiredIf setzen, sonst Typ 'boolean' verwenden.`,en:`Field '${e.key}' is a consent nobody is asked to give \u2014 set required: true or requiredIf, or use type 'boolean'.`}})),e.type==="boolean"&&r&&e.defaultValue?.trim()==="false"&&n.push({severity:"warning",path:t,code:"config.boolean-required-default-false",message:{de:`Feld '${e.key}' ist ein Ja/Nein-Pflichtfeld, vorbelegt mit Nein \u2014 es gilt von Anfang an als ausgef\xFCllt. Ist es eine Zustimmung, Typ 'consent' verwenden.`,en:`Field '${e.key}' is a required yes/no preset to No \u2014 it counts as answered from the start. If it is a consent, use type 'consent'.`}}),n}s(SX,"consentConfigIssues");function AX(e,t){let n=e.exclusiveOptions;if(n===void 0)return[];let r=s((a,l)=>[{severity:"error",path:t,code:"config.exclusive-options",message:{de:a,en:l}}],"refuse");if(e.type!=="enum"||e.multiple!==!0)return r(`Feld '${e.key}' setzt exclusiveOptions ohne Mehrfachauswahl \u2014 exklusive Optionen gibt es nur bei type: 'enum' mit multiple: true.`,`Field '${e.key}' sets exclusiveOptions without a multi-select \u2014 exclusive options exist only on type: 'enum' with multiple: true.`);if(e.enumListKey!==void 0)return r(`Feld '${e.key}' setzt exclusiveOptions auf einer Liste des Mandanten (enumListKey) \u2014 exklusive Optionen brauchen eigene enumOptions.`,`Field '${e.key}' sets exclusiveOptions on a tenant list (enumListKey) \u2014 exclusive options need inline enumOptions.`);if(!Array.isArray(n)||n.length===0||n.some(a=>typeof a!="string"))return r(`Feld '${e.key}' setzt exclusiveOptions auf ${JSON.stringify(n)} \u2014 erwartet ist eine nicht leere Liste von Optionsschl\xFCsseln.`,`Field '${e.key}' sets exclusiveOptions to ${JSON.stringify(n)} \u2014 it must be a non-empty list of option keys.`);let i=e.enumOptions??[],o=n.filter(a=>!i.includes(a));return o.length>0?r(`Feld '${e.key}' nennt in exclusiveOptions ${o.map(a=>`'${a}'`).join(", ")} \u2014 keine Option des Feldes.`,`Field '${e.key}' names ${o.map(a=>`'${a}'`).join(", ")} in exclusiveOptions \u2014 not an option of the field.`):new Set(n).size!==n.length?r(`Feld '${e.key}' nennt eine Option in exclusiveOptions doppelt.`,`Field '${e.key}' names an option twice in exclusiveOptions.`):[]}s(AX,"exclusiveOptionIssues");function Ps(e,t,n){try{return nn(e,t)}catch(r){F(`${n} does not evaluate: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}s(Ps,"evalOrBug");var TX="blocked";function PV(e,t){let n={values:t};for(let r of e.outcomes){let i=Ps(r.when,n,`outcome "${r.id}" when-expression`);if(RX(i))return r.id===TX?null:r.id}return null}s(PV,"resolveActiveOutcome");function RX(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(RX,"truthy");function CV(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(CV,"isScalar");function $X(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(CV(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))CV(a)&&(t[`${r}.${o}`]=a)}EX(e,t,n)}s($X,"mergeRecord");function EX(e,t,n){let r=new Set(n);for(let i of Object.keys(e)){let o=i.indexOf("[");if(o<=0)continue;let a=i.slice(0,o);_o(a).test(i)&&r.add(a)}for(let i of r){let o=hA(e,i),a=0;for(let l=0;l<o;l++)uV(e,i,l)&&a++;t[`${i}.count`]=a}}s(EX,"mergeRepeatedCounts");function DV(e,t,n){let r={...n};return $X(e,r,t),r}s(DV,"flattenValues");function bA(e,t,n){return{code:e,fieldKey:t,text:n}}s(bA,"submitIssue");function FV(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(FV,"truthyEval");function LV(e){if(e==null)return!0;if(typeof e=="string")return e.trim()==="";if(Array.isArray(e))return e.length===0;if(typeof e=="object"){let t=e;if("storageId"in t)return!(typeof t.storageId=="string"&&t.storageId.trim()!=="");let n=t;return!n.street?.trim()||!n.hausnr?.trim()||!n.plz?.trim()||!n.ort?.trim()||!n.land?.trim()}return!1}s(LV,"isEmptyValue");function IX(e,t,n){let r=!!e.required;return!r&&e.requiredIf&&(r=FV(Ps(e.requiredIf,{values:t},`requiredIf of '${e.key}'`))),r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(IX,"fieldIsLiveRequired");function OX(e,t,n){return MV(e,t,n).evalCtx}s(OX,"buildSubmitEvalContext");function MV(e,t,n){let r=_X(e),i=Object.keys(t).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[y,b]of Object.entries(t))(r(y)===null||o.has(y))&&(l[y]=b);let d=qV(e,l,n),c=new Set,u=new Set;jV(e,d,y=>c.add(y.key),y=>u.add(y.key));let p=new Set(i.filter(y=>{let b=r(y);return b.kind==="field"?c.has(y):u.has(b.repeatedKey)}));if(p.size===o.size&&[...p].every(y=>o.has(y))){let y={};for(let b of i)o.has(b)||(y[b]=t[b]);return{visible:l,hidden:y,evalCtx:d}}let h=[...p].sort().join("\0");if(a.has(h)){let y=i.filter(b=>p.has(b)!==o.has(b));F(`[smartForm] visibility of ${y.join(", ")} does not settle \u2014 each depends on whether the other's value counts. The form's visibleIf conditions are contradictory.`)}a.add(h),o=p}}s(MV,"splitWithContext");function _X(e){let t=new Map,n=[];for(let r of lg(e.sections)){for(let i of r.fields)t.set(i.key,i);for(let i of r.groups??[])for(let o of i.fields)t.set(o.key,o);for(let i of r.repeated??[])n.push({key:i.key,pattern:_o(i.key),items:new Map(i.itemTemplate.map(o=>[o.key,o]))})}return r=>{let i=t.get(r);if(i!==void 0)return{kind:"field",field:i};for(let o of n){let a=o.pattern.exec(r);if(a!==null)return{kind:"row",repeatedKey:o.key,field:o.items.get(a[2])}}return null}}s(_X,"fieldOwnership");function qV(e,t,n){let r=[];for(let o of lg(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=DV(t,r,n);for(let o of lg(e.sections))for(let a of o.computed??[])i[a.key]=Ps(a.expression,{values:i},`computed '${a.key}'`);return i}s(qV,"rawEvalContext");function KV(e,t,n){let{values:r,defaulted:i}=NX(e,t,n),o=MV(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(KV,"splitDraftValues");function NX(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of lg(e.sections))for(let d of[...l.fields,...(l.groups??[]).flatMap(c=>c.fields)]){if(!d.defaultValue||t[d.key]!=null||r?.(d.key))continue;a??=qV(e,t,n);let c=Ps(d.defaultValue,{values:a},`defaultValue of '${d.key}'`);c!=null&&(i[d.key]=c,o.add(d.key))}return{values:i,defaulted:o}}s(NX,"applyFieldDefaults");function lg(e){let t=[],n=s(r=>{t.push(r);for(let i of r.subsections??[])n(i)},"walk");for(let r of e)n(r);return t}s(lg,"walkSectionsDeep");function PX(e,t,n,r=!1){if(LV(t))return null;let i=n.fields[e.type];i||F(`[fieldFormatIssue] no field provider registered for type "${e.type}" (field "${e.key}"). Register it in the domain form registry.`);let o=i.validate(e,t,{state:{values:{},computed:{}},testMode:r});return o.length>0?o[0].message:null}s(PX,"fieldFormatIssue");function CX(e,t){return LV(t)||e.type==="consent"&&t!==!0}s(CX,"isUnanswered");function ag(e,t){return e?FV(Ps(e,{values:t},"visibleIf")):!0}s(ag,"isVisibleUnder");function jV(e,t,n,r){let i=s(o=>{if(ag(o.visibleIf,t)){for(let a of o.fields)ag(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(ag(a.visibleIf,t))for(let l of a.fields)ag(l.visibleIf,t)&&n(l);if(r!==void 0)for(let a of o.repeated??[])r(a);for(let a of o.subsections??[])i(a)}},"walk");for(let o of e.sections)i(o)}s(jV,"forEachVisibleField");function VV(e,t,n,r={}){let i=OX(e,t,n),o=[],a=PV(e,i);a===null&&r.requireOutcome!==!1&&o.push(bA("no-outcome",null,{de:"Die Angaben ergeben keinen g\xFCltigen Abschluss \u2014 bitte pr\xFCfen Sie das Formular.",en:"The answers do not lead to a valid outcome \u2014 please check the form."}));let l=new Set(r.exemptFromRequired??[]);return jV(e,i,d=>{let c=t[d.key];if(CX(d,c)){!l.has(d.type)&&IX(d,i,a)&&o.push(bA("required",d.key,sd([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=PX(d,c,r.registry,r.testMode===!0);u!==null&&o.push(bA("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(VV,"checkSubmittable");function UV(){return[...Ge,null].flatMap(t=>zw.map(n=>({language:t,channel:n})))}s(UV,"applicantVariants");function GV(e,t){let n=new Map;for(let r of e){let i={};for(let a of t)r[a]===void 0&&F(`[scenario/environment] the host supplied no "${a}"`),i[a]=r[a];let o=JSON.stringify(t.map(a=>i[a]));n.has(o)||n.set(o,i)}return[...n.values()]}s(GV,"projectEnvironments");var BV={"self-service":{de:"online",en:"online"},staff:{de:"durch die Schule",en:"by the school"}};function zV(e){let t=[];for(let n of[e.offer?.title,e.unit?.name,e.stage?.name,e.run?.name])n!==void 0&&t.push({de:n,en:n});if(e.applicant){let{language:n,channel:r}=e.applicant;t.push({de:`${n===null?"ohne Konto":`Konto ${n}`}, ${BV[r].de}`,en:`${n===null?"no account":`account ${n}`}, ${BV[r].en}`})}return{de:t.map(n=>n.de).join(" \xB7 "),en:t.map(n=>n.en).join(" \xB7 ")}}s(zV,"describeEnvironment");var WV=6;function YV(e,t){let n=e.slice(0,WV).map(i=>i[t]).join("; "),r=e.length-WV;return r<=0?n:t==="de"?`${n} und ${r} weitere`:`${n} and ${r} more`}s(YV,"listed");function HV(e,t){let n=e.testScenarios??[];if(n.length===0)return[];let r=_F(e).filter(mo),i=r.length===0?[{}]:t??[];if(r.length>0&&t===void 0)return[{severity:"warning",path:"testScenarios",code:"scenario.unjudged",message:{de:`Die Testszenarien werden hier nicht gepr\xFCft: das Formular liest ${r.join(", ")}, und welche Klassenstufen und Schuljahre das Angebot hat, ist hier nicht bekannt \u2014 die Ver\xF6ffentlichung pr\xFCft sie.`,en:`The test scenarios are not judged here: the form reads ${r.join(", ")}, and which grades and school years the offer has is not known here \u2014 publishing judges them.`}}];if(i.length===0)return[{severity:"warning",path:"testScenarios",code:"scenario.no-environment",message:{de:"Das Angebot hat noch keine Klassenstufe mit Schuljahr \u2014 die Testszenarien sind gegen keine Umgebung gepr\xFCft. Nach dem Anlegen erneut ver\xF6ffentlichen.",en:"The offer has no grade with a school year yet \u2014 the test scenarios are judged against no environment. Publish again once one exists."}}];let{compiled:o}=Ka(e),a=[];for(let l of n){let d=l.prefill??{},c=new Map,u=s((p,h)=>{let y=`${p.path}\0${p.message.de}`,b=c.get(y);b===void 0?c.set(y,{...p,where:[h]}):b.where.some(k=>k.de===h.de)||b.where.push(h)},"add");for(let p of i){let h=OF(p,r),{visible:y}=KV(o,d,h),b=VV(o,y,h,{exemptFromRequired:["docRef"]}),k=zV(p);for(let v of b.issues){if(v.code==="no-outcome"){u({path:`scenario:${l.id}`,code:"scenario.no-outcome",message:{de:`Szenario "${l.label.de}" erreicht kein g\xFCltiges Outcome \u2013 der Testfall ist nicht absendbar.`,en:`Scenario "${l.label.en}" reaches no valid outcome \u2013 the test case cannot be submitted.`}},k);continue}if(v.code==="required"){u({path:`scenario:${l.id}/${v.fieldKey}`,code:"scenario.required-field-unfilled",message:{de:`Szenario "${l.label.de}" l\xE4sst das Pflichtfeld ${v.fieldKey} unbef\xFCllt \u2013 kein g\xFCltiges Outcome.`,en:`Scenario "${l.label.en}" leaves the required field ${v.fieldKey} empty \u2013 no valid outcome.`}},k);continue}u({path:`scenario:${l.id}/${v.fieldKey}`,code:"scenario.invalid-value",message:sd([l.label,v.text],([A,T],I)=>I==="de"?`Szenario "${A}": ${T}`:`Scenario "${A}": ${T}`)},k)}}for(let p of c.values())a.push({severity:"error",path:p.path,code:p.code,message:r.length===0?p.message:{de:`${p.message.de} \u2014 in: ${YV(p.where,"de")}`,en:`${p.message.en} \u2014 in: ${YV(p.where,"en")}`}})}return a}s(HV,"validateScenarios");function dg(e){return e.filter(t=>(t.severity??"error")==="error")}s(dg,"blockingIssues");function cg(e,t={}){return[...OV(e,t),...HV(e,t.scenarioEnvironments)]}s(cg,"runFormValidators");function ug(e){return dg(e)}s(ug,"blockingFormErrors");function JV(e,t,n){return HL(e,t,n)}s(JV,"runWorkflowValidators");function QV(e){return dg(e)}s(QV,"blockingWorkflowErrors");var DX=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"];var ZV={join:{required:[],optional:[]},end:{required:[],optional:[]},eventTrigger:{required:[],optional:[]},form:{required:[],optional:["adoptForm","formExports"]},roleAssign:{required:[],optional:[]},setFlag:{required:[],optional:[]},if:{required:["condition"],optional:[]},countersign:{required:["contract"],optional:["signing","titles"]},engagePush:{required:["form"],optional:["contract","engage","payment"]},decision:{required:[],optional:["commentRequired","decisionAsTask","reads","requiresOneOf","view"]},review:{required:[],optional:["commentRequired","decisionAsTask","form"]},waitlist:{required:[],optional:[]},completenessCheck:{required:["deadline","requires"],optional:[]},collectPayment:{required:[],optional:[]},governedDocument:{required:["approval","production","responseStrategy"],optional:["confirmBeforeIssue","confirmContractTerms","contractTermsQuestionText","form","generatorStamp","reads","responseLabels","templateStamp","titles"]}},Rn={id:m.string(),label:Ui,actionTeams:m.optional(m.any()),artifacts:m.optional(m.any()),assign:m.optional(m.any()),inputs:m.optional(m.any()),library:m.optional(m.any()),next:m.optional(m.any()),notifications:m.optional(m.any()),optionalActions:m.optional(m.any()),outcomes:m.optional(m.any()),outputLabels:m.optional(m.any()),sublabel:m.optional(m.any()),tasks:m.optional(m.any())},FX=m.object({...Rn,type:m.literal("join")}),LX=m.object({...Rn,type:m.literal("end")}),MX=m.object({...Rn,type:m.literal("eventTrigger")}),qX=m.object({...Rn,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),KX=m.object({...Rn,type:m.literal("roleAssign")}),jX=m.object({...Rn,type:m.literal("setFlag")}),VX=m.object({...Rn,type:m.literal("if"),condition:m.optional(m.any())}),BX=m.object({...Rn,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),UX=m.object({...Rn,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),GX=m.object({...Rn,type:m.literal("decision"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),reads:m.optional(m.any()),requiresOneOf:m.optional(m.any()),view:m.optional(m.any()),formView:m.optional(m.any())}),zX=m.object({...Rn,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),WX=m.object({...Rn,type:m.literal("waitlist")}),YX=m.object({...Rn,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),HX=m.object({...Rn,type:m.literal("collectPayment")}),JX=m.object({...Rn,type:m.literal("governedDocument"),approval:m.optional(m.any()),confirmBeforeIssue:m.optional(m.any()),confirmContractTerms:m.optional(m.any()),contractTermsQuestionText:m.optional(m.any()),form:m.optional(m.any()),generatorStamp:m.optional(m.any()),production:m.optional(m.any()),reads:m.optional(m.any()),responseLabels:m.optional(m.any()),responseStrategy:m.optional(m.any()),templateStamp:m.optional(m.any()),titles:m.optional(m.any())}),IGe=m.union(FX,LX,MX,qX,KX,jX,VX,BX,UX,GX,zX,WX,YX,HX,JX);function XV(e){let t=[];return e.forEach((n,r)=>{if(n===null||typeof n!="object"||Array.isArray(n)){t.push(`graph.nodes[${r}]: a node must be an object`);return}let i=n,o=`graph.nodes[${r}]${typeof i.id=="string"?` (${i.id})`:""}`;(typeof i.id!="string"||i.id==="")&&t.push(`${o}: \`id\` must be a non-empty string`);let a=i.type;if(typeof a!="string"||!(a in ZV)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=ZV[a],d=new Set(["id","type","label",...DX,...l.required,...l.optional]);for(let c of Object.keys(i))d.has(c)||t.push(`${o}: \`${c}\` is not a field of a ${a} node. Delete the line.`)}),t}s(XV,"workflowNodeEnvelopeIssues");var eB=s(e=>e,"asEffectId"),No=s(e=>e,"asOutcomeId"),fl=s(e=>e,"asSectionId"),yn=s(e=>e,"asFieldKey");var jr=["string","boolean","consent","date","enum","email","tel","address","docRef"],Cc=["person","organization","relationship","fieldMap"],Po=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],pl=["fresh","keyed","manual"];function Cs(e,t,n,r){if(e===void 0||e===""){if(t!==void 0&&t!=="")throw new g(`${n}: ${r}-en needs ${r} too`);return}return pt(e,t,n,r)}s(Cs,"optionalLocalizedText");function ln(e,t){if(!(e===void 0||e===""))try{Mt(e)}catch(n){throw new g(`offer form: ${t} is not a valid expression: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}s(ln,"assertExpression");function Dc(e){return Object.keys(e.smartforms??{})}s(Dc,"carriedFormSlugs");function vA(e){let n=e.workflow?.graph?.nodes??[],r=[];for(let i of n){if(i.type!=="form")continue;let o=i.inputs?.smartForm;o?.kind==="literal"&&typeof o.value=="string"&&o.value&&r.push(o.value)}return r}s(vA,"boundFormSlugs");function fg(e,t){let n=Dc(e);if(t){if(!n.includes(t))throw new g(`offer form: no smartform "${t}" in this bundle (have: ${n.join(", ")||"none"})`);return t}if(n.length===0)throw new g("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(n.length>1)throw new g(`offer form: bundle carries ${n.length} smartforms \u2014 pass --form <key> (one of: ${n.join(", ")})`);return n[0]}s(fg,"resolveFormSlug");function pg(e,t){let n=e.smartforms?.[t];if(!n)throw new g(`offer form: smartform "${t}" not found in bundle`);return n}s(pg,"getForm");function nr(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(nr,"walkSections");function vr(e,t){return nr(e).find(n=>n.id===t)}s(vr,"findSection");function Ds(e,t){for(let n of nr(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Ds,"findField");function Fs(e){let t=new Set;for(let n of nr(e))n.fields.forEach(r=>t.add(r.key)),n.groups?.forEach(r=>r.fields.forEach(i=>t.add(i.key))),n.repeated?.forEach(r=>r.itemTemplate.forEach(i=>t.add(i.key))),n.computed?.forEach(r=>t.add(r.key));return t}s(Fs,"allFieldKeys");function QX(e){let t=pt(e.label,e.labelEn,"offer form add"),n={id:fl("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:No("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(QX,"buildSkeletonSmartForm");function mg(e,t){let{key:n,label:r}=t;if(Dc(e).includes(n))throw new g(`offer form add: smartform "${n}" already exists in this bundle`);let i=QX({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(mg,"addForm");function tB(e,t){if(!Dc(e).includes(t))throw new g(`offer form rm: smartform "${t}" not found in bundle`);if(vA(e).includes(t))throw new g(`offer form rm: smartform "${t}" is still bound by a form node \u2014 remove the form node first (offer workflow node rm), then the form`);return delete e.smartforms[t],e.index.smartforms&&delete e.index.smartforms[t],t}s(tB,"removeForm");function nB(e,t){let n=pg(e,t.slug);if(t.label===void 0&&t.labelEn===void 0)throw new g("offer form set: nothing to change \u2014 pass --label/--label-en");if(t.label==="")throw new g("offer form set: --label cannot be empty");St(n,"label",{de:t.label,en:t.labelEn},"offer form set")}s(nB,"setForm");function rB(e,t){let n=e.workflow?.graph?.nodes;if(!Array.isArray(n))throw new g(`${t}: the bundle carries no workflow graph (workflow.json)`);return n}s(rB,"nodesOf");function iB(e,t,n){let r=rB(e,n),i=r.find(o=>o.id===t);if(i===void 0)throw new g(`${n}: no node "${t}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(iB,"nodeOf");function oB(e){return e.flatMap(t=>{if(t.type!=="form"||Pn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(oB,"creatingFormNodes");function sB(e){return ug(cg(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(sB,"formErrors");function hg(e){let t="offer workflow restamp-exports",n=rB(e,t),r=[];for(let{node:i,slug:o}of oB(n)){let a=e.smartforms?.[o];if(a===void 0)throw new g(`${t}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=sB(l);if(d.length>0)throw new g(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
11850
+ `),this.print(t,o=>o.slots.map(a=>{let l=o.override?.[a.key];return{block:a.key,label:a.label,deviates:l===void 0?"":"yes",text:(l??a.default).replace(/\s+/g," ").slice(0,80)}}),["block","label","deviates","text"])}},bS=class extends P{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=E.Usage({category:"Notifications",description:"Reword one or more blocks of a letter for this school (merge \u2014 untouched blocks stay as they are).",details:"A block whose text EQUALS the platform default is dropped rather than stored: what is kept is the deviation, never a copy, so a later improvement to an untouched block still reaches this school. An unknown block or an undeclared {{placeholder}} is refused by the backend with every finding named \u2014 nothing is written.",examples:[["One paragraph",'$0 --tenant test notifications letters set applicant.welcome --locale de --slot intro="Sch\xF6n, dass Sie da sind."'],["The English letter",'$0 --tenant test notifications letters set applicant.welcome --locale en --slot intro="Lovely to have you."'],["From a file","$0 --tenant test notifications letters set applicant.tasksOpen --locale de --slot-file intro=./intro.txt"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${Ge.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=f.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let t=gZ(this.slot,this.slotFile);if(Object.keys(t).length===0)throw new g("notifications letters set: nothing to write \u2014 pass --slot <blockKey>=<text> or --slot-file <blockKey>=<path>");let n=await this.caller(),r=await n.mutation(S.notifications.saveLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:cK(this.locale,"letters set"),slots:t});return this.print({templateId:this.templateId,submitted:Object.keys(t),...r},i=>[{key:"letter",value:i.templateId},{key:"submitted",value:i.submitted.join(", ")},{key:"deviating blocks",value:i.overriddenSlotKeys.join(", ")||"\u2014 (back to the platform text)"}]),0}},vS=class extends P{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=E.Usage({category:"Notifications",description:"Drop this school's deviations \u2014 named blocks, or the whole letter with --all.",details:"--all is required to drop a whole letter: dropping everything must be typed, never be what happens when a --slot is forgotten.",examples:[["One block back to the platform text","$0 --tenant test notifications letters reset applicant.welcome --locale de --slot intro"],["The whole letter","$0 --tenant test notifications letters reset applicant.welcome --locale en --all"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${Ge.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"Block key to reset (repeatable)"});all=f.Boolean("--all",!1,{description:"Reset every block of this letter"});async execute(){let t=(this.slot??[]).map(i=>i.trim()).filter(Boolean);if(this.all&&t.length>0)throw new g("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&t.length===0)throw new g("notifications letters reset: name the blocks with --slot <blockKey>, or pass --all to reset the whole letter.");let n=await this.caller(),r=await n.mutation(S.notifications.resetLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:cK(this.locale,"letters reset"),...this.all?{}:{slotKeys:t}});return this.print({templateId:this.templateId,reset:this.all?"all":t.join(", "),...r},i=>[{key:"letter",value:i.templateId},{key:"reset",value:i.reset},{key:"still deviating",value:i.overriddenSlotKeys.join(", ")||"\u2014 (nothing)"}]),0}},Ic=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function Lh(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":Ic(t[r],""),...n===null?{}:{platform:Ic(n[r],"")}}))}s(Lh,"chromeTextRows");var xS=class extends P{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=E.Usage({category:"Notifications",description:"The school's letter frame (greeting and sign-off per language, sender name) and the platform wording each falls back to."});async execute(){let t=await this.caller(),n=await t.query(S.notifications.getTenantChrome,{tenantSlug:this.requireTenant(t)});return this.print(n,r=>[...Lh("greeting",r.greeting,r.defaults.greeting),...Lh("closing",r.closing,r.defaults.closing),{field:"senderName",school:Ic(r.senderName,"\u2014 (platform)"),platform:Ic(r.defaults.senderName,"")}],["field","school","platform"]),0}},SS=class extends P{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=E.Usage({category:"Notifications",description:"Set the school's letter frame. Greeting and sign-off are set in BOTH languages at once; both EMPTY clears that field back to the platform wording.",examples:[["Own sign-off",'$0 --tenant test notifications chrome set --closing-de="Herzliche Gr\xFC\xDFe, Ihr Grundschul-Team" --closing-en="Warm regards, your primary school team"'],["Back to the platform sign-off",'$0 --tenant test notifications chrome set --closing-de="" --closing-en=""']]});greetingDe=f.String("--greeting-de",{description:"Opening line, German"});greetingEn=f.String("--greeting-en",{description:"Opening line, English"});closingDe=f.String("--closing-de",{description:"Sign-off, German"});closingEn=f.String("--closing-en",{description:"Sign-off, English"});senderName=f.String("--sender-name",{description:"Name the school signs with (empty string clears it)"});async execute(){let t=s((l,d,c)=>{if(!(d===void 0&&c===void 0)){if(d===void 0||c===void 0)throw new g(`notifications chrome set: --${l}-de and --${l}-en go together \u2014 the frame is worded in every language`);return{de:d,en:c}}},"pair"),n=t("greeting",this.greetingDe,this.greetingEn),r=t("closing",this.closingDe,this.closingEn);if(n===void 0&&r===void 0&&this.senderName===void 0)throw new g("notifications chrome set: nothing to change \u2014 pass --greeting-de/--greeting-en, --closing-de/--closing-en or --sender-name");let i=await this.caller(),o=this.requireTenant(i);await i.mutation(S.notifications.saveTenantChrome,{tenantSlug:o,...n!==void 0?{greeting:n}:{},...r!==void 0?{closing:r}:{},...this.senderName!==void 0?{senderName:this.senderName}:{}});let a=await i.query(S.notifications.getTenantChrome,{tenantSlug:o});return this.print(a,l=>[...Lh("greeting",l.greeting,null),...Lh("closing",l.closing,null),{field:"senderName",school:Ic(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},fK=[pS,mS,hS,gS,yS,wS,kS,bS,vS,xS,SS];var kZ={capacity:null,isOpen:!1},bZ={capacity:null,isOpen:!0};function vZ(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(vZ,"isCapacity");function Mh(e,t){let n=[],r=t===void 0?void 0:new Set(t);return e.forEach((i,o)=>{if(i.capacities===void 0)return;let a=`program.runs[${o}] ("${i.key}")`;if(i.isOpen!==void 0&&n.push(`[capacity/runIsOpenWithCells] ${a}: \`isOpen\` on the run AND \`capacities\` \u2014 the open state lives on each cell; drop the run-level \`isOpen\``),i.capacities===null||typeof i.capacities!="object"||Array.isArray(i.capacities)){n.push(`[capacity/shape] ${a}: \`capacities\` must map stage keys to { isOpen, capacity }`);return}for(let[l,d]of Object.entries(i.capacities)){let c=`${a}.capacities.${l}`;r!==void 0&&!r.has(l)&&n.push(`[capacity/unknownStage] ${c}: no stage with key "${l}" in program.stages (have: ${[...r].join(", ")||"none"})`);let u=d;if(u===null||typeof u!="object"){n.push(`[capacity/shape] ${c}: expected { isOpen, capacity }`);continue}typeof u.isOpen!="boolean"&&n.push(`[capacity/isOpen] ${c}: \`isOpen\` must be true or false`),(!("capacity"in u)||!vZ(u.capacity))&&n.push(`[capacity/value] ${c}: \`capacity\` must be a whole number \u2265 0, "unlimited", or null (unconfigured) \u2014 got ${JSON.stringify(u.capacity)}`)}}),n}s(Mh,"capacitySpecIssues");function mK(e,t,n={stageKeys:[],runKeys:[]}){let r=e.programKey,i=new Map;if(r!==null)for(let c of e.stages)c.archived||i.set(ri(r,c.key),c.stageId);let o=new Set(n.stageKeys),a=new Set(n.runKeys),l=new Map(e.runStages.map(c=>[`${c.runId}|${c.stageId}`,c])),d=[];for(let c of t){if(c.capacities===void 0)continue;let u=r===null?void 0:e.runs.find(p=>p.key===lr(r,c.key));if(u===void 0&&!a.has(c.key))throw new g(`offer[admission]: run "${c.key}" does not exist and is not created by this apply`);for(let[p,h]of Object.entries(c.capacities)){let y=i.get(p);if(y===void 0&&!o.has(p))throw new g(`offer[admission]: capacities of run "${c.key}" name stage "${p}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let b={capacity:h.capacity,isOpen:h.isOpen},k=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,v=k!==void 0?{capacity:k.capacity,isOpen:k.isOpen}:u===void 0?kZ:bZ;v.capacity===b.capacity&&v.isOpen===b.isOpen||d.push({run:c.key,stageKey:p,from:v,to:b})}}return d}s(mK,"planRunCapacities");function pK(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(pK,"describeCell");function qh(e){return`~cap ${e.run}\xD7${e.stageKey} ${pK(e.from)} \u2192 ${pK(e.to)}`}s(qh,"describeCapacityStep");function hK(e){if(e.programKey===void 0)throw new Error("offer[admission]: the target backend predates stage keys \u2014 deploy it before running offer plan / apply / export with this CLI")}s(hK,"assertBackendHasStageKeys");async function AS(e,t,n,r){let i=await e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),o=i.stages.map(u=>({stageId:u.stageId,key:u.key,name:u.name,...u.gradeLevel!==void 0?{gradeLevel:u.gradeLevel}:{},sequence:u.sequence,archived:u.archived}));hK(i);let a=Sp(i.programKey,o,r),l=a.flatMap(u=>u.op==="archive"?[u.stageId]:[]);if(l.length===0)return a;let d=await e.query(S.programAdmin.getStageOccupancy,{client:t,offerKey:n,stageIds:l}),c=new Map(d.map(u=>[u.stageId,u]));return a.map(u=>{if(u.op!=="archive")return u;let p=c.get(u.stageId);if(p===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:p.activeApplications,openLeads:p.openLeads}}})}s(AS,"planStages");async function Kh(e,t,n,r){let i=r.program?.runs??[];if(!i.some(c=>c.capacities!==void 0))return[];let o=n===null?{programKey:null,stages:[],runs:[],runStages:[]}:await e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n});hK(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>ri(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return mK(o,i,{stageKeys:l.filter(c=>!a.has(c)),runKeys:i.map(c=>c.key).filter(c=>d===null||!o.runs.some(u=>u.key===lr(d,c)))})}s(Kh,"planCapacities");async function xZ(e,t,n,r){let i=(r.program?.runs??[]).map(d=>d.key);if(i.length===0)return;let o=await e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),a=o.programKey;if(a===null)return;let l=i.filter(d=>o.runs.some(c=>c.key===lr(a,d)&&c.status==="archived"));if(l.length>0)throw new g(`offer[admission]: run(s) ${l.map(d=>`"${d}"`).join(", ")} exist only ARCHIVED \u2014 restore with \`offer run restore --run <key>\` or drop the bundle entry`)}s(xZ,"assertNoArchivedRunKey");var TS={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...xp(o??[]),...vp(n.program?.runs??[])];if(a.length>0)throw new g(`offer[admission]: ${a.map(k=>k.message.de).join("; ")}`);let l=Mh(n.program?.runs??[],o?.map(k=>k.key));if(l.length>0)throw new g(`offer[admission]: ${l.join("; ")}`);await xZ(e,i,t,n);let d=await Kh(e,i,t,n),c=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=SZ(n);if(!u)throw new g("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let p=c.units.find(k=>k.key===u);if(!p)throw new g(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(k=>k.key===null?[]:[k.key]).join(", ")||"(none)"}`);let h=[];if(r.dryRun||(await e.mutation(S.programAdmin.ensurePedagogyUnit,{client:i,unitId:p.unitId}),await e.mutation(S.programAdmin.createProgramForAngebot,{client:i,offerKey:t,unitId:p.unitId,...n.program?.key!==void 0?{programKey:n.program.key}:{}})),h.push(`unit=${u}`),o!==void 0)if(r.dryRun){let k=await AS(e,i,t,o);h.push(...k.map(Ap))}else{let k=await e.mutation(S.programAdmin.reconcileProgramStages,{client:i,offerKey:t,stages:o.map(v=>({key:v.key,name:v.name,...v.gradeLevel!==void 0?{gradeLevel:v.gradeLevel}:{}}))});h.push(...k.steps,...k.warnings.map(v=>`warning ${v}`))}let y=r.dryRun?c:await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t});for(let k of n.program?.runs??[]){let v=y.programKey===null?void 0:y.runs.find(A=>A.key===lr(y.programKey,k.key));if(v!==void 0){sa(v.name,k.name)||(r.dryRun||await e.mutation(S.programAdmin.updateProgramRun,{client:i,offerKey:t,runId:v.runId,name:k.name}),h.push(`~run ${k.key} ("${Fe(v.name)}" \u2192 "${Fe(k.name)}")`));continue}r.dryRun||await e.mutation(S.programAdmin.addProgramRun,{client:i,offerKey:t,key:k.key,name:k.name,isOpen:k.capacities!==void 0?!1:k.isOpen??!0,...k.startDate?{startDate:k.startDate}:{},...k.endDate?{endDate:k.endDate}:{}}),h.push(`+run ${k.key} (${Fe(k.name)})`)}let b=r.dryRun?d:await Kh(e,i,t,n);if(!r.dryRun&&b.length>0){let k=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),v=k.programKey;if(v===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let A of b){let T=k.runs.find(C=>C.key===lr(v,A.run))?.runId,I=k.stages.find(C=>ri(v,C.key)===A.stageKey)?.stageId;if(T===void 0||I===void 0)throw new Error(`offer[admission]: cell ${A.run}\xD7${A.stageKey} vanished between plan and write`);await e.mutation(S.programAdmin.setRunStageCapacity,{client:i,offerKey:t,runId:T,stageId:I,capacity:A.to.capacity,isOpen:A.to.isOpen})}}return h.push(...b.map(qh)),h.join(", ")}};function SZ(e){let t=e.program?.unitKey,n=e.links?.unitKey;if(t!==void 0&&n!==void 0&&t!==n)throw new g(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${t}" and links.unitKey "${n}"; keep one`);return t??n}s(SZ,"bundleUnitKey");var gK={role:"control",effect:"pure",cardinality:"N-to-1"};var jh=["add","remove","replace"];function yK(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(yK,"roleAssignLiteral");var wK={role:"method",effect:"context-mutation",inputs:s(()=>[{id:"person",label:{de:"Person",en:"Person"},type:"personRef",required:!0},{id:"roleKey",label:{de:"Rolle",en:"Role"},type:"roleKey",required:!0,optionSource:"tenantRoles"},{id:"mode",label:{de:"Modus",en:"Mode"},type:"enum",defaultValue:"add",optionSource:"declared",enumOptions:[{value:"add",label:{de:"Rolle hinzuf\xFCgen",en:"Add role"}},{value:"remove",label:{de:"Rolle entziehen",en:"Remove role"}},{value:"replace",label:{de:"Alle Rollen ersetzen",en:"Replace all roles"}}]}],"inputs"),validate:s((e,t,n)=>{let r=[],i=yK(e,"roleKey")?.trim()??"",o=yK(e,"mode")??"add";return i===""?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/missingRoleKey] roleAssign-Knoten "${e.id}" nennt keine Rolle \u2014 welche Rolle vergeben wird, muss der Autor aus dem Rollenkatalog des Mandanten w\xE4hlen.`,en:`[roleAssign/missingRoleKey] roleAssign node "${e.id}" names no role \u2014 the author must choose which role is assigned from the school's role catalog.`},severity:"error"}):n?.roleKeys!==void 0&&!n.roleKeys.has(i)?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/unknownRoleKey] Rolle "${i}" existiert nicht im Rollenkatalog des Mandanten \u2014 der Knoten w\xFCrde bei jeder Ausf\xFChrung abbrechen. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[roleAssign/unknownRoleKey] Role "${i}" does not exist in the school's role catalog \u2014 the node would abort on every run. Known roles: ${[...n.roleKeys].sort().join(", ")}.`},severity:"error"}):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(i)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/nonLeafRoleKey] Rolle "${i}" hat untergeordnete Rollen und ist deshalb nicht vergebbar \u2014 eine Partei bekommt ein Blatt, keine Oberkategorie. Vergebbare Rollen: ${[...n.assignableRoleKeys].sort().join(", ")}.`,en:`[roleAssign/nonLeafRoleKey] Role "${i}" has sub-roles and therefore cannot be assigned \u2014 a party gets a leaf role, not a parent category. Assignable roles: ${[...n.assignableRoleKeys].sort().join(", ")}.`},severity:"error"}),jh.includes(o)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.mode`,reason:{de:`[roleAssign/unknownMode] roleAssign-Knoten "${e.id}" deklariert Modus "${o}" \u2014 erlaubt sind ${jh.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${jh.join(" | ")}.`},severity:"error"}),r},"validate")};var AZ=["event","effect","outcomes"],RS=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),kK={outcomes:[{id:zn,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of AZ)i in r&&n.push(RS(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${zn}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${zn}" itself.`));return Cn(t.nodes).some(i=>i.target===e.id)&&n.push(RS(`nodes.${e.id}`,`[eventTrigger/notStart] Knoten "${e.id}" ist ein Start-Knoten, hat aber eine eingehende Kante \u2014 nur der Start l\xF6st ihn aus, jeder Vorgang bliebe hier stehen.`,`[eventTrigger/notStart] Node "${e.id}" is a start node but has an incoming edge \u2014 only the start triggers it, every process would stop here.`)),e.next?.[zn]===void 0&&n.push(RS(`nodes.${e.id}.next.${zn}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${zn}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${zn}" nowhere.`)),n},"validate")};var TZ="submit",bK=[{id:TZ,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function vK(e){return e==="draft"}s(vK,"isWritableSmartFormState");var $S=["draft","committed"],SLe=$S.filter(e=>vK(e));async function xK(e,t,n){let r=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",i=>i.eq("applicationId",t).eq("formNodeId",n)).take(2);return r.length>1&&F(`application ${t}: two form instances for node "${n}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(xK,"getSmartFormInstance");var SK="form:fill",ES="request:collectPayment",IS="request:collectPaymentSeparate",Lr="confirmPayment";var RZ={key:SK,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},AK={key:"bearbeitung",label:ie("In Bearbeitung","In progress"),scope:"node"},TK={[Vw]:{label:ie("In Bearbeitung","In progress"),tone:"neutral",phase:AK,external:at(ie("Entwurf","Draft"),"neutral",ie("Bewerbung fortsetzen","Continue application"),ie("Sie haben die Bewerbung bereits begonnen. Schlie\xDFen Sie sie ab, um sie einzureichen.","You have already started the application. Complete it to submit it."),ie("Bewerbung fortsetzen","Continue application"),"continue-form")},[$p]:{label:ie("Eingereicht","Submitted"),tone:"blue",phase:AK,external:at(ie("Eingereicht","Submitted"),"blue",ie("Ihre Bewerbung ist eingereicht","Your application has been submitted"),ie("Ihre Bewerbung ist bei uns eingegangen. Wir melden uns mit den n\xE4chsten Schritten.","We have received your application. We will be in touch with the next steps."))}},RK={role:"user-action",effect:"side-effect",progressDefaults:TK,progressEvents:Yt(TK),entryProgressEvent:s(()=>Vw,"entryProgressEvent"),actions:s(()=>bK,"actions"),workItemTemplates:s(()=>[RZ],"workItemTemplates"),states:$S,currentState:s(async(e,t)=>{let n=await xK(e,t.applicationId,t.node.id);return n===null?"draft":n.state},"currentState"),inputs:s(e=>[{id:"smartForm",label:{de:"Formular",en:"Form"},type:"smartForm",optionSource:"offerSmartForms",required:e.adoptForm===void 0,inspector:"literal-only"}],"inputs"),outputs:s(e=>[{name:"admission",type:"admission",label:{de:"Anmeldung",en:"Application"},schema:[{key:"beneficiary",type:"personRef",label:{de:"Beschulte Person",en:"Student"}},{key:"signers",type:"personList",label:{de:"Unterzeichner",en:"Signers"}},...e.formExports??[]]}],"outputs"),notificationEvents:s(e=>Pn(e)?[]:[{id:Ep,label:{de:"Formular abgesendet",en:"Form submitted"},audience:"external",args:[{key:"applicationId",type:"string",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[],n=e.inputs?.smartForm,r=n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0,i=e.adoptForm!==void 0;return r&&i?t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.adoptForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" hat sowohl ein smartForm als auch adoptForm \u2014 genau eines ist erlaubt.`,en:`[form.adopt-xor-create] Form node "${e.id}" has both a smartForm and adoptForm \u2014 exactly one is allowed.`},severity:"error"}):!r&&!i&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.smartForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" braucht entweder ein smartForm (neu erzeugen) oder adoptForm (bestehende Instanz \xFCbernehmen).`,en:`[form.adopt-xor-create] Form node "${e.id}" needs either a smartForm (create new) or adoptForm (adopt an existing instance).`},severity:"error"}),t},"validate")};var $K={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Kt.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Kt.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Kt.value,label:{de:"Setzen oder zur\xFCcknehmen",en:"Raise or lower"},type:"boolean",defaultValue:!0,inspector:"literal-only",enumOptions:[{value:"true",label:{de:"Setzen",en:"Raise"}},{value:"false",label:{de:"Zur\xFCcknehmen",en:"Lower"}}]}],"inputs"),notificationEvents:s(e=>[{id:"unlocked",label:{de:"Abschnitt freigeschaltet",en:"Section unlocked"},audience:"external",required:uP(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[];e.inputs?.[Kt.flagKey]?.kind==="literal"&&Hp(e)===null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Kt.flagKey}`,reason:{de:`[setFlag/missingFlagKey] setFlag-Knoten "${e.id}" nennt kein Merkmal (Parameter \u201EMerkmal im Formular\u201C).`,en:`[setFlag/missingFlagKey] setFlag node "${e.id}" names no flag (parameter "Flag in the form").`},severity:"error"});let r=e.inputs?.[Kt.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Kt.value}`,reason:{de:`[setFlag/valueType] setFlag-Knoten "${e.id}": \u201ESetzen oder zur\xFCcknehmen\u201C ist ein Ja/Nein-Wert (true/false), kein Text.`,en:`[setFlag/valueType] setFlag node "${e.id}": "Raise or lower" is a yes/no value (true/false), not text.`},severity:"error"}),t},"validate")};var $Z="true",EZ="false",OS=[{id:$Z,label:{de:"Ja",en:"Yes"}},{id:EZ,label:{de:"Nein",en:"No"}}];var EK={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:OS,validate:s((e,t,n)=>IZ(e,t,n),"validate")};function IZ(e,t,n){let r=s(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${o.de}`,en:`[if/condition] Node "${e.id}": ${o.en}`},severity:"error"}),"issue"),i=OS.filter(o=>e.next?.[o.id]===void 0).map(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${o.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${o.label.de}\u201C (${o.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${o.label.en}" (${o.id}) leads nowhere.`},severity:"error"}));return typeof e.condition!="string"||e.condition.trim()===""?[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})]:[...i,...Im(e.condition,aN(t),n).map(r)]}s(IZ,"ifNodeIssues");var Gi="decision",OZ=new Set(["decision","review"]),WLe=new Set([...OZ,"governedDocument"]);var OK=[{id:"approved",label:{de:"Freigeben",en:"Approve"},semantic:"granted"},{id:"rejected",label:{de:"Ablehnen",en:"Reject"},semantic:"rejected"},{id:"waitlisted",label:{de:"Auf Warteliste",en:"Waitlist"},semantic:"waitlisted"}],IK={released:{label:ie("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:ie("Freigabe","Release"),scope:"node"},external:at(ie("Freigegeben","Released"),"green",ie("Ihre Bewerbung wurde freigegeben","Your application has been released"),ie("Wir haben Ihre Bewerbung freigegeben und melden uns mit den n\xE4chsten Schritten.","We have released your application and will be in touch with the next steps."))}},Ns={role:"user-action",effect:"side-effect",outcomes:OK,progressDefaults:IK,progressEvents:Yt(IK),entryProgressEvent:s(()=>"released","entryProgressEvent"),notificationEvents:s(e=>(e.outcomes??[]).map(t=>({id:t.id,label:t.label,audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"comment",type:"string"}]})),"notificationEvents"),actions:s(e=>[...(e.outcomes??[]).map(t=>({id:t.id,kind:"advance",outcome:t.id,label:t.label,...ho(t.semantic)?{semantic:t.semantic}:{}})),...YF(e)],"actions"),optionalActionKinds:["spawnTasks","skipRule"],workItemTemplates:s(e=>[{key:Gi,recipient:"internal",title:e.decisionAsTask?.title??{de:"Entscheidung",en:"Decision"},unlocks:(e.outcomes??[]).map(t=>t.id).filter(t=>typeof t=="string"&&t.length>0),gatesNode:!1,advancesNode:!0,dueInDays:e.decisionAsTask?.dueInDays}],"workItemTemplates"),taskDocuments:s((e,t)=>t===Gi&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),taskView:s((e,t)=>t===Gi?e.view:void 0,"taskView"),placelessTasks:{[Gi]:"Placed only by the node's authored `view`; a decision that names none is worked in its step wherever the decider opens it."},validate:_S};function _S(e,t,n){let r=[],i=e.outcomes??[];i.length===0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[decision/missingOutcomes] Entscheidungs-Knoten "${e.id}" hat keine Outcomes \u2014 die Entscheidung w\xE4re niemals aufl\xF6sbar.`,en:`[decision/missingOutcomes] Decision node "${e.id}" has no outcomes \u2014 the decision could never be resolved.`},severity:"error"});let o=new Set(i.map(l=>l.id));for(let l of i){let d=l.label;(typeof d=="string"?d.trim().length>0:d!=null&&typeof d=="object"&&Object.values(d).some(p=>typeof p=="string"&&p.trim().length>0))||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}`,reason:{de:`[decision/outcomeMissingLabel] Outcome "${l.id}" von "${e.id}" hat keine Beschriftung \u2014 sie ist der Text des Knopfs im Cockpit.`,en:`[decision/outcomeMissingLabel] Outcome "${l.id}" of "${e.id}" has no label \u2014 it is the text of the button in the cockpit.`},severity:"error"});let u=l.semantic;u===void 0?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticMissing] Outcome "${l.id}" von "${e.id}" sagt nicht, was es bedeutet \u2014 eines von ${Nn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${Nn.join(", ")}.`},severity:"error"}):ho(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" von "${e.id}" hat die Bedeutung "${String(u)}" \u2014 erlaubt: ${Nn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${Nn.join(", ")}.`},severity:"error"})}for(let l of Object.keys(e.commentRequired??{}))o.has(l)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.commentRequired.${l}`,reason:{de:`[decision/commentRequiredUnknownOutcome] Unbekanntes Outcome "${l}" in commentRequired; erlaubt: ${[...o].join(", ")}`,en:`[decision/commentRequiredUnknownOutcome] Unknown outcome "${l}" in commentRequired; allowed: ${[...o].join(", ")}`},severity:"error"});let a=e.decisionAsTask?.title;return a!==void 0&&(a!==null&&typeof a=="object"&&Object.values(a).some(d=>typeof d=="string"&&d.length>0)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.decisionAsTask.title`,reason:{de:"[decision/decisionTaskMissingTitle] decisionAsTask.title ist gesetzt, aber leer \u2014 entweder einen nicht-leeren lokalisierten Text angeben oder das Feld weglassen (dann greift der Standardtitel).",en:"[decision/decisionTaskMissingTitle] decisionAsTask.title is set but empty \u2014 either give a non-empty localized text or omit the field (the default title then applies)."},severity:"error"})),r}s(_S,"validateDecisionNode");var NS=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],_K=[{id:"complete",label:{de:"Vollst\xE4ndig",en:"Complete"}},{id:"acceptedIncomplete",label:{de:"Ohne Nachreichung abgeschlossen",en:"Closed without the missing documents"}},{id:"rejected",label:{de:"Abgelehnt",en:"Rejected"}},{id:"absage",label:{de:"Zur\xFCckgezogen",en:"Withdrawn"}}];var PS="promoted";var NK="promote",PK="Nachr\xFCcken",ll="promoteLabel";var _Z={de:PK,en:"Promote from waitlist"};function NZ(e){let t=e.inputs?.[ll];if(t===void 0||t.kind==="unset")return _Z;let n=t.kind==="literal"?t.value:void 0;return os(n)!==null&&F(`waitlist node ${e.id}: inputs.${ll} ${JSON.stringify(t)} is not a { de, en } literal`),n}s(NZ,"promoteLabelOf");var CS={key:"warteliste",label:ie("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},CK={waitlisted:{label:ie("Warteliste","Waitlisted"),tone:"amber",phase:CS,external:at(ie("Warteliste","Waiting list"),"amber",ie("Sie stehen auf der Warteliste","You are on the waiting list"),ie("Ihre Bewerbung wurde auf die Warteliste gesetzt. Wir informieren Sie, sobald ein Platz frei wird.","Your application has been placed on the waiting list. We will let you know as soon as a place becomes available."))},promoted:{label:ie("Nachger\xFCckt","Promoted"),tone:"green",phase:CS,external:at(ie("Nachger\xFCckt","Moved up"),"green",ie("Sie sind nachger\xFCckt","You have moved up"),ie("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:ie("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:CS,external:at(ie("Warteliste geschlossen","Waiting list closed"),"red",ie("Die Warteliste wurde geschlossen","The waiting list has been closed"),ie("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},DK={outcomes:NS,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:cr.map(e=>({value:e,label:kN[e]}))},{id:ll,label:{de:"Beschriftung \u201ENachr\xFCcken\u201C",en:"Label of \u201CPromote\u201D"},type:"localizedText",required:!1,inspector:"literal-only"}],"inputs"),validate:s((e,t)=>{let n=e.inputs?.[ll];if(n?.kind==="literal"){let a=os(n.value);if(a!==null)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${ll}`,reason:{de:`[waitlist/promoteLabelText] Die Beschriftung \u201ENachr\xFCcken\u201C von "${e.id}" braucht einen Text auf Deutsch und auf Englisch (${a}).`,en:`[waitlist/promoteLabelText] The "Promote" label of "${e.id}" needs a text in German and in English (${a}).`},severity:"error"}]}let r=ik(e);if(r===null)return[];let i=t.nodes.filter(a=>a.type==="waitlist"&&a.id!==e.id),o=t.nodes.indexOf(e);for(let a of i){if(t.nodes.indexOf(a)>o)continue;let l=ik(a);if(l!==null&&l.waitlistOrder!==r.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${a.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 alle Wartelisten eines Prozesses ordnen gleich.`,en:`[waitlist/policyConflict] Waiting lists "${a.id}" and "${e.id}" state different orders \u2014 all waiting lists of a process order alike.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:CK,progressEvents:Yt(CK),entryProgressEvent:s(()=>"waitlisted","entryProgressEvent"),notificationEvents:s(()=>[{id:"placed",label:{de:"Auf die Warteliste gesetzt",en:"Placed on the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]},{id:"promoted",label:{de:"Nachger\xFCckt",en:"Promoted from the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]}],"notificationEvents"),actions:s(e=>(e.outcomes!==void 0&&e.outcomes.length>0?e.outcomes:NS).some(n=>n.id===PS)?[{id:NK,kind:"advance",outcome:PS,semantic:"other",label:NZ(e),surface:gr,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var DS="complete",Oc="acceptedIncomplete",Vh="rejected",PZ="absage",FK="closeWithoutDocuments",LK="rejectAtCompleteness",MK="Ohne Nachreichung abschlie\xDFen",qK="Ablehnen",FS="awaitingDocuments",LS="documentsComplete",MS="closedWithoutDocuments",qS="rejected",KS="withdrawn",KK="requested",g0e={[DS]:{event:LS,status:"complete",endsRole:!0},[Oc]:{event:MS,status:"acceptedIncomplete",endsRole:!1},[Vh]:{event:qS,status:"rejected",endsRole:!0},[PZ]:{event:KS,status:"withdrawn",endsRole:!0}};var _c=s(()=>pd[0],"beneficiary"),jS=366;function CZ(e){let t=e.reads,n=md(e).flatMap(({address:r})=>gt(r)&&!pd.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(gt):[],...n]}s(CZ,"printedFields");function DZ(e,t){let n=de(t);return e.nodes.filter(r=>r.type==="governedDocument"&&CZ(r).some(i=>de(i)===n))}s(DZ,"documentsPrinting");function FZ(e,t){if(!gt(t)||t.path!==_c())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!Pn(n)}s(FZ,"isCreatedFormBeneficiary");function Ht(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Ht,"issue");function LZ(e,t,n){let r=new Map(e.nodes.map(l=>[l.id,l])),i=t.next??{},o=new Set,a=[DS,Oc].flatMap(l=>{let d=i[l]?.to;return d===void 0?[]:[d]});for(;a.length>0;){let l=a.pop();if(o.has(l))continue;o.add(l);let d=r.get(l);if(d!==void 0&&!(d.type==="review"&&ke(d.form)&&ur(d.form)&&d.form.owner===n)){if(d.type==="end"){if(ls(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(LZ,"reachesApprovedEndUnreviewed");var VS={key:"unterlagen",label:ie("Unterlagen nachreichen","Outstanding documents"),scope:"node"},jK={[FS]:{label:ie("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:VS,external:at(ie("Unterlagen fehlen","Documents missing"),"amber",ie("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),ie("Uns fehlen noch einige Angaben oder Unterlagen. Sie finden die Liste und die Frist in Ihren Aufgaben.","Some details or documents are still missing. You will find the list and the deadline in your tasks."))},[LS]:{label:ie("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:VS,external:at(ie("Unterlagen vollst\xE4ndig","Documents complete"),"green",ie("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),ie("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[MS]:{label:ie("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:VS,external:at(ie("Abgeschlossen","Closed"),"neutral",ie("Die Nachreichung ist abgeschlossen","The document request is closed"),ie("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[qS]:{label:ie("Abgelehnt","Rejected"),tone:"red",phase:wC,external:at(ie("Abgelehnt","Rejected"),"red",ie("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),ie("Wir bedauern, Ihnen mitteilen zu m\xFCssen, dass wir Ihre Bewerbung nicht ber\xFCcksichtigen konnten.","We regret to inform you that we were unable to accept your application."))},[KS]:{label:ie("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:mm,external:at(ie("Zur\xFCckgezogen","Withdrawn"),"red",ie("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),ie("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},VK={outcomes:_K,progressDefaults:jK,progressEvents:Yt(jK),entryProgressEvent:s(()=>FS,"entryProgressEvent"),notificationEvents:s(()=>[{id:KK,label:{de:"Unterlagen angefordert",en:"Documents requested"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"fieldLabels",type:"localizedText",required:!0},{key:"dueAt",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=s(r=>e.next?.[r]!==void 0,"wired"),n=[];return t(Oc)&&n.push({id:FK,kind:"advance",outcome:Oc,semantic:"other",label:{de:MK,en:"Close without documents"},surface:gr,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Es geht ohne die fehlenden Unterlagen weiter. Die Anfrage an die Familie wird geschlossen.",en:"The application continues without the missing documents. The request to the family is closed."},confirmLabel:{de:"Abschlie\xDFen",en:"Close"}}}),t(Vh)&&n.push({id:LK,kind:"advance",outcome:Vh,semantic:"rejected",label:{de:qK,en:"Reject application"},surface:gr,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Der Platz wird abgesagt und die Anfrage an die Familie geschlossen. Das l\xE4sst sich nicht r\xFCckg\xE4ngig machen.",en:"The application is rejected and the request to the family is closed. This cannot be undone."},confirmLabel:{de:"Ablehnen",en:"Reject"}}}),n},"actions"),inputs:s(()=>[{id:"person",label:{de:"Person (Gasth\xF6rer-Rolle)",en:"Person (guest role)"},type:"personRef",required:!1},{id:"guestRole",label:{de:"Gastrolle bis zur Nachreichung",en:"Guest role until submitted"},type:"roleKey",required:!1,inspector:"literal-only",optionSource:"tenantRoles"}],"inputs"),validate:s((e,t,n)=>{let r=[],i=`Vollst\xE4ndigkeitspr\xFCfung \u201E${e.label?.de??e.id}\u201C (${e.id})`,o=`Completeness check "${e.label?.en||e.id}" (${e.id})`,a=s(A=>Ue(t,A,"de"),"shown"),l=s(A=>Ue(t,A,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Ht(e,"requires",{de:`[completenessCheck/missingRequires] ${i} nennt keine Felder \u2014 \`requires\` muss mindestens ein Feld eines Formulars enthalten ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/missingRequires] ${o} names no fields \u2014 \`requires\` must contain at least one field of a form ($node.<form>.admission.<field>).`}));else{let A=new Set;for(let T of d){if(!ke(T))continue;let I=de(T);if(A.has(I)){r.push(Ht(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(T)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(T)} appears twice in \`requires\`.`}));continue}if(A.add(I),!gt(T)){r.push(Ht(e,"requires",{de:`[completenessCheck/unknownField] ${a(T)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(T)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let C=ai(n,T);if(C==null)continue;let L=Ra("requires",Ta(C));L==="computed"||L==="repeated"?r.push(Ht(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(T)} ist ${C.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(T)} is ${C.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(Ht(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(T)} (\u201E${wo(C,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 die Benachrichtigung \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l(T)} ("${wo(C,"de")}") has no English name (field or person/section) \u2014 the notification "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},p="inDays"in u,h="until"in u;if(p===h)r.push(Ht(e,"deadline",{de:`[completenessCheck/deadlineShape] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" braucht genau eine Frist: \`{ inDays: n }\` (Tage ab Eintritt) oder \`{ until: "JJJJ-MM-TT" }\`.`,en:`[completenessCheck/deadlineShape] Completeness check "${e.id}" needs exactly one deadline: \`{ inDays: n }\` (days after entry) or \`{ until: "YYYY-MM-DD" }\`.`}));else if(p){let A=u.inDays;(typeof A!="number"||!Number.isInteger(A)||A<0||A>jS)&&r.push(Ht(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(A)}" ist keine ganze Zahl von 0 bis ${jS} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(A)}" is not a whole number from 0 to ${jS} days.`}))}else typeof u.until!="string"||Xk(u.until)===null?r.push(Ht(e,"deadline.until",{de:`[completenessCheck/deadlineDate] Frist "${String(u.until)}" ist kein g\xFCltiges Datum (JJJJ-MM-TT).`,en:`[completenessCheck/deadlineDate] Deadline "${String(u.until)}" is not a valid date (YYYY-MM-DD).`})):u.until<rD(Date.now())&&r.push({...Ht(e,"deadline.until",{de:`[completenessCheck/deadlinePassed] Frist "${u.until}" liegt in der Vergangenheit \u2014 jede Anfrage bek\xE4me den Tag des Eintritts als Frist. Datum aktualisieren?`,en:`[completenessCheck/deadlinePassed] Deadline "${u.until}" is in the past \u2014 every request would get the day of entry as its deadline. Update the date?`}),severity:"warning"});if(Array.isArray(d)){let A=new Map(d.filter(gt).map(T=>[de(T),T]));for(let T of A.values())for(let I of DZ(t,T))r.push(Ht(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(T)} flie\xDFt in das Dokument \u201E${I.label?.de??I.id}" (${I.id}) ein \u2014 nach dessen Ausstellung kann die Familie es nicht mehr nachreichen. Feld aus \`requires\` oder aus dem Dokument nehmen.`,en:`[completenessCheck/requiresConsumedUpstream] Field ${l(T)} flows into the document "${I.label?.en||I.id}" (${I.id}) \u2014 once it is issued, the family can no longer submit it later. Remove the field from \`requires\` or from the document.`}))}if(Array.isArray(d)&&n!==void 0){let A=d.filter(gt).filter(C=>{let L=ai(n,C);return L!=null&&Om(L)}),I=[...new Set(A.map(C=>C.owner))].filter(C=>LZ(t,e,C));if(I.length>0){let C=A.filter(L=>I.includes(L.owner));r.push({...Ht(e,"next",{de:`[review/unreviewedAfterSupply] ${C.map(a).join(", ")} ist pr\xFCfpflichtig und wird hier nachgereicht, aber nach \u201Evollst\xE4ndig\u201C oder \u201Eohne Nachreichung\u201C f\xFChrt ein Weg ohne Pr\xFCfknoten dieses Formulars zur Aufnahme \u2014 niemand pr\xFCft das Nachgereichte. Dort einen Pr\xFCfknoten einf\xFCgen (z. B. \u201EWenn nichts zu pr\xFCfen ist: Durchreichen\u201C).`,en:`[review/unreviewedAfterSupply] ${C.map(l).join(", ")} requires review and is supplied here, but after "complete" or "accepted incomplete" a path without a review node of this form leads to admission \u2014 nobody reviews what was supplied. Insert a review node there (e.g. "When nothing is owed: pass through").`}),severity:"warning"})}}let y=e.inputs?.guestRole,b=y?.kind==="literal"?y.value:void 0,k=e.inputs?.person,v=k?.kind==="binding"?k.address:null;b!==void 0&&(typeof b!="string"||b.trim()===""?r.push(Ht(e,"inputs.guestRole",{de:"[completenessCheck/guestRoleEmpty] `guestRole` ist leer \u2014 Rollenschl\xFCssel angeben oder das Feld weglassen.",en:"[completenessCheck/guestRoleEmpty] `guestRole` is empty \u2014 give a role key or omit the field."})):n?.roleKeys!==void 0&&!n.roleKeys.has(b)?r.push(Ht(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${b}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${b}" does not exist in this school's role catalog. Known roles: ${[...n.roleKeys].sort().join(", ")}.`})):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(b)&&r.push(Ht(e,"inputs.guestRole",{de:`[completenessCheck/nonLeafRole] Rolle "${b}" hat untergeordnete Rollen und ist nicht vergebbar.`,en:`[completenessCheck/nonLeafRole] Role "${b}" has sub-roles and cannot be assigned.`})),v===null&&r.push(Ht(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(b)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${Wt}.${_c()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(b)}", but the input "person" is not bound (e.g. to $node.<form>.${Wt}.${_c()}).`}))),ke(v)&&!FZ(t,v)&&r.push(Ht(e,"inputs.person",{de:`[completenessCheck/personNotFormParty] Eingang \u201Eperson" ist an ${a(v)} gebunden \u2014 die Pr\xFCfung vergibt die Rolle der Person, f\xFCr die ein Formular abgeschickt wurde ($node.<anlegender Formularknoten>.${Wt}.${_c()}).`,en:`[completenessCheck/personNotFormParty] The input "person" is bound to ${l(v)} \u2014 the check assigns the role to the person a form was submitted for ($node.<creating form node>.${Wt}.${_c()}).`})),v!==null&&b===void 0&&r.push(Ht(e,"inputs.person",{de:'[completenessCheck/personWithoutRole] Eingang \u201Eperson" ist gebunden, aber es wird keine Rolle vergeben \u2014 die Bindung wirkt nicht.',en:'[completenessCheck/personWithoutRole] The input "person" is bound, but no role is assigned \u2014 the binding has no effect.'}));for(let A of["complete","rejected"])e.next?.[A]===void 0&&r.push(Ht(e,`next.${A}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${A}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${A}" nowhere.`}));return r},"validate")};var MZ=[{id:vN,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Bh=s(e=>e,"asDecision"),BK={[lk]:{label:ie("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:ie("In Pr\xFCfung","In review"),scope:"node"},external:at(ie("Eingereicht","Submitted"),"blue",ie("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),ie("Ihre Bewerbung ist bei uns eingegangen. Wir pr\xFCfen jetzt Ihre Unterlagen und melden uns, falls etwas fehlt.","We have received your application. We are now reviewing your documents and will get in touch if anything is missing."))}},UK={role:"user-action",effect:"side-effect",outcomes:MZ,progressDefaults:BK,progressEvents:Yt(BK),entryProgressEvent:s(()=>lk,"entryProgressEvent"),advancesAtEntry:s(e=>ov(e)==="advance","advancesAtEntry"),notificationEvents:s(e=>Ns.notificationEvents(Bh(e)),"notificationEvents"),inputs:s(()=>[{id:Qn,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Ss.map(e=>({value:e,label:r0[e]}))}],"inputs"),actions:s(e=>[...Ns.actions(Bh(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:ak,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Ns.optionalActionKinds,workItemTemplates:s(e=>Ns.workItemTemplates(Bh(e)).map(t=>t.key===Gi?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,ak]}:t),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),taskView:s((e,t)=>t===Gi&&e.form!==void 0&&ur(e.form)?{kind:"form",form:e.form.owner,view:gL}:void 0,"taskView"),placelessTasks:{[Gi]:"A review without a form has no checklist to tick; its row is finished in its step (\u201EPr\xFCfung abschlie\xDFen\u201C)."},validate:s((e,t,n)=>{let r=_S(Bh(e),t,n);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!jp.includes(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/rejectingOutcome] Pr\xFCf-Knoten "${e.id}" deklariert das Outcome "${c.id}" mit der Bedeutung "${String(u)}" \u2014 eine Pr\xFCfung lehnt nicht ab und setzt nicht auf die Warteliste; das ist die Entscheidung der Freigabe bzw. \u201EBewerbung ablehnen".`,en:`[review/rejectingOutcome] Review node "${e.id}" declares the outcome "${c.id}" meaning "${String(u)}" \u2014 a review neither rejects nor waitlists; that is the decision of the approval or "Reject application".`},severity:"error"})}let i={de:`\u201E${e.label?.de??e.id}\u201C (${e.id})`,en:`"${e.label?.en||e.id}" (${e.id})`},o=e.inputs?.[Qn],a=ov(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Qn}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${Ss.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${Ss.join(" or ")}.`},severity:"error"});let l=a==="advance",d=e.form;if(l&&d===void 0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:{de:`[review/advanceNeedsForm] Pr\xFCf-Knoten ${i.de} reicht durch, wenn nichts zu pr\xFCfen ist, nennt aber kein Formular \u2014 er w\xFCrde immer durchreichen. Nenne das Formular, dessen pr\xFCfpflichtige Felder er pr\xFCft.`,en:`[review/advanceNeedsForm] Review node ${i.en} passes through when nothing is owed but names no form \u2014 it would always pass through. Name the form whose review-required fields it checks.`},severity:"error"}),l&&(e.outcomes??[]).length!==1&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/advanceOneOutcome] Pr\xFCf-Knoten ${i.de} reicht durch, hat aber ${(e.outcomes??[]).length} Outcomes \u2014 durchgereicht wird \xFCber genau eines.`,en:`[review/advanceOneOutcome] Review node ${i.en} passes through but has ${(e.outcomes??[]).length} outcomes \u2014 it passes through over exactly one.`},severity:"error"}),ke(d)&&ur(d)){let c=n?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(Om)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${de(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt w\xFCrde jedes Mal durchreichen. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${de(d)}, but that form declares no field review-required \u2014 the step would pass through every time. Mark the fields "Review required" in the form.`}:{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${de(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt wartet, ohne dass etwas abzuhaken ist. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${de(d)}, but that form declares no field review-required \u2014 the step waits with nothing to tick. Mark the fields "Review required" in the form.`},severity:l?"error":"warning"})}return r},"validate")};var GK=["awaitingAnswer","answered"];async function zK(e,t){return(await Pa(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(zK,"externalRequestState");var HK=[{id:ss,label:{de:"Bezahlt",en:"Paid"}}],tMe=new Set(HK.map(e=>e.id));var qZ=ss,WK=[{id:qZ,kind:"advance",outcome:ss,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],KZ={id:Dk,kind:"advance",outcome:ss,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:gr,confirm:{title:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},body:{de:"Die Geb\xFChr ist au\xDFerhalb von Plexus eingegangen. Der Schritt wird als separat bezahlt abgeschlossen, die Aufgabe der Familie schlie\xDFt mit.",en:"The fee was received outside Plexus. The step is completed as paid separately; the family's task closes with it."},confirmLabel:{de:"Best\xE4tigen",en:"Confirm"}}},jZ={id:Ck,kind:"advance",outcome:ss,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:gr,superUserOnly:!0,confirm:{title:{de:"Zahlung \xFCberspringen",en:"Skip payment"},body:{de:"Die Geb\xFChr wird au\xDFerhalb von Plexus abgerechnet. Der Schritt wird ohne Zahlung abgeschlossen; es wird kein Betrag als bezahlt verbucht.",en:"The fee is billed outside Plexus. The step is completed without a payment; no amount is recorded as paid."},confirmLabel:{de:"\xDCberspringen",en:"Skip"}}},VZ={id:Ck,kind:"advance",outcome:ss,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:gr,superUserOnly:!0,availableIn:["awaitingAnswer"],confirm:{title:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},body:{de:"Die Familie hat nicht online \xFCber Plexus bezahlt. Der Schritt wird ohne Online-Zahlung abgeschlossen; eine offene Zahlungsseite wird geschlossen. Bitte den Grund angeben (z. B. bar bezahlt).",en:"The family did not pay online through Plexus. The step is completed without an online payment; an open payment page is closed. Please give the reason (e.g. paid in cash)."},confirmLabel:{de:"Abschlie\xDFen",en:"Complete"}},commentRequired:!0};function BS(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(BS,"literalOf");function Ro(e){let t=BS(e,on);return Zp(t)?t:null}s(Ro,"modeOrNull");function BZ(e){let t=BS(e,_i);return typeof t=="string"&&t.length>0?t:null}s(BZ,"articleKeyOrNull");function UZ(e){let t=BS(e,Wn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(UZ,"payeeKeyOrNull");var GZ={id:_i,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},zZ={id:on,label:{de:"Zahlungsweg",en:"Payment mode"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"manual",label:{de:"Manuell (\xDCberweisung an die Schule)",en:"Manual (transfer to the school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},WZ={id:Ni,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},YZ={id:Wn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function HZ(e){return[GZ,zZ,...Ro(e)==="online"?[YZ]:[],WZ]}s(HZ,"collectPaymentInputs");var JZ=["amount","currency","settlement"],QZ={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},ZZ={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function XZ(e,t){if(Ro(e)!=="online")return[];let n=UZ(e);if(n===null)return[];let r=`nodes.${e.id}.inputs.${Wn}`,i=s(o=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:o,severity:"error"}),"at");return t?.traeger!==void 0&&!t.traeger.has(n)?[i({de:`[collectPayment/unknownPayee] Zahlungsempf\xE4nger \u201E${n}" ist kein Tr\xE4ger dieses Mandanten \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[collectPayment/unknownPayee] Payee "${n}" is not a legal entity of this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})]:t?.stripeReadyTraegerKeys!==void 0&&!t.stripeReadyTraegerKeys.has(n)?[i({de:`[collectPayment/onlineWithoutStripe] Zahlungsweg \u201Eonline" an \u201E${n}" setzt voraus, dass dieser Tr\xE4ger ein einsatzbereites Stripe-Konto hat (Administration \u2192 Integrationen \u2192 Stripe, Tr\xE4ger \u201E${n}") \u2014 sonst kann keine Familie bezahlen. Bis dahin \u201Emanual" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Payment mode "online" to "${n}" requires this legal entity to have a ready Stripe account (Administration \u2192 Integrations \u2192 Stripe, legal entity "${n}") \u2014 otherwise no family can pay. Until then, choose "manual".`})]:[]}s(XZ,"payeeIssues");var YK={awaitingPayment:{label:ie("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:ie("Zahlung","Payment"),scope:"node"},external:at(ie("Zahlung offen","Payment due"),"amber",ie("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),ie("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},JK={outputs:s(()=>[{name:tP,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>HZ(e),"inputs"),outcomes:HK,progressDefaults:YK,progressEvents:Yt(YK),entryProgressEvent:s(()=>"awaitingPayment","entryProgressEvent"),notificationEvents:s(e=>Ro(e)!=="online"?[]:[{id:"requested",label:{de:"Zahlung angefordert",en:"Payment requested"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"amount",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=Ro(e);return t==="online"?[...WK,VZ]:t==="manual"?[KZ,jZ]:[]},"actions"),states:GK,currentState:s((e,t)=>zK(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:Ro(t.node)==="manual"?IS:ES}),"currentState"),placelessTasks:{[Lr]:"A payment has no document or form view; the team confirms it in its step's action bar."},workItemTemplates:s(e=>{let t=e,n=Ro(t);return n==="manual"?[{key:Lr,recipient:"internal",title:QZ,unlocks:[Dk],advancesNode:!0},{key:IS,recipient:"external",title:ZZ,unlocks:[],informational:!0,advancesNode:!1}]:n!=="online"?[]:[{key:ES,recipient:"external",title:t.label,unlocks:WK.map(r=>r.id),advancesNode:!0}]},"workItemTemplates"),validate:s((e,t,n)=>{let r=[],i=s((d,c)=>r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${d}`,reason:c,severity:"error"}),"push");for(let d of JZ)d in e&&i(d,{de:`[collectPayment/retiredField] \u201E${d}" steht nicht mehr am Zahlungsknoten \u2014 Betrag und W\xE4hrung kommen aus dem Artikel (Parameter \u201EArtikel"), der Zahlungsweg ist der Parameter \u201EZahlungsweg" (inputs.mode).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and the payment mode is the parameter "Payment mode" (inputs.mode).`});r.push(...XZ(e,n)),Ro(e)==="manual"&&e.assign?.[Lr]===void 0&&i("assign",{de:"[collectPayment/assign] Die Geb\xFChr wird manuell bezahlt, aber kein Team best\xE4tigt den Zahlungseingang \u2014 `assign.confirmPayment` nennt das Team.",en:"[collectPayment/assign] The fee is paid manually, but no team confirms the payment \u2014 `assign.confirmPayment` names the team."}),Ro(e)===null&&i(`inputs.${on}`,{de:`[collectPayment/invalidMode] Zahlungsweg muss einer von ${va.join(", ")} sein (online = die Familie zahlt im Portal, manual = die Schule erh\xE4lt das Geld au\xDFerhalb von Plexus); erhalten ${JSON.stringify(e.inputs?.[on])}.`,en:`[collectPayment/invalidMode] Payment mode must be one of ${va.join(", ")} (online = the family pays in the portal, manual = the school receives the money outside Plexus); received ${JSON.stringify(e.inputs?.[on])}.`});let o=e.inputs?.[Ni];if(o?.kind==="literal"){let d=os(o.value);d!==null&&i(`inputs.${Ni}`,{de:`[collectPayment/reasonText] Der Hinweis f\xFCr die Familie braucht einen Text auf Deutsch und auf Englisch (${d}).`,en:`[collectPayment/reasonText] The note for the family needs a text in German and in English (${d}).`})}let a=BZ(e);if(a===null)return i(`inputs.${_i}`,{de:'[collectPayment/missingArticle] Der Zahlungsknoten nennt keinen Artikel \u2014 unter \u201EParameter" einen einmaligen Artikel des Programms w\xE4hlen (Finanzen \u2192 Artikel).',en:'[collectPayment/missingArticle] The payment node names no article \u2014 under "Parameters" choose a one-time article of the program (Finance \u2192 Articles).'}),r;let l=`inputs.${_i}`;return n?.billingItemKeys!==void 0&&!n.billingItemKeys.has(a)?(i(l,{de:`[collectPayment/unknownArticle] Artikel \u201E${a}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel.`,en:`[collectPayment/unknownArticle] Article "${a}" \u2014 no article of this school has this key.`}),r):(n?.oneTimeBillingItemKeys!==void 0&&!n.oneTimeBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotOneTime] Artikel \u201E${a}" ist kein einmaliger Artikel \u2014 eine Geb\xFChr nimmt nur ${Fk.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${Fk.join(", ")}.`}),n?.offerProgram===null?i(l,{de:"[collectPayment/articleOfferWithoutProgram] Das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.",en:"[collectPayment/articleOfferWithoutProgram] The offer is not assigned to a program, so no article belongs to it; give the offer a program."}):n?.offerProgram?.directBillingItemKeys!==void 0&&!n.offerProgram.directBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotInProgram] Artikel \u201E${a}" ist dem Programm \u201E${n.offerProgram.nameDe}" des Angebots nicht direkt zugeordnet \u2014 unter Finanzen \u2192 Artikel zuordnen (ein Paket z\xE4hlt nicht: es kann den Artikel anders bepreisen).`,en:`[collectPayment/articleNotInProgram] Article "${a}" is not directly assigned to the offer's program "${n.offerProgram.nameDe}" \u2014 assign it under Finance \u2192 Articles (a package does not count: it can price the article differently).`}),r)},"validate")};function QK(e){return{de:`[governedDocument/localeFieldMissing] Die Vorlage "${e}" nennt kein Sprachfeld \u2014 ein Schreiben entsteht in genau einer Sprache. Ein Pflicht-Auswahlfeld mit den Optionen de/en unter den Parametern der Vorlage anlegen, es als localeField der Vorlage nennen und im Knoten an die Sprache des Benutzerkontos binden ($env.applicant.language); die Word-Datei h\xE4lt je Sprache einen Abschnitt <<#input.<feld>.de>> \u2026 <</input.<feld>.de>>.`,en:`[governedDocument/localeFieldMissing] The template "${e}" names no language field \u2014 a letter is written in exactly one language. Create a required choice field with the options de/en among the template's parameters, name it as the template's localeField and bind it in the node to the language of the user account ($env.applicant.language); the Word file holds one section per language <<#input.<field>.de>> \u2026 <</input.<field>.de>>.`}}s(QK,"localeFieldMissingText");var US=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),ZK=/^[a-z][a-z0-9_]*$/;function XK(e,t){let n=[],r=e?.fields;if(!Array.isArray(r))return[{path:"",reason:{de:`[governedDocument/missingTemplateFields] Die Vorlage "${t}" deklariert keine Parameter \u2014 erwartet wird { fields } (die Platzhalter input.<schl\xFCssel>, die ein Knoten f\xFCllt).`,en:`[governedDocument/missingTemplateFields] The template "${t}" declares no parameters \u2014 expected { fields } (the placeholders input.<key> a node fills).`}}];let i=r,o=new Set;for(let a of i){if(typeof a?.key!="string"||!ZK.test(a.key)||o.has(a.key)){n.push({path:`fields.${String(a?.key)}`,reason:{de:`[governedDocument/templateFieldKey] Feld "${String(a?.key)}" der Vorlage "${t}" ist ${o.has(a?.key)?"doppelt":"kein g\xFCltiger Schl\xFCssel"} \u2014 erlaubt sind eindeutige Kleinbuchstaben, Ziffern und _ (gedruckt als input.<schl\xFCssel>).`,en:`[governedDocument/templateFieldKey] Field "${String(a?.key)}" of the template "${t}" is ${o.has(a?.key)?"duplicated":"not a valid key"} \u2014 allowed are unique lower-case letters, digits and _ (printed as input.<key>).`}});continue}o.add(a.key);let l=`fields.${a.key}`;if(!yo(a.type)){n.push({path:l,reason:{de:`[governedDocument/unknownFieldType] Vorlage "${t}" typisiert das Feld "${a.key}" als "${String(a.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${ba.join(", ")}).`,en:`[governedDocument/unknownFieldType] Template "${t}" types the field "${a.key}" as "${String(a.type)}" \u2014 that is not part of the platform's value vocabulary (${ba.join(", ")}).`}});continue}if(US.has(a.type)||n.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${t}" hat den Typ "${a.type}" \u2014 ein Dokument aus einer Vorlage druckt nur ${[...US].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a document from a template only prints ${[...US].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!ZK.test(String(d.value)))&&n.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${t}" hat Optionen, die kein Platzhalter adressieren kann (${a.options.map(d=>d.value).join(", ")}) \u2014 Optionswerte sind Kleinbuchstaben, Ziffern und _ (gedruckt als input.${a.key}.<option>).`,en:`[governedDocument/templateFieldKey] Select field "${a.key}" of the template "${t}" has options no placeholder can address (${a.options.map(d=>d.value).join(", ")}) \u2014 option values are lower-case letters, digits and _ (printed as input.${a.key}.<option>).`}}),a.type==="enum"&&(!Array.isArray(a.options)||a.options.length===0)&&n.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${t}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${t}" names no options \u2014 without them there are no sections input.${a.key}.<option>.`}}),a.type==="pricedItem"){let d=i.find(c=>c.key===a.priceDate);(d===void 0||d.type!=="date")&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${t}" nennt kein Preisdatum \u2014 priceDate muss ein Datumsfeld derselben Vorlage sein (welche Preisversion gilt); genannt: ${JSON.stringify(a.priceDate)}.`,en:`[governedDocument/templateFieldPriceDate] Price field "${a.key}" of the template "${t}" names no price date \u2014 priceDate must be a date field of the same template (which price version applies); named: ${JSON.stringify(a.priceDate)}.`}})}else a.priceDate!==void 0&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Feld "${a.key}" setzt priceDate, ist aber kein Preisfeld (pricedItem).`,en:`[governedDocument/templateFieldPriceDate] Field "${a.key}" sets priceDate but is not a price field (pricedItem).`}});a.processSource==="countersignature"?n.push({path:l,reason:{de:`[governedDocument/countersignatureInTemplate] Feld "${a.key}" wird bei einer Gegenzeichnung gesetzt \u2014 ein Dokument aus einer Vorlage wird nicht gegengezeichnet.`,en:`[governedDocument/countersignatureInTemplate] Field "${a.key}" is set at a countersignature \u2014 a document from a template is not countersigned.`}}):a.processSource!==void 0&&!jm.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${jm.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${jm.join(", ")}.`}})}return n.push(...e9(e,t)),n}s(XK,"templateParameterIssues");function e9(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:QK(t)}];let n=e.fields.find(i=>i.key===e.localeField),r=n===void 0?{de:"nennt kein Feld der Vorlage",en:"names no field of the template"}:n.type!=="enum"?{de:`ist ${n.type}, erwartet wird ein Auswahlfeld (enum)`,en:`is ${n.type}, a select field (enum) is expected`}:n.required!==!0?{de:"ist kein Pflichtfeld \u2014 ohne Sprache gibt es keine Variante",en:"is not a required field \u2014 without a language there is no variant"}:(n.options??[]).length===0?{de:"hat keine Optionen",en:"has no options"}:(n.options??[]).some(i=>!Ge.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${Ge.join(", ")})`,en:`has options that are not a language (allowed: ${Ge.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${t}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${t}" ${r.en}.`}}]}s(e9,"localeFieldIssues");function ej(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(ej,"applyTemplateStamp");var GS=50;async function Uh(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take(GS+1);return n.length>GS&&F(`signing_returns: Vorgang ${t} has more than ${GS} returns`),n}s(Uh,"returnsOf");var zS=50;async function WS(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(zS+1);return n.length>zS&&F(`signing_returns: return ${t} has more than ${zS} files`),n.length===0&&F(`[signing/noDocument] return ${t} carries no file`),n}s(WS,"returnDocumentsOf");async function tj(e,t){let n=await WS(e,t);return n.length!==1&&F(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(tj,"soleReturnDocumentOf");var Gh=200,vMe=Gh*20;async function t9(e,t){let n=await e.db.get(t);return n===null&&F(`[process] application ${t} not found`),n.redactedAt!==void 0}s(t9,"processRedacted");async function YS(e,t){await t9(e,t)&&ue("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(YS,"assertProcessReadable");function n9(e){let t={_id:e._id,_creationTime:e._creationTime,owner:e.owner,key:e.key};return e.scope==="task"?{...t,scope:"task",result:{kind:"value",value:e.value},writtenByTaskId:e.writtenByTaskId}:{...t,scope:"node",result:e.result}}s(n9,"rowOf");async function nj(e,t,n){await YS(e,t);let r=await e.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",i=>i.eq("applicationId",t).eq("scope",n.scope).eq("owner",n.owner).eq("key",n.key)).order("desc").take(Gh+1);return r.length>Gh&&F(`[process] application ${t} has more than ${Gh} results of ${n.scope}.${n.owner}.${n.key}`),r.map(n9)}s(nj,"storeHistory");async function r9(e,t,n){if(n.key===Wt){await YS(e,t);let i=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",o=>o.eq("applicationId",t).eq("formNodeId",n.owner)).unique();return i===null||i.state!=="committed"?{state:"pending",reason:null}:{state:"present",result:{kind:"ref",ref:{kind:"form",formInstanceId:i._id}},row:null}}let[r]=await nj(e,t,{scope:"node",owner:n.owner,key:n.key});return r===void 0?{state:"pending",reason:null}:{state:"present",result:r.result,row:r}}s(r9,"nodeResultAt");async function zh(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return i9(await r9(e,t.applicationId,n),n,t.applicationId)}s(zh,"readOwnResult");function i9(e,t,n){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${de(t)} of application ${n} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(i9,"refOf");var HS={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},o9=Object.keys(HS),s9=o9.filter(e=>HS[e]==="open"),OMe=s9.filter(e=>e!=="pending");function rj(e){return HS[e]==="terminal"}s(rj,"isTerminalSigningStatus");var $o=["docusign","insign"];var Nc={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var l9=rj;function oj(e){return!l9(e.status)&&e.voidRequestedAt===void 0}s(oj,"holdsContract");async function sj(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(sj,"traegerLegalEntityOfParty");async function d9(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(d9,"isOrganizationParty");async function aj(e,t){return await sj(e,t)!==null?"traeger":await d9(e,t)?"organization":"person"}s(aj,"signerKindOf");async function lj(e,t){t.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await c9(e,n.partyId)==="family")return"family";return"traeger"}s(lj,"signingSideOf");async function c9(e,t){return await aj(e,t)==="traeger"?"traeger":"family"}s(c9,"sideOfParty");var mqe=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),cj=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var JS=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),Wh=m.object({period:JS,anchorDate:m.string()});var kqe=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),bqe=m.union(m.literal("line"),m.literal("aggregate")),Yh=m.record(m.string(),m.string());var u9=m.union(m.literal("active"),m.literal("ended")),QS=m.union(m.object({mode:m.literal("track")}),m.object({mode:m.literal("pin"),billingItemVersionId:ze.restrict(m.id("billing_item_versions"),{unindexed:"pinned price version inside the pricing union"})}),m.object({mode:m.literal("override"),amount:m.number()})),f9=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),p9={contractId:ze.belongsTo(m.id("contracts")),billingItemDefinitionId:ze.restrict(m.id("billing_item_definitions")),pricing:QS,pricingSelections:m.optional(Yh),paymentSchedule:m.optional(Wh),resolvedSnapshot:m.any(),feeGroup:m.optional(cj),generationRunId:m.optional(ze.history(m.id("contract_generation_runs")))},m9={...p9,period:f9,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:u9,enrollmentContextId:m.optional(ze.restrict(m.id("enrollments")))},Eqe=Gn(m9).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var Mr=m.union(m.string(),m.null()),uj=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),h9=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string(),representative:m.optional(m.object({userId:m.id("users"),nameAtSigning:m.string(),email:m.string()}))}),fj=m.object({sourceAllocationId:m.id("payer_allocations"),scope:m.union(m.object({kind:m.literal("contract")}),m.object({kind:m.literal("contract_line"),contractLineId:m.id("contract_lines")})),payer:m.union(m.object({kind:m.literal("party"),partyId:m.id("parties"),nameAtSigning:m.string()}),m.object({kind:m.literal("payment_method"),paymentMethodId:m.id("payment_methods"),label:m.string(),ownersAtSigning:m.array(uj)})),sharePct:m.union(m.number(),m.null()),flatAmount:m.union(m.number(),m.null()),cap:m.union(m.number(),m.null()),activeFrom:m.string(),activeTo:Mr}),pj=m.object({sourceAppliedGrantId:m.string(),sourceGrantTemplateId:m.union(m.string(),m.null()),name:m.string(),reason:m.string(),kind:m.string(),value:m.number(),rule:m.optional(m.any()),scope:m.optional(m.union(m.literal("line"),m.literal("aggregate"))),floorTotal:m.optional(m.number()),pricePeriod:m.optional(JS),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:Mr,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),g9={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:Mr,pricing:QS,paymentSchedule:m.optional(Wh),pricingSelections:m.optional(Yh),billingItemDefinition:m.object({sourceBillingItemDefinitionId:m.id("billing_item_definitions"),name:m.string(),itemType:m.string(),configOpaque:m.any()}),resolvedSnapshotOpaque:m.any(),enrolment:m.union(m.object({sourceEnrolmentId:m.id("enrollments"),status:m.string(),startDate:Mr,endDate:Mr,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:Mr,programName:Mr,runName:Mr,groupName:Mr}),m.null()),grants:m.array(pj),payerAllocations:m.array(fj)},y9=m.object({...g9,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:Mr,sourceValidTo:Mr})}),w9=m.object({formatVersion:m.literal(2),contract:m.object({scope:m.string(),generator:m.object({sourceGeneratorDefinitionId:m.id("contract_generator_definitions"),sourceCreationTime:m.number(),name:m.string(),bodyOpaque:m.any()})}),parties:m.array(uj),declaredSigners:m.array(h9),payerAllocations:m.array(fj),aggregateGrants:m.optional(m.array(pj)),lines:m.array(y9)}),k9=w9;var b9=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),v9=m.object({pageCount:m.number(),spots:m.array(m.object({signer:m.union(m.object({kind:m.literal("party"),role:m.string(),ordinal:m.union(m.number(),m.null())}),m.object({kind:m.literal("named"),label:Ui})),caption:m.string(),page:m.number(),box:b9}))});var x9=m.object({storageId:ze.holds(m.id("_storage")),sourceArtifactId:m.optional(ze.history(m.id("admission_documents"))),sha256:m.string(),filename:m.string(),source:m.union(m.object({kind:m.literal("uploaded")}),m.object({kind:m.literal("machine_rendered"),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),signaturePlacement:m.optional(v9)}))}),S9=m.object({storageId:ze.holds(m.id("_storage")),sha256:m.string(),filename:m.string(),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),confirmationRequired:m.boolean()}),A9={importedTemplateSource:m.optional(m.object({id:m.string(),creationTime:m.number()})),tenantId:ze.tenant(m.id("tenants")),contractId:ze.restrict(m.id("contracts")),snapshotNumber:m.optional(m.number()),revisionNumber:m.optional(m.number()),supersedesSnapshotId:m.optional(ze.history(m.id("contract_snapshots"))),frozenAt:m.number(),frozenByUserId:m.optional(ze.history(m.id("users"))),document:x9,coverLetter:m.optional(S9),snapshot:ze.historyOf(k9),generation:m.optional(m.object({generatorVersionId:m.optional(ze.history(m.id("contract_generator_versions"))),generatorRevisionId:m.optional(m.string()),implementationKey:m.string(),implementationChecksum:m.string(),input:m.any(),output:m.any()}))},Lqe=Gn(A9).index("by_tenantId",["tenantId"]).index("by_document_storageId",["document.storageId"]).index("by_coverLetter_storageId",["coverLetter.storageId"]).index("by_contractId_and_snapshotNumber",["contractId","snapshotNumber"]).index("by_supersedesSnapshotId",["supersedesSnapshotId"]).index("by_generation_generatorVersionId",["generation.generatorVersionId"]);var Qqe=16*1024;var Zqe=15*6e4;var Xqe=10*6e4;var ZS={contractSnapshotId:ze.restrict(m.id("contract_snapshots")),storageId:ze.restrict(m.id("_storage")),sha256:m.string(),filename:m.string(),uploadedAt:m.number(),signers:m.array(m.object({partyId:ze.history(m.id("parties")),role:m.string()}))},gKe=Gn({tenantId:ze.tenant(m.id("tenants")),signingRequestDocumentId:ze.belongsTo(m.id("signing_request_documents")),...ZS}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var vKe=m.object(ZS);var XS=200;async function T9(e,t,n,r){t.length>XS&&F(`${r} is carried by more than ${XS} signing requests`);let i=[],o=new Set;for(let l of t){if(o.has(l.signingRequestId))continue;o.add(l.signingRequestId);let d=await e.db.get(l.signingRequestId);d===null&&F(`signing_request_documents ${l._id} names a missing signing request ${l.signingRequestId}`),i.push(d)}let a=n==="asc"?1:-1;return i.sort((l,d)=>a*(l._creationTime-d._creationTime))}s(T9,"requestsOfMembers");async function mj(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(XS+1);return await T9(e,r,n,`revision ${t}`)}s(mj,"requestsOfSnapshot");var hj=100;async function R9(e,t){let n=await mj(e,t);n.length>hj&&F(`requestsBySideOf: revision ${t} has more than ${hj} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await lj(e,i.signers)].push(i);return r}s(R9,"requestsBySideOf");async function eA(e,t){return(await R9(e,t)).family}s(eA,"familyRequestsOf");var tA=100;async function $9(e,t){let n=await e;return n.length>tA&&F(`contractChain: more than ${tA} ${t}`),n}s($9,"bounded");async function E9(e,t,n){let r=await zh(e,{applicationId:t,nodeId:n,key:Wp});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${n}.${Wp} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(E9,"nodeContractRef");async function gj(e,t){return await $9(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",n=>n.eq("contractId",t)).take(tA+1),`revisions on contract ${t}`)}s(gj,"snapshotsAsc");async function nA(e,t){let n=(await eA(e,t)).filter(oj);return n.length>1&&F(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s(nA,"openFamilyRequest");async function I9(e,t){for(let n of await gj(e,t))if((await eA(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(I9,"familyRoute");async function yj(e,t){for(let n of t)if(await I9(e,n)==="paper")return"paper";return"provider"}s(yj,"familyRouteOf");async function O9(e,t){let n=await tj(e,t._id),r=await e.db.system.get("_storage",n.storageId);return r===null&&F(`contractChain: return ${t._id} holds missing file ${n.storageId}`),{_id:t._id,_creationTime:t._creationTime,storageId:n.storageId,filename:n.filename,...r.contentType!==void 0?{mimeType:r.contentType}:{},round:t._id}}s(O9,"toReturn");function Hh(e){async function t(a,l){return await E9(a,l,e.id)}s(t,"contractOrNull");async function n(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),p=u===null?null:await a.db.get(u),h=await t(a,l);return(p===null||h===null||p.contractId!==h)&&F(`${c}: ${d} is no revision of node "${e.id}"'s contract ${h??"(none yet)"} \u2014 corrupt arc`),p}s(n,"snapshotOf");async function r(a,l){let d=await t(a,l);return d===null?null:(await gj(a,d)).at(-1)??null}return s(r,"newestSnapshot"),{reads:{kind:"contract",async returned(a,l,d){if(d.askedAbout===void 0){if(d.onUnpinned==="notReturned")return null;F(`returned(${d.where}): an ask of the contract chain is always pinned to its revision`)}let c=await n(a,l,d.askedAbout,`returned(${d.where})`),u=await nA(a,c._id);if(u===null)return null;let p=(await Uh(a,u._id)).filter(h=>h.review.status==="pending"&&h._id!==d.rejected);return p.length>1&&F(`returned(${d.where}): Vorgang ${u._id} has ${p.length} returns pending \u2014 one is checked at a time`),p[0]===void 0?null:await O9(a,p[0])},pinOf(a){return a.contractSnapshotId},returnPinOf(a){return a.signingReturnId}},contractOrNull:t,snapshotOf:n,newestSnapshot:r,contractsOf:{async contractsOf(a,l){let d=await t(a,l);return d===null?[]:[d]}}.contractsOf}}s(Hh,"contractNodeReads");async function _9(e,t){let n=await e.db.system.get("_storage",t);return n===null?null:{...n.contentType===void 0?{}:{mimeType:n.contentType},sizeBytes:n.size,sha256:DM(n.sha256)}}s(_9,"storedObjectMeta");async function rA(e,t){let n=(await _9(e,t))?.mimeType;return n===void 0?{}:{mimeType:n}}s(rA,"objectType");function Jh(e){return e.addedParts??[]}s(Jh,"addedPartsOf");var iA=50;async function N9(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(iA+1);return n.length>iA&&F(`groupRunsOf: generation group ${t} has more than ${iA} runs`),n.length===0&&F(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(N9,"groupRunsOf");async function wj(e,t){let n=await N9(e,t),r=n[0].packageRunId;if(r!==void 0){(n.some(l=>l.packageRunId!==r||l.partKey===void 0)||new Set(n.map(l=>l.partKey)).size!==n.length)&&F(`groupRunsInOrder: package group ${t} has inconsistent members`);let i=await e.db.get(r);i===null&&F(`groupRunsInOrder: package run ${t} is missing`);let o=await e.db.query("contract_package_parts").withIndex("by_packageVersionId_and_position",l=>l.eq("packageVersionId",i.packageVersionId)).take(51),a=[...o.map(l=>l.partKey),...Jh(i).map(l=>l.partKey)];return(o.length>50||n.some(l=>!a.includes(l.partKey)))&&F(`groupRunsInOrder: package group ${t} names an unknown part`),n.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}F(`Package run ${t} has no package reference.`)}s(wj,"groupRunsInOrder");function kj(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(kj,"isCompleteGroup");var oA=200;function P9(e){let t=e.generatorStamp?.parts;return t===void 0&&F(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),t.map(n=>n.partKey)}s(P9,"groupPartKeys");async function C9(e,t,n){let r=await e.db.query("contract_generation_runs").withIndex("by_applicationId_and_workflowNodeId",i=>i.eq("applicationId",t).eq("workflowNodeId",n)).take(oA+1);return r.length>oA&&F(`groupChain: more than ${oA} generation runs on node ${n}`),r}s(C9,"nodeRuns");async function D9(e,t,n){let r=P9(n),i=new Set;for(let a of await C9(e,t,n.id))a.packageRunId===void 0&&F(`groupChain: run ${a._id} on the combined node "${n.id}" carries no generation group`),i.add(a.packageRunId);let o=[];for(let a of i){let l=await wj(e,a);if(!kj(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(Jh(d).map(p=>p.partKey)),u=[];for(let p of l){!r.includes(p.partKey)&&!c.has(p.partKey)&&F(`groupChain: run ${p._id} renders part "${p.partKey}", which node "${n.id}"'s pin does not declare and nobody added`);let h=await e.db.get(p.contractSnapshotId);h===null&&F(`groupChain: run ${p._id} names revision ${p.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:p,snapshot:h})}o.push({packageRunId:a,startedAt:Math.min(...l.map(p=>p._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(D9,"groupRevisionRows");async function sA(e,t,n){let r=await zh(e,{applicationId:t,nodeId:n,key:Yp});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${n}.${Yp} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(sA,"nodeGroupContracts");async function F9(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await nA(e,r._id);i!==null&&n.set(i._id,i)}return n.size>1&&F(`groupChain: generation group ${t.packageRunId} is held by ${n.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...n.values()][0]??null}s(F9,"openGroupRequest");async function L9(e,t){let n=[];for(let i of await WS(e,t._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&F(`groupChain: return ${t._id} holds missing file ${i.storageId}`),n.push({contractSnapshotId:i.contractSnapshotId,storageId:i.storageId,filename:i.filename,...o.contentType!==void 0?{mimeType:o.contentType}:{}})}let r=n[0];return{_id:t._id,_creationTime:t._creationTime,storageId:r.storageId,filename:r.filename,...r.mimeType!==void 0?{mimeType:r.mimeType}:{},round:t._id,documents:n}}s(L9,"toGroupReturn");function bj(e){async function t(i,o,a,l){let d=(await D9(i,o,e)).find(c=>c.members[0]?.snapshot._id===a);return d===void 0&&F(`${l}: ${a} is no revision of node "${e.id}"'s generation groups \u2014 corrupt arc`),d}return s(t,"revisionRowOf"),{reads:{kind:"group",async returned(i,o,a){if(a.askedAbout===void 0){if(a.onUnpinned==="notReturned")return null;F(`returned(${a.where}): an ask of the group chain is always pinned to its lead revision`)}let l=await t(i,o,a.askedAbout,`returned(${a.where})`),d=await F9(i,l);if(d===null)return null;let c=(await Uh(i,d._id)).filter(u=>u.review.status==="pending"&&u._id!==a.rejected);return c.length>1&&F(`returned(${a.where}): Vorgang ${d._id} has ${c.length} returns pending \u2014 one is checked at a time`),c[0]===void 0?null:await L9(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await sA(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(bj,"groupNodeReads");async function M9(e,t){let n=t.lifecycle.kind==="draft"?void 0:t.lifecycle.kind;return{_id:t._id,_creationTime:t._creationTime,versionNumber:t.versionNumber,...n!==void 0?{status:n}:{},origin:t.origin.kind,storageId:t.storageId,...await rA(e,t.storageId),...t.filename!==void 0?{filename:t.filename}:{}}}s(M9,"toRevision");async function q9(e,t){let n=await M9(e,t);return{_id:n._id,_creationTime:n._creationTime,storageId:n.storageId,...n.filename!==void 0?{filename:n.filename}:{},...n.mimeType!==void 0?{mimeType:n.mimeType}:{},round:n.versionNumber}}s(q9,"toReturn");function vj(e){let t=Gm(e);async function n(o,a){return await o.db.query("admission_documents").withIndex("by_applicationId_and_slotKey_and_versionNumber",l=>l.eq("applicationId",a).eq("slotKey",t)).collect()}return s(n,"contentRowsAsc"),{reads:{kind:"artifact",async returned(o,a,l){if(l.askedAbout===void 0){if(l.onUnpinned==="notReturned")return null;ue("CONFLICT",{de:"Die offene Antwort-Aufgabe ist an keine Dokumentversion gebunden, daher l\xE4sst sich die unterschriebene Fassung nicht vom versandten Dokument unterscheiden. Stellen Sie das Dokument neu aus (Zur\xFCckziehen & neu ausstellen).",en:"The open response task is not bound to a document version, so the signed copy cannot be told apart from the document that was sent. Issue the document again (withdraw and reissue)."})}let d=await n(o,a),c=d[d.length-1];if(c===void 0||c._id===l.askedAbout||c.origin.kind!=="uploaded")return null;if(l.rejected!==void 0){let u=d.find(p=>p._id===l.rejected);if(u===void 0&&F(`returned(${l.where}): the handed-back scan ${l.rejected} is no version of slot "${t}"`),c.versionNumber<=u.versionNumber)return null}return await q9(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(vj,"artifactNodeReads");function Qh(e){return e.production==="none"&&F(`documentChainKind: node "${e.id}" has production 'none' \u2014 it keeps no document`),e.production!=="resolver"?"artifact":e.generatorStamp?.parts!==void 0?"group":"contract"}s(Qh,"documentChainKind");function xj(e){switch(Qh(e)){case"contract":return Hh(e).reads;case"group":return bj(e).reads;case"artifact":return vj(e).reads}}s(xj,"documentReadsFor");var K9={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Pc(e){let t=e.responseStrategy;return typeof t=="string"&&t in Ki?Ki[t].producesResponseArtifact:!1}s(Pc,"returnsSignedCopy");function j9(e){return Pc(e)&&e.confirmContractTerms!==!1}s(j9,"asksContractTerms");function Sj(e){return j9(e)?{title:e.contractTermsQuestionText??K9,body:{de:"Die unterschriebene Fassung wird erst nach Ihrer Best\xE4tigung hochgeladen. Die Best\xE4tigung wird mit Zeitpunkt und Person festgehalten.",en:"The signed copy is uploaded only after you confirm. The confirmation is recorded with time and person."},confirmLabel:{de:"OK",en:"OK"}}:null}s(Sj,"contractTermsConfirm");function Aj(e){let t=V9(e);return t.length>0&&t.every(n=>n.status==="blocked")}s(Aj,"producerWindowHeld");function V9(e){return e.filter(t=>t.isOpen&&t.kind==="admission"&&t.templateKey!==void 0&&Dd.has(t.templateKey))}s(V9,"openProducerRows");async function B9(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:cb(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==ui||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${ui} row`),a}s(B9,"rejectedReturnOfAsk");async function Tj(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await B9(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(Tj,"returnedCopyOfAsk");var aA=new Set([...Dd,Cr,gs,To,ui,gn]),Oj={id:en,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},_j={id:Qo,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function U9(e){let t=[],n=[{slot:Oj,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:_j,production:"template",de:{a:"eine",the:"die",it:"sie"}}];for(let{slot:r,production:i,de:o}of n){let a=e.inputs?.[r.id];if(a===void 0||a.kind==="unset")continue;let l=`inputs.${r.id}`;if(e.production!==i){t.push(Te(e,l,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber ${o.a} ${r.label.de} \u2014 nur production '${i}' verwendet sie.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a ${r.label.en.toLowerCase()} \u2014 only production '${i}' uses it.`}));continue}if(a.kind==="binding"){t.push(Te(e,l,{de:`[governedDocument/referenceNotLiteral] Knoten "${e.id}": ${o.the} ${r.label.de} ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ${o.it} aus.`,en:`[governedDocument/referenceNotLiteral] Node "${e.id}": the ${r.label.en.toLowerCase()} is a fixed value of the node, not a binding \u2014 choose it from the list.`}));continue}if(a.kind!=="literal")continue;let d=hd(a.value,{type:r.type});d!==null&&t.push(Te(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return t}s(U9,"referenceInputIssues");var G9={id:qi,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},z9={id:za,type:"boolean",label:{de:"Anschreiben best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},W9={id:Jn,type:"legalEntity",label:SL,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function Y9(e,t){let n=`inputs.${Jn}`,r=e.inputs?.[Jn];if(r!==void 0&&r.kind==="binding")return[Te(e,n,{de:`[governedDocument/traegerNotLiteral] Knoten "${e.id}": der Tr\xE4ger ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ihn aus.`,en:`[governedDocument/traegerNotLiteral] Node "${e.id}": the legal entity is a fixed value of the node, not a binding \u2014 choose it from the list.`})];let i=Ga(e),o=t?.resolverPrintsTraegerAddress?.get(e.id)??new Set,a=[];for(let l of new Set([...i===null?[]:[i],...o])){let d=t?.traeger?.get(l);t?.traeger!==void 0&&d===void 0?a.push(Te(e,n,{de:`[governedDocument/unknownTraeger] Knoten "${e.id}" nennt den Tr\xE4ger "${l}", den es in diesem Mandanten nicht gibt \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[governedDocument/unknownTraeger] Node "${e.id}" names the legal entity "${l}", which does not exist in this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})):d!==void 0&&!d.hasAddress&&o.has(l)&&a.push(Te(e,n,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Cm.address}), aber "${l}" hat keine \u2014 in der Konfiguration des Mandanten nachtragen (foundation.legalEntities[].address).`,en:`[governedDocument/traegerAddressMissing] The generator template on node "${e.id}" prints the legal entity's address (${Cm.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(Y9,"traegerIssues");function Zh(e){if(e.production==="template"){let n=e.templateStamp?.fields;return Array.isArray(n)?n:[]}if(e.production!=="resolver")return[];let t=e.generatorStamp?.inputSchema?.fields;return Array.isArray(t)?t.map(n=>{let{label:r}=n;return r===void 0?{...n,label:{de:n.key,en:n.key}}:(co(r)||F(`governedDocument "${e.id}": the stamped generator parameter "${n.key}" has no { de, en } label (${JSON.stringify(r)}) \u2014 rebuild local fixtures or obtain a reviewed repair of this retained workflow stamp.`),{...n,label:r})}):[]}s(Zh,"generatorFields");function H9(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(H9,"deferredToCockpit");function J9(e){return yo(e.type)?e.type:void 0}s(J9,"resolverSlotType");function Q9(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=Ha(e);return{confirm:{title:{de:`\u201E${t.de}\u201C jetzt senden?`,en:`Send "${t.en}" now?`},body:{de:"Das Dokument wird danach f\xFCr die Familie sichtbar.",en:"The family will be able to see the document afterwards."},confirmLabel:{de:"Senden",en:"Send"}}}}s(Q9,"issueConfirmation");function Te(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Te,"issue");function Xh(e){return Km.includes(e.production)&&vs.includes(e.approval)&&Vm.includes(e.responseStrategy)}s(Xh,"hasValidModes");async function lA(e,t){let n=await Pa(e,{applicationId:t.applicationId,nodeId:t.node.id});if(n.length===0)return"pending";let r=n.filter(a=>a.isOpen&&a.kind==="admission");if(Aj(r))return"producingHeld";if(r.some(a=>a.templateKey!==void 0&&Dd.has(a.templateKey)))return"producing";if(r.some(a=>a.templateKey===To))return"awaitingCoverLetter";let i=r.find(a=>a.templateKey===Cr);if(i!==void 0)return i.status==="blocked"?"deferred":"awaitingApproval";if(r.some(a=>a.templateKey===gn))return"signatureStalled";let o=r.find(a=>a.templateKey===gs);if(o!==void 0){if(ji(t.node).issuesBy==="provider"){let l=Qh(t.node)==="group"?(await sA(e,t.applicationId,t.node.id)).map(d=>d.contractId):[await Hh(t.node).contractOrNull(e,t.applicationId)].flatMap(d=>d===null?[]:[d]);if(l.length===0&&F(`governedDocCurrentState: eSignature node "${t.node.id}" has an open ask but no contract`),await yj(e,l)==="provider")return"awaitingSignature"}return ji(t.node).producesResponseArtifact?await Tj(e,{chain:xj(t.node),applicationId:t.applicationId,ask:o,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${t.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(a=>a.templateKey===ui)?"responseInCheck":"done"}s(lA,"governedDocCurrentState");function Rj(e){return e.production!=="none"&&Qh(e)!=="artifact"}s(Rj,"keepsDocumentInContractDomain");function Z9(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!ke(r)||r.scope!=="env"||!dr(r.key))return[];let i=Jo(r.key);if(t.type!==i.type)return[Te(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" ist ${t.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${de(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${t.key}" is ${t.type}, the environment variable "${i.label.en}" (${de(r)}) supplies ${i.type}.`})];let o=new Set((t.options??[]).map(l=>l.value)),a=(i.enumOptions??[]).filter(l=>!o.has(l.value));return a.length===0?[]:[Te(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" kennt ${a.map(l=>`\u201E${l.label.de}\u201C (${l.value})`).join(", ")} nicht \u2014 die Umgebungsvariable \u201E${i.label.de}\u201C kann diese Werte liefern. Jeder Wert braucht eine Option.`,en:`[governedDocument/envNotCovered] Field "${t.key}" does not know ${a.map(l=>`"${l.label.en}" (${l.value})`).join(", ")} \u2014 the environment variable "${i.label.en}" can supply these values. Every value needs an option.`})]}s(Z9,"envCoverageIssues");function Nj(e,t){let n=[];for(let r of Zh(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...Z9(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${ke(a.address)?de(a.address):JSON.stringify(a.address)}`,en:`a binding to ${ke(a.address)?de(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:H9(e,r.key)?{de:"eine Erg\xE4nzung im Cockpit",en:"a completion in the cockpit"}:null;l!==null&&n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/processSourceConflict] "${r.label.de}" wird vom Vorgang selbst gef\xFCllt (${r.processSource}), daneben steht ${l.de}. Eine der beiden Quellen bliebe wirkungslos \u2014 entferne die Verdrahtung.`,en:`[governedDocument/processSourceConflict] "${r.label.en}" is filled by the case itself (${r.processSource}), and ${l.en} is set as well. One of the two sources would have no effect \u2014 remove the wiring.`},severity:"error"});continue}if(r.required!==!0)continue;let i=e.inputs?.[r.key];i?.kind==="binding"||i?.kind==="literal"||i?.kind==="cockpit"||r.defaultValue!==void 0||n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/unsourcedRequiredField] Pflichtfeld "${r.label.de}" des Generators ${t.de} hat keine Quelle \u2014 binde es an ein Formular-Export-Feld, setze einen festen Wert oder lass es ausdr\xFCcklich im Cockpit erg\xE4nzen.`,en:`[governedDocument/unsourcedRequiredField] Required field "${r.label.en}" of the generator ${t.en} has no source \u2014 bind it to a form export field, set a fixed value or leave it explicitly to the cockpit.`},severity:"error"})}return n}s(Nj,"fieldSourceIssues");function X9(e){let t=_r(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=XK(e.templateStamp,t).map(({path:r,reason:i})=>Te(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...Nj(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(X9,"templateIssues");function eX(e,t){return(t?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(n=>{if(n.documentAnchors===null)return[Te(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage des Generators "${n.pin}" wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the generator template "${n.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})];let r=n.signerAnchors.filter(i=>!n.documentAnchors.has(i));return r.length===0?[]:[Te(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage von "${n.pin}" tr\xE4gt keinen Anker f\xFCr ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 der Anbieter f\xE4nde f\xFCr diese Personen kein Unterschriftsfeld.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the template of "${n.pin}" has no anchor for ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 the provider would find no signature field for these people.`})]})}s(eX,"eSignatureAnchorIssues");function tX(e,t){return t===void 0||t.sendable?[]:ji(e).issuesBy!=="provider"?[]:[Te(e,"responseStrategy",{de:`[signing/noActiveProvider] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[signing/noActiveProvider] Node "${e.id}" is signed electronically, but the school cannot send: ${t.reason.en}`})]}s(tX,"eSignatureProviderIssues");var $j={key:"dokument",label:ie("Dokument","Document"),scope:"node"},Ej={producing:{label:ie("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:$j,external:at(ie("In Vorbereitung","In preparation"),"blue",ie("Ihr Dokument wird vorbereitet","Your document is being prepared"),ie("Die Schule erstellt Ihr Dokument. Sie erhalten es in K\xFCrze im Portal.","The school is preparing your document. You will receive it in the portal shortly."))},issued:{label:ie("Dokument bereitgestellt","Document issued"),tone:"blue",phase:$j,external:at(ie("Dokument bereit","Document ready"),"amber",ie("Ihr Dokument liegt bereit","Your document is ready"),ie("Bitte beantworten Sie das Dokument innerhalb der Frist. Sie finden es in Ihren Aufgaben.","Please respond to the document within the deadline. You will find it in your tasks."),ie("Dokument beantworten","Respond to the document"))}};function Ij(e,t){return!Xh(e)||e.production==="none"?null:t===To||Um(e).some(r=>r.key===t)?Gm(e):null}s(Ij,"governedDocRowSlot");var Pj={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>hs,"processHoldTemplate"),progressDefaults:Ej,progressEvents:Yt(Ej),entryProgressEvent:s(e=>e.production==="none"?"issued":"producing","entryProgressEvent"),notificationEvents:s(e=>[{id:"issued",label:{de:"Dokument bereitgestellt",en:"Document issued"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number"}]},{id:"responded",label:{de:"Antwort eingegangen",en:"Response received"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]},{id:"coverLetterAsked",label:{de:"Anschreiben zur Best\xE4tigung",en:"Cover letter to confirm"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number",required:!1}]},{id:"responseRejected",label:{de:"R\xFCcklauf zur\xFCckgegeben",en:"Returned copy handed back"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"reason",type:"string",required:!0}]}],"notificationEvents"),strictActionCoverage:!0,actions:s(e=>{if(!Xh(e))return[];let t=ji(e),n=[],r=t.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=t.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...bs(e)?["awaitingCoverLetter"]:[],...i,...t.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(n.push({id:Lb(e),kind:"internal",surface:Wa,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...e.approval==="release"?{handsTo:Cr}:{},...Q9(e)??{}}),n.push({id:$L,kind:"internal",surface:Wa,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:EL,kind:"internal",surface:Wa,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:Lm,kind:"internal",label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"documentReturned"}}:{id:t.acceptOutcomeId,kind:"advance",outcome:t.acceptOutcomeId,semantic:t.outcomeSemantics.accept,label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"userTaskResolved"}},{id:t.declineOutcomeId,kind:"advance",outcome:t.declineOutcomeId,semantic:t.outcomeSemantics.decline,label:e.responseLabels?.decline??t.defaultLabels.decline,availableIn:bs(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),bs(e)&&(n.push({id:Dm,kind:"internal",label:{de:"Angebot best\xE4tigen",en:"Confirm offer"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),n.push({id:Fm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),t.producesResponseArtifact&&n.push({id:Mm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:qm,kind:"internal",surface:Wa,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:ys,kind:"internal",surface:Wa,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:IL,currentState:lA,workItemTemplates:s(e=>{let t=e;return Xh(t)?Um(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e,r=Ij(n,t);return r===null?[]:Um(n).find(o=>o.key===t)?.recipient==="internal"?[{kind:"artifact",key:r}]:[]},"taskDocuments"),taskView:s((e,t)=>{let n=Ij(e,t);if(n!==null)return t===To?{kind:"artifact",slot:n,part:"coverLetter"}:{kind:"artifact",slot:n}},"taskView"),inputs:s(e=>[...e.production==="resolver"?[Oj,W9]:[],...e.production==="template"?[_j]:[],G9,...e.generatorStamp?.coverLetter===!0?[z9]:[],...Zh(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=J9(t);return n===void 0?[]:[{field:t,type:n}]}).map(({field:t,type:n})=>({id:t.key,type:n,label:t.label,required:t.required===!0&&t.processSource===void 0,...t.processSource===void 0?{deferrable:!0}:{},...t.defaultValue!==void 0&&(typeof t.defaultValue=="string"||typeof t.defaultValue=="number"||typeof t.defaultValue=="boolean"||t.defaultValue===null||n==="pricedItem"&&go(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:Sk,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===gs||t===To||t===Cd||t===ui||t===gn){let n=t===gs?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===ui?{de:"die Pr\xFCfung des R\xFCcklaufs entsteht erst mit dem R\xFCcklauf der Familie",en:"the check of the returned copy only arises once the family returns it"}:t===gn?{de:"die Kl\xE4rung der elektronischen Unterschrift entsteht erst, wenn sie nicht zustande kommt",en:"resolving the electronic signature only arises when it does not come about"}:{de:"die \xDCberarbeitungs-Aufgabe entsteht nur durch eine Ablehnung",en:"the revision task only arises from a rejection"};return{de:`[governedDocument/blocksTarget] 'blocks' auf "${t}" (Knoten "${e.id}") ist verboten \u2014 ${n.de}; zul\xE4ssige intrinsische Ziele: ${hs}${e.approval==="release"?`, ${Cr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${hs}${e.approval==="release"?`, ${Cr}`:""}.`}}return t===Cr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Cr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Cr}" on node "${e.id}" \u2014 with approval 'none' this template does not exist; the blocker would postpone a phantom.`}:null},"refuseBlocksTarget"),userUploadGate:s(async(e,t)=>{if(Rj(t.node))return!1;let n=await lA(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&ji(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=Sj(t.node);if(n===null||Rj(t.node))return null;let r=await lA(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Xh(e))return r.push(Te(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${Km.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${vs.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Vm.join(", ")}} (ist: ${JSON.stringify(e.responseStrategy)}). Eine Betriebsart ist eine erkl\xE4rte Entscheidung, nie aus der Verdrahtung abgeleitet.`,en:`[governedDocument/unknownMode] Node "${e.id}" declares no valid mode \u2014 required: production \u2208 {${Km.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${vs.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Vm.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=Ki[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Te(e,"production",{de:`[governedDocument/modeContract] Knoten "${e.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben und nichts zu unterschreiben: approval muss 'none' sein (ist: '${e.approval}') und responseStrategy 'confirm' (ist: '${e.responseStrategy}').`,en:`[governedDocument/modeContract] Node "${e.id}" has production 'none' \u2014 with no document there is nothing to release and nothing to sign: approval must be 'none' (is: '${e.approval}') and responseStrategy 'confirm' (is: '${e.responseStrategy}').`}));let o=e.artifacts??[];if(e.production==="none")o.length!==0&&r.push(Te(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" hat production 'none', deklariert aber ${o.length} Artefakt-Slot(s) \u2014 ein dokumentloser Best\xE4tigungs-Knoten verwaltet keinen Slot.`,en:`[governedDocument/slotContract] Node "${e.id}" has production 'none' but declares ${o.length} artifact slot(s) \u2014 a confirmation node without a document manages no slot.`}));else{o.length!==1&&r.push(Te(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" deklariert ${o.length} Artefakt-Slots \u2014 genau EINER (das verwaltete Dokument) ist erforderlich.`,en:`[governedDocument/slotContract] Node "${e.id}" declares ${o.length} artifact slots \u2014 exactly ONE (the managed document) is required.`}));for(let A of o)A.visibility!=="external"&&r.push(Te(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${A.key}" auf Knoten "${e.id}" hat visibility "${A.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${A.key}" on node "${e.id}" has visibility "${A.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(A=>A.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(A=>l.includes(A)))&&r.push(Te(e,"outcomes",{de:`[governedDocument/outcomeContract] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') muss genau ZWEI Outcomes deklarieren \u2014 das Accept-Terminal "${i.acceptOutcomeId}" und das Decline-Terminal "${i.declineOutcomeId}" (deklariert: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"keine"}). Beide sind Pflicht: der Knoten besitzt die Antwort, nicht nur die Freigabe.`,en:`[governedDocument/outcomeContract] Node "${e.id}" (responseStrategy '${e.responseStrategy}') must declare exactly TWO outcomes \u2014 the accept terminal "${i.acceptOutcomeId}" and the decline terminal "${i.declineOutcomeId}" (declared: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(A=>{let T=c?.[A];return T===null||typeof T!="object"||!Object.values(T??{}).some(I=>typeof I=="string"&&I.length>0)},"missingTitle"),p=[];e.production!=="none"&&p.push("prepare","revise"),e.approval==="release"&&p.push("approve"),i.checksReturn&&p.push("check");let h=p.filter(u);h.length>0&&r.push(Te(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${h.join(", ")} \u2014 der Knotentyp ist dokument-agnostisch, die Betitelung ist Pflicht-Konfiguration seiner Betriebsart.`,en:`[governedDocument/missingTitles] Node "${e.id}" is missing the task titles ${h.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let y=e.assign??{};if(e.production!=="none"&&y.prepareDocument===void 0&&r.push(Te(e,"assign.prepareDocument",{de:`[governedDocument/productionAssign] Knoten "${e.id}" (production '${e.production}') verdrahtet kein Produzenten-Team (assign.prepareDocument) \u2014 ohne Producer-Aufgabe g\xE4be es die Submit-Aktion ohne freischaltendes Work-Item.`,en:`[governedDocument/productionAssign] Node "${e.id}" (production '${e.production}') wires no producer team (assign.prepareDocument) \u2014 without a producer task there would be the submit action without an enabling work item.`})),e.approval==="none"&&(y.releaseApproval!==void 0&&r.push(Te(e,"assign.releaseApproval",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', verdrahtet aber assign.releaseApproval \u2014 tote Verdrahtung darf nicht als konfiguriert durchgehen (Betriebsart explizit \xE4ndern statt Gruppen zuweisen).`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but wires assign.releaseApproval \u2014 dead wiring must not pass as configured (change the mode explicitly instead of assigning groups).`})),c?.approve!==void 0&&r.push(Te(e,"titles.approve",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', deklariert aber titles.approve \u2014 es gibt keine Freigabe-Aufgabe, die diesen Titel tr\xFCge.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but declares titles.approve \u2014 there is no release task that would carry this title.`}))),i.checksReturn)y.responseCheck===void 0&&r.push(Te(e,"assign.responseCheck",{de:`[governedDocument/checkAssign] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') verdrahtet kein Team f\xFCr die Pr\xFCfung des R\xFCcklaufs (assign.responseCheck) \u2014 ohne Team l\xE4ge jeder R\xFCcklauf bei niemandem.`,en:`[governedDocument/checkAssign] Node "${e.id}" (responseStrategy '${e.responseStrategy}') wires no team for checking the returned copy (assign.responseCheck) \u2014 without a team every returned copy would lie with nobody.`})),e.production!=="resolver"&&i.issuesBy==="provider"?r.push(Te(e,"responseStrategy",{de:`[governedDocument/eSignatureNeedsResolver] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben (eSignature), erzeugt das Dokument aber mit production '${e.production}' \u2014 der Anbieter bekommt eine eingefrorene Vertragsrevision mit Unterschriftsankern und deklarierten Unterzeichnern, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/eSignatureNeedsResolver] Node "${e.id}" is signed electronically (eSignature) but produces the document with production '${e.production}' \u2014 the provider gets a frozen contract revision with signature anchors and declared signatories, and that only exists with production 'resolver'.`})):e.production!=="resolver"&&r.push(Te(e,"responseStrategy",{de:`[governedDocument/checkNeedsContract] Knoten "${e.id}" pr\xFCft den R\xFCcklauf (signedUploadChecked), erzeugt das Dokument aber mit production '${e.production}' \u2014 die Pr\xFCfung hakt die unterzeichnenden Personen einer eingefrorenen Vertragsrevision ab, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/checkNeedsContract] Node "${e.id}" checks the returned copy (signedUploadChecked) but produces the document with production '${e.production}' \u2014 the check ticks off the signatories of a frozen contract revision, and that only exists with production 'resolver'.`}));else{e.production==="resolver"&&r.push(Te(e,"responseStrategy",{de:`[governedDocument/contractNeedsCheckedReturn] Knoten "${e.id}" erzeugt einen Vertrag (production 'resolver'), beantwortet ihn aber mit '${e.responseStrategy}' \u2014 ein Vertrag gilt erst als unterschrieben, wenn die Schule den R\xFCcklauf gepr\xFCft hat oder ein Anbieter die Unterschrift belegt: responseStrategy muss 'signedUploadChecked' oder 'eSignature' sein (mit assign.responseCheck und titles.check).`,en:`[governedDocument/contractNeedsCheckedReturn] Node "${e.id}" produces a contract (production 'resolver') but answers it with '${e.responseStrategy}' \u2014 a contract only counts as signed once the school has checked the returned copy or a provider proves the signature: responseStrategy must be 'signedUploadChecked' or 'eSignature' (with assign.responseCheck and titles.check).`}));for(let[A,T]of[["assign.responseCheck",y.responseCheck!==void 0],["titles.check",c?.check!==void 0]])T&&r.push(Te(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 eine Pr\xFCfung des R\xFCcklaufs gibt es nur mit responseStrategy 'signedUploadChecked' oder 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"?y.signingRecovery===void 0&&r.push(Te(e,"assign.signingRecovery",{de:`[governedDocument/recoveryAssign] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, verdrahtet aber kein Team f\xFCr die Kl\xE4rung einer Unterschrift, die nicht zustande kommt (assign.signingRecovery) \u2014 \u201EErneut senden" und \u201EAuf Papier umstellen" l\xE4gen bei niemandem.`,en:`[governedDocument/recoveryAssign] Node "${e.id}" is signed electronically but wires no team for resolving a signature that does not come about (assign.signingRecovery) \u2014 "Send again" and "Switch to paper" would lie with nobody.`})):y.signingRecovery!==void 0&&r.push(Te(e,"assign.signingRecovery",{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert assign.signingRecovery \u2014 eine Kl\xE4rung der elektronischen Unterschrift gibt es nur mit responseStrategy 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares assign.signingRecovery \u2014 resolving an electronic signature only exists with responseStrategy 'eSignature'.`})),i.issuesBy==="provider"&&r.push(...eX(e,n),...tX(e,n?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Te(e,"confirmBeforeIssue",{de:`[governedDocument/confirmBeforeIssue] Knoten "${e.id}" setzt confirmBeforeIssue auf ${JSON.stringify(e.confirmBeforeIssue)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmBeforeIssue] Node "${e.id}" sets confirmBeforeIssue to ${JSON.stringify(e.confirmBeforeIssue)} \u2014 only true or false is allowed.`})):e.confirmBeforeIssue===!0&&e.approval==="release"&&r.push(Te(e,"confirmBeforeIssue",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'release', deklariert aber confirmBeforeIssue \u2014 \u201EFreigabe anfordern" schickt noch nichts an die Familie, und die Freigabe selbst ist die bewusste Pr\xFCfung vor dem Versand. Die R\xFCckfrage gibt es nur mit approval 'none'.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'release' but declares confirmBeforeIssue \u2014 "Request release" sends nothing to the family yet, and the release itself is the deliberate check before sending. The confirmation prompt only exists with approval 'none'.`})),e.confirmContractTerms!==void 0&&typeof e.confirmContractTerms!="boolean"&&r.push(Te(e,"confirmContractTerms",{de:`[governedDocument/confirmContractTerms] Knoten "${e.id}" setzt confirmContractTerms auf ${JSON.stringify(e.confirmContractTerms)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmContractTerms] Node "${e.id}" sets confirmContractTerms to ${JSON.stringify(e.confirmContractTerms)} \u2014 only true or false is allowed.`})),Pc(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Te(e,"contractTermsQuestionText",{de:`[governedDocument/deadWiring] Knoten "${e.id}" schaltet die Best\xE4tigung der Vertragsbedingungen ab (confirmContractTerms: false), formuliert aber die Frage um \u2014 ohne Best\xE4tigung wird sie nie gestellt.`,en:`[governedDocument/deadWiring] Node "${e.id}" switches off the confirmation of the contract terms (confirmContractTerms: false) but rewords the question \u2014 without the confirmation it is never asked.`}));else for(let[A,T]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])T&&r.push(Te(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 die Best\xE4tigung der Vertragsbedingungen geh\xF6rt zum Hochladen der unterschriebenen Fassung, das es nur mit responseStrategy 'signedUpload' oder 'signedUploadChecked' gibt.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 the confirmation of the contract terms belongs to uploading the signed copy, which only exists with responseStrategy 'signedUpload' or 'signedUploadChecked'.`}));if(e.production==="none")for(let[A,T]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",y.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])T&&r.push(Te(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${A} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${A} \u2014 without a production phase there is nothing to carry it.`}));for(let A of e.tasks??[])aA.has(A.key)&&r.push(Te(e,`tasks.${A.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${A.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...aA].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${A.key}" on node "${e.id}" collides with an intrinsic template (${[...aA].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...Y9(e,n)):e.inputs?.[Jn]!==void 0&&r.push(Te(e,`inputs.${Jn}`,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber einen Tr\xE4ger \u2014 nur ein erzeugter Vertrag hat eine Vertragspartei der Schule.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a legal entity \u2014 only a generated contract has a contracting party on the school's side.`})),r.push(...U9(e)),e.production==="resolver"){let A=Ti(e);if(A!==null){let T=mN(A);for(let I of Zh(e)){if(!yo(I.type)){r.push(Te(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/unknownFieldType] Generator "${T}" typisiert das Feld "${I.key}" als "${String(I.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${ba.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${T}" types the field "${I.key}" as "${String(I.type)}" \u2014 that is not part of the platform's value vocabulary (${ba.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(I.type==="personList"){r.push(Te(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${T}" deklariert das Feld "${I.key}" als personList \u2014 daf\xFCr gibt es keine Platzhalter-Heimat im Dokument und keine Eingabe. Eine Liste von Personen geh\xF6rt als Rolle mit Kapazit\xE4t deklariert oder als berechneter Textwert.`,en:`[governedDocument/partyListUnsupported] Generator "${T}" declares the field "${I.key}" as personList \u2014 there is no placeholder home for it in the document and no input. A list of people belongs declared as a role with capacity or as a computed text value.`}));continue}I.type==="party"&&(I.key.endsWith("PartyId")||r.push(Te(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${I.key}" endet nicht auf "PartyId" \u2014 aus diesem Suffix wird der Platzhalter-Pr\xE4fix im Dokument abgeleitet (emergencyContactPartyId \u2192 emergency_contact).`,en:`[governedDocument/partyFieldKey] Party field "${I.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...Nj(e,{de:`"${T}"`,en:`"${T}"`}))}}else e.generatorStamp!==void 0&&r.push(Te(e,"generatorStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber den Stempel eines Generators \u2014 ohne maschinelle Produktion l\xE4uft keiner.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a generator stamp \u2014 without machine production none runs.`}));e.production==="template"?r.push(...X9(e)):e.templateStamp!==void 0&&r.push(Te(e,"templateStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber die Parameter einer Vorlage \u2014 ohne Vorlagen-Produktion wird sie nie gef\xFCllt.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a template's parameters \u2014 without template production it is never filled.`}));let b=e.inputs?.[za];b!==void 0&&b.kind!=="unset"&&!(b.kind==="literal"&&typeof b.value=="boolean")&&r.push(Te(e,`inputs.${za}`,{de:`[governedDocument/coverLetterInput] Knoten "${e.id}": Die Best\xE4tigung des Anschreibens ist ein fester Wert ja oder nein.`,en:`[governedDocument/coverLetterInput] Node "${e.id}": the cover letter's confirmation is a fixed yes or no.`})),bs(e)&&(n!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Te(e,`inputs.${za}`,{de:`[governedDocument/coverLetterNotDeclared] Knoten "${e.id}" l\xE4sst ein Anschreiben best\xE4tigen, sein Generator erzeugt aber keines.`,en:`[governedDocument/coverLetterNotDeclared] Node "${e.id}" asks to confirm a cover letter, but its generator produces none.`})),e.approval!=="release"&&r.push(Te(e,"approval",{de:`[governedDocument/coverLetterNeedsRelease] Knoten "${e.id}": Ein Anschreiben mit Best\xE4tigung braucht die Freigabe, denn Vertrag und Anschreiben werden zusammen freigegeben.`,en:`[governedDocument/coverLetterNeedsRelease] Node "${e.id}": a cover letter with confirmation needs the release, because contract and letter are released together.`})),ji(e).producesResponseArtifact||r.push(Te(e,"responseStrategy",{de:`[governedDocument/coverLetterNeedsSigning] Knoten "${e.id}": Ein Anschreiben steht vor einer Unterschrift; dieser Knoten l\xE4sst nicht unterschreiben.`,en:`[governedDocument/coverLetterNeedsSigning] Node "${e.id}": a cover letter comes before a signature; this node takes none.`})));let k=e.inputs?.[qi],v=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return v!==void 0&&!Ld(v)&&r.push(Te(e,`inputs.${qi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(v)} \u2014 erlaubt ist eine ganze Zahl von ${ws} bis ${ks} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(v)} \u2014 a whole number from ${ws} to ${ks} days is allowed.`})),v===void 0&&Zh(e).some(A=>A.processSource==="responseDueInDays")&&r.push(Te(e,`inputs.${qi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" druckt die Antwortfrist (processSource 'responseDueInDays'), setzt aber kein responseDueInDays \u2014 das Dokument nennte eine Frist, die es nicht gibt.`,en:`[governedDocument/dueInDays] Node "${e.id}" prints the response deadline (processSource 'responseDueInDays') but sets no responseDueInDays \u2014 the document would name a deadline that does not exist.`})),r},"validate")};var Cj={addPupil:{method:"POST",path:"/api/v1/admissions/AddPrPupilBasic/{schoolid}",kind:"create",body:"PrPupilBasicCreate",required:["forename","surname","genderId"],maxLength:{titleId:4,forename:50,surname:50,middleName:50,preferredForename:50,preferredSurname:50,genderId:4,firstLanguage:4}},addAdmissionDetails:{method:"POST",path:"/api/v1/admissions/AddAdmissionDetails/{schoolid}/{pupilid}",kind:"create",body:"AddPrPupilAdmissionDetails",required:[],maxLength:{boarderStatusId:4,ageAdjust:4,entryYear:4,entryTerm:4,entryYearGroup:4,currentSchoolId:20,enquirySource:4,currentAdmissionStageId:25}},addNationality:{method:"POST",path:"/api/v1/admissions/AddNationlityInfo/{schoolid}/{pupilid}",kind:"create",body:"NationalityInfoCreate",required:["nationalityId"],maxLength:{nationalityId:4,countryOfBirth:4}},addVisa:{method:"POST",path:"/api/v1/admissions/AddVisaInfo/{schoolid}/{pupilid}",kind:"create",body:"CreateVisaInfo",required:[],maxLength:{placeOfBirth:50,passportCountry:4,passportNumber:50,residenceVisaNumber:50,healthCardNumber:50}},addMedical:{method:"POST",path:"/api/v1/admissions/AddMedicalInfo/{schoolid}/{pupilid}",kind:"create",body:"MedicalInfoCreate",required:[],maxLength:{}},addContact:{method:"POST",path:"/api/v1/admissions/AddContactBasicInfo/{schoolid}/{pupilid}",kind:"create",body:"AddContactBasicInfo",required:["titleId","firstName","lastName","genderId"],maxLength:{relationshipId:4,titleId:4,firstName:50,middleName:50,lastName:50,contactName:200,greeting:200,languageId:4,secondLanguageId:4,genderId:4,professionId:4,companyName:50,jobTitle:50}},linkExistingContact:{method:"POST",path:"/api/v1/admissions/LinkExistingContact/{schoolid}/{pupilid}/{contactid}",kind:"create",body:"LinkContact",required:["relationshipId"],maxLength:{relationshipId:4}},addContactAddress:{method:"POST",path:"/api/v1/admissions/AddContactAddressNew/{schoolid}/{contactid}/{addressformatid}",kind:"create",body:"AddAddressVM",required:["countryId"],maxLength:{addressTypeId:4,countryId:4,addressLine1:100,addressLine2:100,addressLine3:100,addressLine4:100,addressLine5:100,addressLine6:100,lookup1:4,lookup2:4,lookup3:4,lookup4:4,lookup5:4}},addContactEmail:{method:"POST",path:"/api/v1/admissions/AddContactEmail/{schoolid}/{contactid}",kind:"create",body:"AddEmailAddress",required:["emailTypeId","email"],maxLength:{emailTypeId:4,email:254}},addContactTelephone:{method:"POST",path:"/api/v1/admissions/AddContactTelephone/{schoolid}/{contactid}",kind:"create",body:"AddTelephoneNumber",required:["typeId","number"],maxLength:{typeId:4}},linkAddressToPupil:{method:"PUT",path:"/api/v1/admissions/LinkAddressToPupil/{schoolId}/{pupilId}/{addressId}",kind:"update",required:[],maxLength:{}},updatePupilAif:{method:"POST",path:"/api/v1/additionalinformation/UpdatePupilAIF/{schoolid}/{pupilid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},updateContactAif:{method:"POST",path:"/api/v1/additionalinformation/UpdateContactAIF/{schoolid}/{contactid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},listPupils:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfo/{schoolid}",kind:"read",required:[],maxLength:{}},getPupil:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfoById/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},listContactsOfPupil:{method:"GET",path:"/api/v1/admissions/GetContactBasicInfoByPupilId/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},getContact:{method:"GET",path:"/api/v1/admissions/GetContactByContactId/{schoolid}/{contactid}",kind:"read",required:[],maxLength:{}},readPupilAifFields:{method:"GET",path:"/api/v1/additionalinformation/ReadPupilAIFFields/{schoolid}",kind:"read",required:[],maxLength:{}},readContactAifFields:{method:"GET",path:"/api/v1/additionalinformation/ReadContactAIFFields/{schoolid}",kind:"read",required:[],maxLength:{}}};function tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(tr,"isRecord");var dA=["field","join","literal","address","payment","contract"],nX=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),rX=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function br(e){return typeof e=="string"&&e.trim().length>0}s(br,"nonEmptyString");function eg(e,t,n,r,i="value"){if(!tr(e)||!tr(e.from)){r.push({path:t,code:"mappingShape",message:{de:`${t}: eine Zuordnung braucht \`from\`.`,en:`${t}: a mapping needs \`from\`.`}});return}let o=e.from,a=dA.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${dA.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${dA.join(" | ")}).`}});return}let[l]=a;l==="field"&&!br(o.field)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.field\` ist leer.`,en:`${t}: \`from.field\` is empty.`}}),l==="join"&&!(Array.isArray(o.join)&&o.join.length>=2&&o.join.every(br))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.join\` nennt mindestens zwei Formularfelder.`,en:`${t}: \`from.join\` names at least two form fields.`}}),e.whenEmpty!==void 0&&(i==="condition"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nicht f\xFCr eine Bedingung (\`unless\`, \`linkAddressToPupilIf\`).`,en:`${t}: \`whenEmpty\` does not apply to a condition (\`unless\`, \`linkAddressToPupilIf\`).`}}):l!=="field"&&l!=="join"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nur f\xFCr eine Formularantwort (\`field\`, \`join\`).`,en:`${t}: \`whenEmpty\` applies only to a form answer (\`field\`, \`join\`).`}}):typeof e.whenEmpty=="boolean"||Number.isFinite(e.whenEmpty)||br(e.whenEmpty)||r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` ist ein Engage-Wert (Text, Zahl oder ja/nein).`,en:`${t}: \`whenEmpty\` is an Engage value (text, number or yes/no).`}})),l==="address"&&!(ke(o.address)&&o.address.scope==="env"&&dr(o.address.key))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.address\` ist eine Umgebungsvariable (\`{ scope: 'env', key: 'stage.key' }\`).`,en:`${t}: \`from.address\` is an environment value (\`{ scope: 'env', key: 'stage.key' }\`).`}}),l==="payment"&&o.payment!=="amount"&&o.payment!=="settledAt"&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.payment\` ist amount oder settledAt.`,en:`${t}: \`from.payment\` is amount or settledAt.`}}),l==="contract"&&!["startDate","signedAt","createdAt"].includes(String(o.contract))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.contract\` ist startDate, signedAt oder createdAt.`,en:`${t}: \`from.contract\` is startDate, signedAt or createdAt.`}}),l==="literal"&&!["string","number","boolean"].includes(typeof o.literal)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.literal\` ist Text, Zahl oder ja/nein.`,en:`${t}: \`from.literal\` is text, a number or yes/no.`}}),e.format!==void 0&&!nX.has(String(e.format))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekanntes Format \u201E${String(e.format)}".`,en:`${t}: unknown format "${String(e.format)}".`}}),e.lookup!==void 0&&!(br(e.lookup)&&tr(n[e.lookup]))&&r.push({path:t,code:"unknownLookup",message:{de:`${t}: die Lookup-Tabelle \u201E${String(e.lookup)}" fehlt in \`lookups\`.`,en:`${t}: the lookup table "${String(e.lookup)}" is missing from \`lookups\`.`}});let d=e.pick;d!==void 0&&(d==="firstWord"||d==="restWords"||d==="year"||tr(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||tr(d)&&rX.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(eg,"checkMapping");function Eo(e,t,n,r,i){if(!tr(e)){i.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet ein Objekt Feld \u2192 Zuordnung.`,en:`${t}: expects an object field \u2192 mapping.`}});return}let o=Cj[n];for(let a of o.required)a in e||i.push({path:`${t}.${a}`,code:"missingRequired",message:{de:`${t}: Engage verlangt \u201E${a}" (${o.body}) \u2014 es fehlt eine Zuordnung.`,en:`${t}: Engage requires "${a}" (${o.body}) \u2014 a mapping is missing.`}});for(let[a,l]of Object.entries(e))eg(l,`${t}.${a}`,r,i)}s(Eo,"checkBody");function Dj(e,t,n,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet eine Liste.`,en:`${t}: expects a list.`}});return}let i=new Set;e.forEach((o,a)=>{let l=`${t}[${a}]`;if(!tr(o)||!br(o.fieldId)){r.push({path:l,code:"aifShape",message:{de:`${l}: \`fieldId\` fehlt.`,en:`${l}: \`fieldId\` is missing.`}});return}i.has(o.fieldId)&&r.push({path:l,code:"aifDuplicate",message:{de:`${l}: \u201E${o.fieldId}" doppelt.`,en:`${l}: "${o.fieldId}" appears twice.`}}),i.add(o.fieldId),eg(o.value,`${l}.value`,n,r),o.unless!==void 0&&eg(o.unless,`${l}.unless`,n,r,"condition")})}s(Dj,"checkAif");function cA(e){let t=[];if(!tr(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=tr(e.lookups)?e.lookups:{};tr(e.lookups)||t.push({path:"engage.lookups",code:"bodyShape",message:{de:"`engage.lookups` fehlt (Tabellen Name \u2192 Plexus-Wert \u2192 Engage-Id).",en:"`engage.lookups` is missing (tables name \u2192 Plexus value \u2192 Engage id)."}});for(let[r,i]of Object.entries(n))(!tr(i)||!Object.values(i).every(br))&&t.push({path:`engage.lookups.${r}`,code:"lookupShape",message:{de:`Lookup \u201E${r}": jede Engage-Id ist ein nicht leerer Text.`,en:`Lookup "${r}": every Engage id is a non-empty text.`}});if(br(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Eo(e.pupil,"engage.pupil","addPupil",n,t),Eo(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&Eo(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&Eo(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&Eo(e.medical,"engage.medical","addMedical",n,t),Dj(e.pupilAif,"engage.pupilAif",n,t),!Array.isArray(e.contacts))t.push({path:"engage.contacts",code:"bodyShape",message:{de:"`engage.contacts` fehlt (Liste der Kontakte).",en:"`engage.contacts` is missing (list of contacts)."}});else{let r=new Set;e.contacts.forEach((i,o)=>{let a=`engage.contacts[${o}]`;if(!tr(i)||!br(i.key)||!br(i.presentIf)){t.push({path:a,code:"contactShape",message:{de:`${a}: \`key\` und \`presentIf\` fehlen.`,en:`${a}: \`key\` and \`presentIf\` are missing.`}});return}r.has(i.key)&&t.push({path:a,code:"contactDuplicate",message:{de:`${a}: Kontakt \u201E${i.key}" doppelt.`,en:`${a}: contact "${i.key}" appears twice.`}}),r.add(i.key),Eo(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&Eo(i.address,`${a}.address`,"addContactAddress",n,t);for(let[l,d]of[["emails","addContactEmail"],["telephones","addContactTelephone"]]){let c=i[l];if(c!==void 0){if(!Array.isArray(c)){t.push({path:`${a}.${l}`,code:"bodyShape",message:{de:`${a}.${l}: erwartet eine Liste.`,en:`${a}.${l}: expects a list.`}});continue}c.forEach((u,p)=>Eo(u,`${a}.${l}[${p}]`,d,n,t))}}Dj(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&eg(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!tr(r)||!br(r.repeated)||!br(r.field)||!br(r.equals))&&t.push({path:"engage.siblingsAttending",code:"bodyShape",message:{de:"`engage.siblingsAttending` braucht repeated, field und equals.",en:"`engage.siblingsAttending` needs repeated, field and equals."}})}return t}s(cA,"engagePushConfigIssues");function*uA(e){let t=[e.pupil,e.admission,e.nationality,e.visa,e.medical];for(let n of t)for(let r of Object.values(n??{}))yield{mapping:r};for(let n of e.pupilAif??[])yield{mapping:n.value},n.unless!==void 0&&(yield{mapping:n.unless});for(let n of e.contacts){let r=[n.basic,n.address,...n.emails??[],...n.telephones??[]];for(let i of r)for(let o of Object.values(i??{}))yield{mapping:o,contactKey:n.key};for(let i of n.aif??[])yield{mapping:i.value,contactKey:n.key},i.unless!==void 0&&(yield{mapping:i.unless,contactKey:n.key});n.linkAddressToPupilIf!==void 0&&(yield{mapping:n.linkAddressToPupilIf,contactKey:n.key})}}s(uA,"mappingsOf");function Fj(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of uA(e))for(let i of iX(n.from))t.add(oX(i,r));return[...t]}s(Fj,"configFieldKeys");function iX(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(iX,"formFieldsOf");function oX(e,t){return e.startsWith(".")?(t===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(oX,"resolveFieldKey");function Lj(e,t){for(let{mapping:n}of uA(e))if(t in n.from)return!0;return!1}s(Lj,"configReadsSource");function Mj(e){let t=new Set;for(let{mapping:n}of uA(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(Mj,"configEnvLeaves");var qj="done",Kj=["sandbox","production"];var tg="engagePush",vVe=660*1e3;function Io(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(Io,"issue");function fA(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(fA,"literal");function jj(e){return cA(e.engage).length===0?e.engage:null}s(jj,"validConfig");function sX(e,t){let n=new Map(e.nodes.map(a=>[a.id,a])),r=e.nodes.filter(a=>a.type==="eventTrigger"),i=new Set,o=r.map(a=>a.id);for(;o.length>0;){let a=o.pop();if(a===t||i.has(a))continue;i.add(a);let l=n.get(a);if(l!==void 0){if(l.type==="end"){let d=l.inputs?.applicationOutcome;if(d?.kind==="literal"&&d.value==="approved")return!0;continue}for(let d of Object.values(l.next??{})){let c=d?.to;typeof c=="string"&&o.push(c)}}}return!1}s(sX,"bypassingPath");var Vj={role:"system-action",effect:"side-effect",outcomes:[{id:qj,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=jj(e);return t===null?[]:Mj(t)},"envReads"),inputs:s(()=>[{id:"target",label:{de:"Ziel-Engage",en:"Target Engage"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"sandbox",label:{de:"Sandbox",en:"Sandbox"}},{value:"production",label:{de:"Produktion",en:"Production"}}]},{id:"contractFields",label:{de:"Vertragsfelder F01\u2013F25",en:"Contract fields F01\u2013F25"},type:"enum",required:!1,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"off",label:{de:"Nicht \xFCbertragen (Bedeutung offen)",en:"Do not transfer (meaning open)"}},{value:"on",label:{de:"\xDCbertragen",en:"Transfer"}}]}],"inputs"),validate:s((e,t,n)=>{let r=e.label?.de??e.id,i=e.label?.en||e.id,o=[],a=fA(e,"target");Kj.includes(a)||o.push(Io(e,"inputs.target",{de:`[engagePush/invalidTarget] \u201E${r}": das Ziel ist sandbox oder production.`,en:`[engagePush/invalidTarget] "${i}": the target is sandbox or production.`}));let l=fA(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(Io(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`})),e.assign?.[tg]===void 0&&o.push(Io(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${tg}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${tg}\` names the team.`}));for(let b of cA(e.engage))o.push(Io(e,b.path,{de:`[engagePush/config] \u201E${r}": ${b.message.de}`,en:`[engagePush/config] "${i}": ${b.message.en}`}));let d=t.nodes.filter(b=>b.id!==e.id&&b.type==="engagePush"&&fA(b,"target")===a);d.length>0&&o.push(Io(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${d.map(b=>`"${b.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${d.map(b=>`"${b.id}"`).join(", ")} already transfers to the same target.`})),sX(t,e.id)&&o.push(Io(e,"next",{de:`[engagePush/bypassed] \u201E${r}": ein Weg erreicht ein \u201Eangenommen"-Ende, ohne durch die Engage-\xDCbertragung zu laufen \u2014 was dort angenommen wird, k\xE4me nie in Engage an.`,en:`[engagePush/bypassed] "${i}": a path reaches an "accepted" end without passing through the Engage transfer \u2014 what is accepted there would never reach Engage.`}));let c=jj(e),u=e;for(let[b,k,v,A]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])c===null||!Lj(c,b)||u[k]!==void 0||o.push(Io(e,k,{de:Sa("address/missing",{where:`\u201E${r}\u201C \u203A ${v}`},"de"),en:Sa("address/missing",{where:`"${i}" \u203A ${A}`},"en")}));let p=u.form,h=ke(p)&&p.scope==="node"?p.owner:void 0,y=h===void 0?void 0:n?.readinessFormFieldsByFormNode?.get(h);if(c!==null&&y!==void 0){let b=new Set(y.keys()),k=Fj(c).filter(v=>!b.has(v)&&!/\[\d+\]\./.test(v));if(k.length>0){let v=t.nodes.find(A=>A.id===h);o.push(Io(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${v?.label?.de??h}" nicht \u2014 sie werden nicht \xFCbertragen: ${k.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${v?.label?.en||h}" does not know these fields \u2014 they are not transferred: ${k.join(", ")}.`},"warning"))}}return o},"validate")};var Oo={join:gK,end:bC,roleAssign:wK,eventTrigger:kK,waitlist:DK,completenessCheck:VK,form:RK,setFlag:$K,if:EK,decision:Ns,review:UK,collectPayment:JK,governedDocument:Pj,countersign:VL,engagePush:Vj};JN(Oo);function Bj(e,t){let n=e;if(n==null||!Array.isArray(n.nodes))throw new g(`offer plan: the ${t} carries no workflow graph with nodes`);return e}s(Bj,"graphOf");function Uj(e){let t=new Map;for(let n of e.nodes)for(let r of oi(e,n))t.set(de(r.address),r.nodeId);return t}s(Uj,"producedOf");function Gj(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(rs(e,n).map(r=>de(r.address))));return t}s(Gj,"readsOf");function zj(e,t){let n=Bj(e,"bundle"),r=Bj(t.graph,"live head"),i=Uj(n),o=Uj(r),a={added:[],removed:[],moved:[]};for(let[u,p]of i){let h=o.get(u);h===void 0?a.added.push({address:u,nodeId:p}):h!==p&&a.moved.push({address:u,from:h,to:p})}for(let[u,p]of o)i.has(u)||a.removed.push({address:u,nodeId:p});let l=Gj(n),d=Gj(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let p=l.get(u)??new Set,h=d.get(u)??new Set,y=[...p].filter(k=>!h.has(k)),b=[...h].filter(k=>!p.has(k));(y.length>0||b.length>0)&&c.push({nodeId:u,added:y,removed:b})}return{headRevision:t.revision,pinnedApplications:t.pinnedApplications,produced:a,reads:c}}s(zj,"planAddresses");function Wj(e){let t=[...e.produced.moved.map(i=>({icon:"~",target:`address:${i.address}`,status:`Knoten ${i.from} \u2192 ${i.to}`})),...e.produced.added.map(i=>({icon:"+",target:`address:${i.address}`,status:`neu (${i.nodeId})`})),...e.produced.removed.map(i=>({icon:"-",target:`address:${i.address}`,status:`entfernt (${i.nodeId})`})),...e.reads.map(i=>({icon:"~",target:`reads:${i.nodeId}`,status:[i.added.length>0?`+${i.added.join(", ")}`:"",i.removed.length>0?`\u2212${i.removed.join(", ")}`:""].filter(Boolean).join(" ")}))];if(t.length===0)return[];let{real:n,test:r}=e.pinnedApplications;return t.push({icon:"!",target:"pinned",status:`${n+r} Anmeldungen (${n} echt, ${r} Test) auf Fassung ${e.headRevision} bleiben auf ihrer Version \u2014 Umpinnen nur per Migration mit Abbildung`}),t}s(Wj,"addressPlanRows");function Yj(e,t){return t==null?!0:Ce(e)!==Ce(t)}s(Yj,"changed");async function Hj(e,t,n){if(t.index.module!==TS.name)throw new g(`offer: unknown module "${t.index.module}"`);return S0(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return TS.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(Hj,"applyOffer");async function Jj(e,t,n,r="published"){let i=await e.query(S.setup.offerBundle.exportOfferBundle,{client:t,offerKey:n,generation:r});return{bundle:i.bundle,generation:i.generation,revision:i.revision}}s(Jj,"exportOffer");async function pA(e,t){let{index:n}=t,i=(await e.query(S.workflow.listManifests,{client:n.tenant})).find(y=>y.offerKey===n.slugs.manifest),o="create";i&&(o="same");let a={};for(let[y,b]of Object.entries(t.smartforms??{})){let k=i?await e.query(S.forms.getSmartFormBySlug,{client:n.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=k?.def?Yj(b,{label:k.def.label,...k.def.definition})?"change":"same":"create"}let l="absent",d=null;if(t.workflow!==void 0){if(l="create",i?.workflowDefinitionId){let y=await e.query(S.workflow.getWorkflowDef,{workflowDefinitionId:i.workflowDefinitionId}),b=y?.publishedVersion??y?.draftVersion;l=Yj(b&&{graph:ua(t.workflow.graph),progressLayout:t.workflow.progressLayout??b.progressLayout,progressWiring:t.workflow.progressWiring??b.progressWiring},b&&{graph:ua(b.graph),progressLayout:b.progressLayout,progressWiring:b.progressWiring})?"change":"same"}if(i){let y=await e.query(S.workflow.getOfferHeadPins,{client:n.tenant,offerKey:n.slugs.manifest});y!==null&&(d=zj(t.workflow.graph,y))}}let c=n.program?.stages,u=c===void 0?[]:i?await AS(e,n.tenant,n.slugs.manifest,c):Sp(null,[],c),p=await Kh(e,n.tenant,i?n.slugs.manifest:null,n),h=i?await e.query(S.workflow.getOfferPublishState,{client:n.tenant,offerKey:n.slugs.manifest}):null;return{manifest:o,smartforms:a,workflow:l,addresses:d,stages:u,capacities:p,publishPending:h?.draftDiffersFromExternal??null,draftRevision:h?.draftRevision??null,externalHeadRevision:h?.externalHeadRevision??null}}s(pA,"diffOffer");function ng(e){if(e.type==="governedDocument"){let t=e.production;return t==="resolver"?"resolver":t==="template"?"template":t==="upload"||t==="none"?"manual":"unauthored"}return null}s(ng,"contractProductionModeOf");function Qj(e){return ng(e)==="resolver"}s(Qj,"isResolverCarrierNode");function rg(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=Ti(n);return!Qj(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(rg,"authoredPins");var Zj={type:"address",dataType:"composite"};var Xj={type:"boolean",dataType:"boolean"};var eV={type:"consent",dataType:"boolean"};var tV={type:"date",dataType:"date"};var nV={type:"docRef",dataType:"file"};var rV={type:"email",dataType:"text"};var iV={type:"string",dataType:"text"};var oV={type:"tel",dataType:"text"};var ig={address:Zj.dataType,boolean:Xj.dataType,consent:eV.dataType,date:tV.dataType,docRef:nV.dataType,email:rV.dataType,enum:rC.dataType,string:iV.dataType,tel:oV.dataType};function mA(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(mA,"shapeOf");function sV(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,mA(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,mA(l)))),o.repeated?.forEach(a=>n.push({key:a.key,itemTemplate:a.itemTemplate,effects:a.effects??[]})),o.subsections?.forEach(r)},"visit");e.sections.forEach(r);let i=[{pathPrefix:"",effects:e.effects??[],shapes:t}];for(let o of n){let a=new Map(t);o.itemTemplate.forEach(l=>a.set(`$item.${l.key}`,mA(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(sV,"fieldMapScopes");function aX(e){let t=new Set,n=s(r=>{r.computed?.forEach(i=>t.add(i.key)),r.subsections?.forEach(n)},"visit");return e.sections.forEach(n),t}s(aX,"computedKeysOf");function aV(e){let t=[],n=aX(e);for(let r of sV(e))r.effects.forEach((i,o)=>{if(i.kind!=="fieldMap")return;let a=new Map;i.mappings.forEach((l,d)=>{let c=`${r.pathPrefix}effects[${o}].mappings[${d}]`;n.has(l.from)&&t.push({severity:"error",path:`${c}.from`,code:"fieldmap.computed-source",message:`Effect '${i.id}' fieldMap '${l.from}' \u2192 '${l.to}': '${l.from}' is a computed field. Its value is derived, never stored, and would never reach the party.`});let u=a.get(l.to);u!==void 0&&u!==l.from?t.push({severity:"error",path:`${c}.to`,code:"fieldmap.duplicate-target",message:`Effect '${i.id}' maps both '${u}' and '${l.from}' onto custom field '${l.to}'. One party field holds one value \u2014 the write would keep one and drop the other.`}):a.set(l.to,l.from)})});return t}s(aV,"validateFieldMapSources");function lV(e){let t=[],n=new Set;for(let o of sV(e))for(let a of o.effects)if(a.kind==="fieldMap")for(let l of a.mappings)n.add(l.from);let r=s((o,a)=>{let l=a.some(d=>n.has(d));o.kind==="cf_value"&&!l?t.push({severity:"error",path:`field '${o.key}'`,code:"persist.cf-unmapped",message:`Field '${o.key}' declares kind 'cf_value' but is not the source of any fieldMap mapping. Either wire a fieldMap ('${o.key}' \u2192 a custom-field key) or set kind: 'control'.`}):o.kind==="control"&&l&&t.push({severity:"error",path:`field '${o.key}'`,code:"persist.control-mapped",message:`Field '${o.key}' declares kind 'control' but is used as a fieldMap source, which would persist it. Set kind: 'cf_value', or remove the fieldMap mapping (a control field may still feed OutcomeDef.output.fields).`})},"check"),i=s(o=>{o.fields.forEach(a=>r(a,[a.key])),o.groups?.forEach(a=>a.fields.forEach(l=>r(l,[l.key]))),o.repeated?.forEach(a=>a.itemTemplate.forEach(l=>r(l,[`$item.${l.key}`,l.key]))),o.subsections?.forEach(i)},"visit");return e.sections.forEach(i),t}s(lV,"validateFieldPersistence");var lX="$";function dX(e){return typeof e=="string"&&e.startsWith(lX)}s(dX,"isRef");function og(e){return e.slice(1)}s(og,"stripRef");function*cX(e){switch(e.kind){case"relationship":if(yield e.from,yield e.to,e.meta)for(let t of Object.values(e.meta))yield t;return;case"fieldMap":yield e.target;return;case"shareValue":yield e.from,yield e.to;return;case"person":case"organization":return}}s(cX,"refSlots");function uX(e){let t=new Set;for(let n of cX(e))dX(n)&&t.add(og(n));return[...t]}s(uX,"collectRefs");function fX(e){let t=new Set(e.map(o=>o.id)),n=new Map,r=new Map,i=new Map;for(let o of e)i.set(o.id,o),n.set(o.id,[]),r.set(o.id,[]);for(let o of e)for(let a of uX(o))t.has(a)&&(n.get(o.id).push(a),r.get(a).push(o.id));for(let o of e){if(o.kind!=="shareValue")continue;let a=og(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&og(l.target)===a||l.kind==="shareValue"&&og(l.to)===a)||n.get(o.id).includes(l.id)||(n.get(o.id).push(l.id),r.get(l.id).push(o.id))}return{refsOf:n,successors:r,byId:i}}s(fX,"buildAdjacency");function dV(e){let{refsOf:t}=fX(e),r=Ym(e.map(i=>i.id),i=>(t.get(i)??[]).map(o=>({target:o,edge:null})))[0];return r===void 0?{hasCycle:!1}:{hasCycle:!0,cycle:r.cycle}}s(dV,"detectCycle");function cV(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(cV,"escapeRegExp");function _o(e){return new RegExp(`^${cV(e)}\\[(\\d+)\\]\\.(.+)$`)}s(_o,"repeatedRowKeyPattern");function hA(e,t){let n=_o(t),r=0;for(let i of Object.keys(e)){let o=i.match(n);if(!o)continue;let a=Number(o[1]);Number.isInteger(a)&&a+1>r&&(r=a+1)}return r}s(hA,"countRepeatedRows");function uV(e,t,n){let r=_o(t);for(let[i,o]of Object.entries(e)){let a=i.match(r);if(!(!a||Number(a[1])!==n)&&o!=null&&!(typeof o=="string"&&o.trim()==="")&&!(Array.isArray(o)&&o.length===0))return!0}return!1}s(uV,"repeatedRowHasData");function fV(e){return e.endsWith(".count")?e.slice(0,-6):e}s(fV,"readKeyOf");function gA(e){return{sections:e,fields:[]}}s(gA,"hiddenSectionsOnly");function pV(e,t,n){for(let r of e.fields)t.add(r.key);for(let r of e.groups??[])for(let i of r.fields)t.add(i.key);for(let r of e.computed??[])t.add(r.key);for(let r of e.repeated??[])n.add(r.key);for(let r of e.subsections??[])pV(r,t,n)}s(pV,"collectKeys");function mV(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;pV(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(_o)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(mV,"restrictedSectionsOf");function hV(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(hV,"matchesKey");function pX(e,t){return t.find(n=>hV(e,n))??null}s(pX,"hiddenSectionOfKey");function mX(e,t){for(let n=e;;){if(hV(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(mX,"fieldOwnsKey");function hX(e,t){return t.find(n=>mX(e,n))??null}s(hX,"restrictedFieldOfKey");function gX(e,t){let n=pX(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=hX(e,t.fields);return r===null?null:{kind:"field",field:r}}s(gX,"hiddenOwnerOfKey");function sg(e,t){return gX(e,t)!==null}s(sg,"isKeyHidden");function yX(e,t,n,r,i){let o=[];r&&o.push({severity:"error",path:n,code:"section.visibleTo-nested",message:{de:`Abschnitt '${e}' liegt in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) und darf selbst keine tragen.`,en:`Section '${e}' sits inside a section with restricted visibility (visibleTo) and may not carry one itself.`}});let a=s(l=>typeof l!="string"||l.trim()==="","isBlank");if((t.length===0||t.some(a)||new Set(t).size!==t.length)&&o.push({severity:"error",path:n,code:"section.visibleTo-invalid",message:{de:`Abschnitt '${e}': visibleTo braucht mindestens ein Team, ohne leere oder doppelte Eintr\xE4ge.`,en:`Section '${e}': visibleTo needs at least one team, with no blank or repeated entries.`}}),i===void 0)return o;for(let l of t)a(l)||i.has(l)||o.push({severity:"error",path:n,code:"section.visibleTo-unknown",message:{de:`Abschnitt '${e}': '${l}' ist weder ein Team noch eine Rechtegruppe dieser Schule.`,en:`Section '${e}': '${l}' is neither a team nor a permission group of this school.`}});return o}s(yX,"visibleToListIssues");function gV(e,t,n){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...yX(c.id,h,`${u}.visibleTo`,p,n));let y=p||h!==void 0;if(y){let b=[...c.fields,...(c.groups??[]).flatMap(k=>k.fields),...(c.repeated??[]).flatMap(k=>k.itemTemplate)];for(let k of b)k.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${k.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${k.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((b,k)=>i(b,`${u}.subsections[${k}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=mV(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=gA(p);for(let y of qt(c)){let b=fV(y);(sg(y,h)||sg(b,h))&&r.push({severity:"error",path:u,code:"section.visibleTo-read-outside",message:{de:`${u} liest '${y}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) \u2014 wer den Abschnitt nicht sieht, bek\xE4me hier ein anderes Ergebnis.`,en:`${u} reads '${y}' from a section with restricted visibility (visibleTo) \u2014 whoever cannot see the section would get a different result here.`}})}},"checkAst"),l=s((c,u,p)=>{a(c.visibleIf,`${u}.visibleIf`,p),a(c.requiredIf,`${u}.requiredIf`,p),a(c.disabledIf,`${u}.disabledIf`,p),a(c.defaultValue,`${u}.defaultValue`,p),c.sameAs!==void 0&&sg(c.sameAs.source,gA(p))&&r.push({severity:"error",path:`${u}.sameAs`,code:"section.visibleTo-read-outside",message:{de:`${u} \xFCbernimmt '${c.sameAs.source}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo).`,en:`${u} copies '${c.sameAs.source}' from a section with restricted visibility (visibleTo).`}})},"checkField"),d=s((c,u,p)=>{let h=c.visibleTo!==void 0?c.id:p,y=o.filter(b=>b.sectionId!==h);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((b,k)=>l(b,`${u}.fields[${k}]`,y)),c.groups?.forEach((b,k)=>{a(b.visibleIf,`${u}.groups[${k}].visibleIf`,y),b.fields.forEach((v,A)=>l(v,`${u}.groups[${k}].fields[${A}]`,y))}),c.repeated?.forEach((b,k)=>{a(b.itemVisibleIf,`${u}.repeated[${k}].itemVisibleIf`,y),b.itemTemplate.forEach((v,A)=>l(v,`${u}.repeated[${k}].itemTemplate[${A}]`,y))}),c.computed?.forEach((b,k)=>a(b.expression,`${u}.computed[${k}]`,y)),c.subsections?.forEach((b,k)=>d(b,`${u}.subsections[${k}]`,h))},"visitCompiled");return t.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(gV,"sectionVisibilityIssues");var hi="#";var yV=s(e=>{let t=Kv.find(n=>n.systemColumn===e);return t===void 0&&F(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),qr={firstName:yV("persons.firstName"),lastName:yV("persons.lastName")};function wV(e,t){let n={firstName:[],lastName:[]},r=`$${e}`;for(let i of t)if(!(i.kind!=="fieldMap"||i.target!==r))for(let{from:o,to:a}of i.mappings??[])a===qr.firstName?n.firstName.push(o):a===qr.lastName&&n.lastName.push(o);return n}s(wV,"personNameKeys");function kV(e){return[...e.firstName,...e.lastName]}s(kV,"personNameKeyList");function bV(e){return e.firstName.length>0||e.lastName.length>0}s(bV,"hasPersonName");function dl(e,t=[],n){let r=[];return e.forEach((i,o)=>{let a=[...t,o];r.push({section:i,path:a,parentId:n});for(let l of dl(i.subsections??[],a,i.id))r.push(l)}),r}s(dl,"walkSections");function wX(e,t){for(let n of e.fields)if(n.key===t)return n;for(let n of e.groups??[])for(let r of n.fields)if(r.key===t)return r;for(let n of e.repeated??[])for(let r of n.itemTemplate)if(r.key===t)return r;return null}s(wX,"findFieldInSection");function vV(e,t){for(let n of dl(e.sections)){let r=wX(n.section,t);if(r)return{section:n.section,field:r}}return null}s(vV,"findField");var kX=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],bX=["blue","rose","amber","violet","teal","emerald","slate"];function xV(e){return kX.includes(e)}s(xV,"isBucketIconName");function SV(e){return bX.includes(e)}s(SV,"isBucketColorName");var vX="__clear__";function AV(e){return e===""?"empty":e===vX?"reserved":null}s(AV,"selectOptionValueDefect");var yA=CM.docRef.allowedMime;function OV(e,t={}){let n=Ka(e).compiled,r=[],i=new Set,o=new Map,a=new Set,l=new Set,d=new Set,c=new Map,u=new Map;function p(O,_){if(i.has(O))return;i.add(O);let V=o.get(O.id);V&&V!==O?r.push({severity:"error",path:`sections[${_.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${O.id}' ist mehrfach deklariert.`,en:`Section id '${O.id}' is declared more than once.`}}):o.set(O.id,O);let M=`sections[${_.join(".")}]`;O.fields.forEach((W,ce)=>{cl(a,W.key,`${M}.fields[${ce}]`,"duplicate.field-key",r),l.add(W.key),u.set(W.key,W),c.set(W.key,kA(W)),W.externalFlag&&(W.type!=="boolean"&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${W.key}' muss den Typ 'boolean' haben (ist '${W.type}').`,en:`External flag '${W.key}' must be type 'boolean' (got '${W.type}').`}}),W.reviewRequired!==void 0&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"review.on-flag",message:{de:`Externes Flag '${W.key}' ist als pr\xFCfpflichtig markiert \u2014 ein Flag setzt der Prozess, die Familie reicht nichts ein, was jemand pr\xFCfen k\xF6nnte.`,en:`External flag '${W.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),W.notice!==void 0&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${W.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${W.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),W.defaultValue==null&&r.push({severity:"error",path:`${M}.fields[${ce}]`,code:"flag.missing-default",message:{de:`Externes Flag '${W.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${W.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...RV(W,`${M}.fields[${ce}]`)),r.push(...TV(W,`${M}.fields[${ce}]`))}),O.groups?.forEach((W,ce)=>{W.fields.forEach((fe,Le)=>{cl(a,fe.key,`${M}.groups[${ce}].fields[${Le}]`,"duplicate.field-key",r),l.add(fe.key),u.set(fe.key,fe),c.set(fe.key,kA(fe)),fe.externalFlag&&r.push({severity:"error",path:`${M}.groups[${ce}].fields[${Le}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${fe.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${fe.key}' must be a direct section field, not a group field.`}}),r.push(...RV(fe,`${M}.groups[${ce}].fields[${Le}]`)),r.push(...TV(fe,`${M}.groups[${ce}].fields[${Le}]`))})}),O.repeated?.forEach((W,ce)=>{W.itemTemplate.forEach((fe,Le)=>{cl(a,fe.key,`${M}.repeated[${ce}].itemTemplate[${Le}]`,"duplicate.field-key",r),c.set(fe.key,kA(fe)),fe.externalFlag&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${fe.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${fe.key}' must be a direct section field, not a repeated item field.`}}),fe.export&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"export.in-repeated",message:{de:`Feld '${fe.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${fe.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),fe.sameAs&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${fe.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${fe.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),fe.reviewRequired!==void 0&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"review.in-repeated",message:{de:`Feld '${fe.key}' ist in einem itemTemplate einer Wiederholung als pr\xFCfpflichtig markiert \u2014 ein Zeilenfeld hat je Zeile einen Wert, kein Feld der Bewerbung, das man einmal abhaken k\xF6nnte.`,en:`Field '${fe.key}' is marked as requiring review inside a repeated itemTemplate \u2014 a row field has one value per row, no field of the application to tick once.`}}),fe.notice!==void 0&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"config.notice-in-repeated",message:{de:`Feld '${fe.key}' tr\xE4gt einen Hinweis (notice) in einem itemTemplate einer Wiederholung \u2014 dort wird er nicht angezeigt. Den Hinweis an den Abschnitt setzen.`,en:`Field '${fe.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),fe.type==="docRef"&&fe.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${M}.repeated[${ce}].itemTemplate[${Le}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${fe.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${fe.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),O.computed?.forEach(W=>{d.add(W.key),cl(a,W.key,`${M}.computed[${W.key}]`,"duplicate.field-key",r),W.exportType==="consent"&&r.push({severity:"error",path:`${M}.computed[${W.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${W.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${W.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),W.export===!0&&W.exportType===void 0&&r.push({severity:"error",path:`${M}.computed[${W.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${W.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${W.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),O.subsections?.forEach((W,ce)=>p(W,[..._,ce]))}s(p,"visitRawSection"),e.sections.forEach((O,_)=>p(O,[_]));let h=new Set;n.effects.forEach((O,_)=>{cl(h,O.id,`effects[${_}]`,"duplicate.effect-id",r)});let y=new Set;n.outcomes.forEach((O,_)=>{cl(y,O.id,`outcomes[${_}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((O,_)=>{O.output.effectRefs?.forEach((V,M)=>{h.has(V.effect)||r.push({severity:"error",path:`outcomes[${_}].output.effectRefs[${M}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${O.id}' verweist auf den unbekannten Effekt '${V.effect}'.`,en:`Outcome '${O.id}' references unknown effect '${V.effect}'.`}})})}),n.outcomes.forEach((O,_)=>{O.output.fields?.forEach((V,M)=>{vV(n,V.path)||r.push({severity:"error",path:`outcomes[${_}].output.fields[${M}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${O.id}' verweist auf das unbekannte Feld '${V.path}'.`,en:`Outcome '${O.id}' references unknown field '${V.path}'.`}})})});let b=new Set;for(let O of dl(n.sections))for(let _ of O.section.repeated??[])b.add(`${_.key}.count`);for(let O of b)(a.has(O)||d.has(O))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${O}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${O}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let k={known:new Set([...a,...d,...b]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...PF(e)),r.push(...gV(e,n,t.visibleToKeys)),r.push(...bL(e));for(let O of dl(n.sections)){let _=O.section,V=`sections[${O.path.join(".")}]`;_.visibleIf&&(Kr(_.visibleIf,`${V}.visibleIf`,k,!1,r),ul(_.visibleIf,`${V}.visibleIf`,c,r)),_.fields.forEach((M,W)=>wA(M,`${V}.fields[${W}]`,k,!1,c,r)),_.groups?.forEach((M,W)=>{M.visibleIf&&(Kr(M.visibleIf,`${V}.groups[${W}].visibleIf`,k,!1,r),ul(M.visibleIf,`${V}.groups[${W}].visibleIf`,c,r)),M.fields.forEach((ce,fe)=>wA(ce,`${V}.groups[${W}].fields[${fe}]`,k,!1,c,r))}),_.repeated?.forEach((M,W)=>{M.itemVisibleIf&&(Kr(M.itemVisibleIf,`${V}.repeated[${W}].itemVisibleIf`,k,!0,r),ul(M.itemVisibleIf,`${V}.repeated[${W}].itemVisibleIf`,c,r)),M.itemTemplate.forEach((ce,fe)=>wA(ce,`${V}.repeated[${W}].itemTemplate[${fe}]`,k,!0,c,r)),M.effects?.forEach((ce,fe)=>{ce.when&&Kr(ce.when,`${V}.repeated[${W}].effects[${fe}].when`,k,!0,r)})}),_.computed?.forEach((M,W)=>Kr(M.expression,`${V}.computed[${W}].expression`,k,!1,r))}n.effects.forEach((O,_)=>{O.when&&Kr(O.when,`effects[${_}].when`,k,!1,r)}),n.outcomes.forEach((O,_)=>{Kr(O.when,`outcomes[${_}].when`,k,!1,r)});let v=new Set(n.outcomes.map(O=>O.id));function A(O,_){O.requiredFor&&O.requiredFor.forEach((V,M)=>{v.has(V)||r.push({severity:"error",path:`${_}.requiredFor[${M}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${O.key}": requiredFor verweist auf das unbekannte Ergebnis "${V}"`,en:`field "${O.key}": requiredFor references unknown outcome "${V}"`}})})}s(A,"checkRequiredFor");for(let O of dl(n.sections)){let _=O.section,V=`sections[${O.path.join(".")}]`;_.fields.forEach((M,W)=>A(M,`${V}.fields[${W}]`)),_.groups?.forEach((M,W)=>{M.fields.forEach((ce,fe)=>A(ce,`${V}.groups[${W}].fields[${fe}]`))}),_.repeated?.forEach((M,W)=>{M.itemTemplate.forEach((ce,fe)=>A(ce,`${V}.repeated[${W}].itemTemplate[${fe}]`))})}function T(O,_){let V=s((M,W)=>{let ce=(M.type==="docRef"?M.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!yA.includes(Ee));ce.length>0&&r.push({severity:"error",path:W,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${M.key}' erlaubt ${ce.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${yA.join(", ")}).`,en:`Field '${M.key}' allows ${ce.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${yA.join(", ")}).`}});let fe=M.type==="docRef"?M.docRefConstraints?.minFiles:void 0;if(fe!==void 0){let Ee=M.docRefConstraints?.multiple===!0,wt=typeof fe=="number"&&Number.isInteger(fe)&&fe>=2;(!Ee||!wt)&&r.push({severity:"error",path:W,code:"config.docref-min-files",message:Ee?{de:`Feld '${M.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(fe)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${M.key}' sets docRefConstraints.minFiles to ${JSON.stringify(fe)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${M.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${M.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}M.multiple===!0&&M.type!=="enum"&&r.push({severity:"error",path:W,code:"config.multiple-non-enum",message:{de:`Feld '${M.key}' setzt multiple: true, hat aber den Typ '${M.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(M.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${M.key}' sets multiple: true but is type '${M.type}' \u2014 only 'enum' supports multi-select.`+(M.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),M.presentation==="yesNo"&&M.type!=="boolean"&&r.push({severity:"error",path:W,code:"config.yesno-non-boolean",message:{de:`Feld '${M.key}' setzt presentation: 'yesNo', hat aber den Typ '${M.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${M.key}' sets presentation: 'yesNo' but is type '${M.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),M.presentation==="yesNo"&&M.defaultValue!=null&&r.push({severity:"error",path:W,code:"config.yesno-default",message:{de:`Feld '${M.key}' ist eine Ja | Nein-Frage (presentation: 'yesNo') mit einem defaultValue \u2014 die Familie muss die Antwort selbst w\xE4hlen. Den defaultValue entfernen.`,en:`Field '${M.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...SX(M,W)),typeof M.minSelections=="number"&&typeof M.maxSelections=="number"&&M.minSelections>M.maxSelections&&r.push({severity:"error",path:W,code:"config.min-gt-max-selections",message:{de:`Feld '${M.key}' hat minSelections (${M.minSelections}) > maxSelections (${M.maxSelections}).`,en:`Field '${M.key}' has minSelections (${M.minSelections}) > maxSelections (${M.maxSelections}).`}}),r.push(...AX(M,W));let Le=M.enumRef;Le!==void 0&&r.push({severity:"error",path:`${W}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${M.key}' nennt den entfernten Options-Katalog (enumRef '${String(Le)}'). Die Optionen im Formular angeben (enumOptions + enumOptionLabels) oder eine Liste des Mandanten binden (enumListKey).`,en:`Field '${M.key}' names the removed option catalog (enumRef '${String(Le)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(M.enumOptions??[]).forEach((Ee,wt)=>{let nt=AV(Ee);nt!==null&&r.push({severity:"error",path:`${W}.enumOptions[${wt}]`,code:"config.enum-option-value",message:{de:nt==="empty"?`Feld '${M.key}' hat einen leeren Enum-Optionswert \u2014 das Steuerelement kann ihn nicht tragen. Der Option einen Wert geben oder sie streichen: Ein Feld, das unbeantwortet bleiben darf, bietet bereits eine eigene Zeile zum Leeren.`:`Feld '${M.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:nt==="empty"?`Field '${M.key}' has an empty enum option value \u2014 the control cannot carry it. Give the option a value, or drop it: a field that may be left unanswered already offers its own clear row.`:`Field '${M.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(M.attachments??[]).forEach((Ee,wt)=>{if("storageId"in Ee){r.push({severity:"error",path:`${W}.attachments[${wt}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${M.key}' tr\xE4gt eine rohe 'storageId' \u2014 Anh\xE4nge nennen eine Bibliotheksdatei jetzt per 'fileKey' (plexus-cli files put, dann field attach --file-key).`,en:`Field '${M.key}' attachment carries a raw 'storageId' \u2014 attachments name a library file by 'fileKey' now (plexus-cli files put, then field attach --file-key).`}});return}let nt=Ee.fileKey!==void 0&&Ee.fileKey!=="",$t=Ee.url!==void 0&&Ee.url!=="";nt===$t&&r.push({severity:"error",path:`${W}.attachments[${wt}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${M.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${nt&&$t?"beide":"keines"}).`,en:`Field '${M.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${nt&&$t?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${W}.attachments[${wt}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${M.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${M.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");O.fields.forEach((M,W)=>V(M,`${_}.fields[${W}]`)),O.groups?.forEach((M,W)=>{M.fields.forEach((ce,fe)=>V(ce,`${_}.groups[${W}].fields[${fe}]`))}),O.repeated?.forEach((M,W)=>{M.itemTemplate.forEach((ce,fe)=>{let Le=`${_}.repeated[${W}].itemTemplate[${fe}]`;V(ce,Le),ce.type==="consent"&&r.push({severity:"error",path:Le,code:"config.consent-in-repeated",message:{de:`Feld '${ce.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${ce.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),O.subsections?.forEach((M,W)=>T(M,`${_}.subsections[${W}]`))}s(T,"visitFieldConfig"),e.sections.forEach((O,_)=>T(O,`sections[${_}]`)),e.effects.forEach((O,_)=>{if(O.kind==="person"){r.push(...IV(O,e.effects,`effects[${_}]`,V=>l.has(V)));return}O.kind==="organization"&&O.nameFrom?.forEach((V,M)=>{l.has(V)||r.push({severity:"error",path:`effects[${_}].nameFrom[${M}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${O.id}': nameFrom verweist auf das unbekannte Feld '${V}'.`,en:`Effect '${O.id}' nameFrom references unknown field '${V}'.`}})})});let I=s((O,_)=>{if(O.kind!=="person"&&O.kind!=="organization")return;let V=O.display;if(!V){r.push({severity:"error",path:`${_}.display`,code:"display.missing",message:{de:`Effekt '${O.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${O.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}xV(V.icon)||r.push({severity:"error",path:`${_}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${O.id}': display.icon '${V.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${O.id}' display.icon '${V.icon}' is not a known bucket icon.`}}),SV(V.color)||r.push({severity:"error",path:`${_}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${O.id}': display.color '${V.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${O.id}' display.color '${V.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((O,_)=>I(O,`effects[${_}]`));let C=new Set,L=s(O=>{O.kind==="person"?C.add(O.bucket):O.kind==="organization"&&C.add(O.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(L);let N=new Set,x=s(O=>{for(let _ of O)_.repeated?.forEach(V=>V.effects?.forEach(M=>L(M))),x(_.subsections??[])},"collectRepeatedBuckets");x(e.sections);let D=s((O,_)=>{C.size!==0&&O.forEach((V,M)=>{V.bucket===void 0||C.has(V.bucket)||r.push({severity:"error",path:`${_}[${M}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${V.key}' geh\xF6rt zum Bucket '${V.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${V.key}' belongs to bucket '${V.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),R=s((O,_)=>{if(N.has(O))return;N.add(O);let V=`sections[${_.join(".")}]`;D(O.fields,`${V}.fields`),O.groups?.forEach((M,W)=>D(M.fields,`${V}.groups[${W}].fields`)),O.repeated?.forEach((M,W)=>D(M.itemTemplate,`${V}.repeated[${W}].itemTemplate`)),O.subsections?.forEach((M,W)=>R(M,[..._,W]))},"visitBucketSection");e.sections.forEach((O,_)=>R(O,[_]));let q=e.effects.flatMap((O,_)=>O.kind==="person"&&O.subject===!0?[{e:O,i:_}]:[]);q.length>1&&q.slice(1).forEach(({e:O,i:_})=>{r.push({severity:"error",path:`effects[${_}].subject`,code:"subject.duplicate",message:{de:`Effekt '${O.id}' deklariert subject:true, aber '${q[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${O.id}' declares subject:true, but '${q[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((O,_)=>{if(!(O.kind!=="person"||O.nationalityFrom===void 0)){if(O.subject!==!0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${O.id}' deklariert nationalityFrom, ist aber nicht das Subjekt der Bewerbung \u2014 die Staatsangeh\xF6rigkeit wird nur f\xFCr das Subjekt der Bewerbung gelesen.`,en:`Effect '${O.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(O.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${O.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${O.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}O.nationalityFrom.forEach((V,M)=>{l.has(V)||r.push({severity:"error",path:`effects[${_}].nationalityFrom[${M}]`,code:"nationality.unknown-field",message:{de:`Effekt '${O.id}': nationalityFrom verweist auf das unbekannte Feld '${V}'.`,en:`Effect '${O.id}' nationalityFrom references unknown field '${V}'.`}})})}});let G=e.effects.flatMap((O,_)=>O.kind==="person"&&O.contractParty!==void 0?[{e:O,i:_,decl:O.contractParty}]:[]);if(G.length>0){let O=new Map;G.forEach(({e:V,i:M})=>{let W=O.get(V.bucket);if(W===void 0){O.set(V.bucket,V.id);return}r.push({severity:"error",path:`effects[${M}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${V.id}' deklariert eine Vertragspartei auf Bucket '${V.bucket}', aber '${W}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${V.id}' declares a contract party on bucket '${V.bucket}', but '${W}' already does. A bucket is at most one contract party.`}})});let _=G.filter(({decl:V})=>V.role==="beneficiary");_.slice(1).forEach(({e:V,i:M})=>{r.push({severity:"error",path:`effects[${M}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${V.id}' deklariert contractParty.role 'beneficiary', aber '${_[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${V.id}' declares contractParty.role 'beneficiary', but '${_[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),_.forEach(({e:V,i:M})=>{V.subject!==!0&&r.push({severity:"error",path:`effects[${M}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${V.id}' ist der Leistungsempf\xE4nger des Vertrags, aber nicht das Subjekt der Bewerbung. Leistungsempf\xE4nger und Subjekt der Bewerbung sind dieselbe Person \u2014 subject:true auf '${V.id}' setzen.`,en:`Effect '${V.id}' is the contract beneficiary but not the application subject. The beneficiary and the application subject are the same person \u2014 set subject:true on '${V.id}'.`}})}),q.forEach(({e:V,i:M})=>{let W=V.contractParty?.role;W!==void 0&&W!=="beneficiary"&&r.push({severity:"error",path:`effects[${M}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${V.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${W}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${V.id}' is the application subject but declares contractParty.role '${W}'. The application subject is the contract beneficiary.`}})}),G.some(({decl:V})=>V.signs===!0)||r.push({severity:"error",path:"effects",code:"contractParty.no-signer",message:{de:"Das Formular deklariert Vertragsparteien, aber keine unterschreibt (contractParty.signs). Ein Vertrag ohne Unterzeichner kann nicht erzeugt werden.",en:"The form declares contract parties, but none signs (contractParty.signs). A contract without a signatory cannot be generated."}})}e.effects.forEach((O,_)=>{O.kind==="fieldMap"&&O.mappings.forEach((V,M)=>{a.has(V.from)||r.push({severity:"error",path:`effects[${_}].mappings[${M}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${O.id}': fieldMap from '${V.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${O.id}' fieldMap from '${V.from}' references unknown field.`}})})});for(let[O,_]of u){if(!_.sameAs)continue;let V=`fields[${O}].sameAs`,M=u.get(_.sameAs.source);M===void 0||_.sameAs.source===O?r.push({severity:"error",path:`${V}.source`,code:"ref.unknown-sameas-source",message:{de:_.sameAs.source===O?`Feld '${O}': sameAs.source verweist auf sich selbst.`:`Feld '${O}': sameAs.source verweist auf das unbekannte Feld '${_.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:_.sameAs.source===O?`Field '${O}' sameAs.source references itself.`:`Field '${O}' sameAs.source references unknown field '${_.sameAs.source}' (must be a top-level or group field).`}}):M.type!==_.type?r.push({severity:"error",path:`${V}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}' (${_.type}): sameAs.source '${_.sameAs.source}' hat einen anderen Typ (${M.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${O}' (${_.type}) sameAs.source '${_.sameAs.source}' has a different type (${M.type}) \u2014 the mirror must be shape-identical.`}}):M.sameAs&&r.push({severity:"error",path:`${V}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}': sameAs.source '${_.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${O}' sameAs.source '${_.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let W=u.get(_.sameAs.toggle);(W===void 0||W.type!=="boolean")&&r.push({severity:"error",path:`${V}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:W===void 0?`Feld '${O}': sameAs.toggle verweist auf das unbekannte Feld '${_.sameAs.toggle}'.`:`Feld '${O}': sameAs.toggle '${_.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${W.type}').`,en:W===void 0?`Field '${O}' sameAs.toggle references unknown field '${_.sameAs.toggle}'.`:`Field '${O}' sameAs.toggle '${_.sameAs.toggle}' must be type 'boolean' (got '${W.type}').`}}),_.required===!0&&r.push({severity:"error",path:`fields[${O}].required`,code:"config.sameas-static-required",message:{de:`Feld '${O}' deklariert sameAs, ist aber statisch Pflicht \u2014 solange es gespiegelt ist, hat es keinen eigenen Wert, die Slice-Validierung beim Commit w\xFCrde immer scheitern. required: false + requiredIf: "${_.sameAs.toggle} != true" verwenden.`,en:`Field '${O}' declares sameAs but is statically required \u2014 while mirrored it holds no own value, so commit-time slice validation would always fail. Use required: false + requiredIf: "${_.sameAs.toggle} != true".`}})}{let O=new Map;e.effects.forEach(_=>O.set(_.id,_.kind)),e.effects.forEach((_,V)=>{if(_.kind!=="shareValue")return;[["from",_.from],["to",_.to]].forEach(([ce,fe])=>{let Le=O.get(fe.slice(1));Le!==void 0&&Le!=="person"&&Le!=="organization"&&r.push({severity:"error",path:`effects[${V}].${ce}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${_.id}': shareValue ${ce} '${fe}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${Le}').`,en:`Effect '${_.id}' shareValue ${ce} '${fe}' must reference a person/organization effect (got '${Le}').`}})});let M=_.from.slice(1);e.effects.some(ce=>ce.kind==="fieldMap"&&ce.target.slice(1)===M&&ce.mappings.some(fe=>fe.to===_.field)||ce.kind==="shareValue"&&ce.id!==_.id&&ce.to.slice(1)===M&&ce.field===_.field)||r.push({severity:"error",path:`effects[${V}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${_.id}' teilt das Feld '${_.field}' aus '${_.from}', aber kein fieldMap mit Ziel '${_.from}' bildet auf '${_.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${_.id}' shares field '${_.field}' from '${_.from}', but no fieldMap targeting '${_.from}' maps to '${_.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((O,_)=>{O.kind==="person"&&O.bucket.includes(hi)&&r.push({severity:"error",path:`effects[${_}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': bucket '${O.bucket}' darf '${hi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' bucket '${O.bucket}' must not contain '${hi}' (reserved for the per-row namespace).`}}),O.kind==="organization"&&O.orgKind.includes(hi)&&r.push({severity:"error",path:`effects[${_}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': orgKind '${O.orgKind}' darf '${hi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' orgKind '${O.orgKind}' must not contain '${hi}' (reserved for the per-row namespace).`}})});let ae=new Set;function Z(O,_){O.repeated?.forEach((V,M)=>{let W=V.effects??[];if(W.length>0){let ce=`${_}.repeated[${M}]`,fe=new Set(W.map(le=>le.id)),Le=new Set(V.itemTemplate.map(le=>le.key)),Ee=(V.uniqueBy?.length??0)>0,wt=s(le=>le.startsWith("$item.")?Le.has(le.slice(6)):l.has(le),"resolvesName"),nt=s(le=>le.startsWith("$item.")?Le.has(le.slice(6)):a.has(le),"resolvesFrom"),$t=s(le=>{let Qt=le.slice(1);return fe.has(Qt)||h.has(Qt)},"resolvesRef");W.forEach((le,Qt)=>{let kt=`${ce}.effects[${Qt}]`;if(h.has(le.id)||ae.has(le.id)?r.push({severity:"error",path:kt,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${le.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${le.id}' is declared more than once.`}}):ae.add(le.id),le.kind==="person"||le.kind==="organization"){I(le,kt),le.kind==="person"&&le.subject===!0&&r.push({severity:"error",path:`${kt}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${le.id}' der Wiederholung deklariert subject:true \u2014 eine Zeile gilt je Zeile, das Subjekt der Bewerbung je Bewerbung. Das Subjekt an einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${le.id}' declares subject:true \u2014 a repeated row is per-row, the application subject is per-application. Declare the subject on a top-level effect.`}}),le.kind==="person"&&le.nationalityFrom!==void 0&&r.push({severity:"error",path:`${kt}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${le.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${le.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),le.kind==="person"&&le.contractParty!==void 0&&r.push({severity:"error",path:`${kt}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${le.id}' der Wiederholung deklariert contractParty \u2014 wer unterschreibt, wird einmal je Bewerbung deklariert, nicht je Zeile. An einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${le.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ee||r.push({severity:"error",path:ce,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${V.key}' hat einen Parteien erzeugenden Effekt '${le.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${V.key}' has a party-creating effect '${le.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Me=le.kind==="person"?le.bucket:le.orgKind;Me.includes(hi)&&r.push({severity:"error",path:`${kt}.${le.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${le.id}' der Wiederholung: ${le.kind==="person"?"bucket":"orgKind"} '${Me}' darf '${hi}' nicht enthalten.`,en:`Repeated effect '${le.id}' ${le.kind==="person"?"bucket":"orgKind"} '${Me}' must not contain '${hi}'.`}}),le.kind==="person"&&r.push(...IV(le,W,kt,wt)),le.kind==="organization"&&le.nameFrom?.forEach((We,Bn)=>{wt(We)||r.push({severity:"error",path:`${kt}.nameFrom[${Bn}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${le.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${We}'.`,en:`Repeated effect '${le.id}' nameFrom references unknown field '${We}'.`}})}),le.identity?.strategy==="keyed"&&le.identity.keyFrom.forEach((We,Bn)=>{nt(We)||r.push({severity:"error",path:`${kt}.identity.keyFrom[${Bn}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${le.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${We}'.`,en:`Repeated effect '${le.id}' identity.keyFrom references unknown field '${We}'.`}})})}else if(le.kind==="relationship"){if([["from",le.from],["to",le.to]].forEach(([Me,We])=>{$t(We)||r.push({severity:"error",path:`${kt}.${Me}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${le.id}' der Wiederholung: ${Me} verweist auf den unbekannten Effekt '${We}'.`,en:`Repeated relationship '${le.id}' ${Me} references unknown effect '${We}'.`}})}),le.meta)for(let[Me,We]of Object.entries(le.meta))typeof We=="string"&&We.startsWith("$")&&!$t(We)&&r.push({severity:"error",path:`${kt}.meta.${Me}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${le.id}' der Wiederholung: meta.${Me} verweist auf den unbekannten Effekt '${We}'.`,en:`Repeated relationship '${le.id}' meta.${Me} references unknown effect '${We}'.`}})}else le.kind==="fieldMap"?($t(le.target)||r.push({severity:"error",path:`${kt}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${le.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${le.target}'.`,en:`Repeated fieldMap '${le.id}' target references unknown effect '${le.target}'.`}}),le.mappings.forEach((Me,We)=>{nt(Me.from)||r.push({severity:"error",path:`${kt}.mappings[${We}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${le.id}' der Wiederholung: from '${Me.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${le.id}' from '${Me.from}' references unknown field.`}})})):le.kind==="shareValue"&&r.push({severity:"error",path:kt,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${le.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${le.id}': shareValue is not supported inside repeated row effects.`}})})}}),O.subsections?.forEach((V,M)=>Z(V,`${_}.subsections[${M}]`))}s(Z,"visitRepeatedEffects"),e.sections.forEach((O,_)=>Z(O,`sections[${_}]`));let oe=dV(n.effects);return oe.hasCycle&&r.push({severity:"error",path:"effects",code:"graph.effect-cycle",message:{de:`Der Effektgraph enth\xE4lt einen Zyklus: ${oe.cycle?.join(" \u2192 ")??"?"}`,en:`Effect graph contains a cycle: ${oe.cycle?.join(" \u2192 ")??"?"}`}}),r.push(...xX(e)),r}s(OV,"validateForm");function xX(e){let t={...e,effects:e.effects.map(_V),sections:e.sections.map(NV),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return Nm(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:Ab(n)}))}s(xX,"missingTranslationIssues");function _V(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(_V,"withoutSubjectFlag");function NV(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(_V)})),subsections:e.subsections?.map(NV)}}s(NV,"withoutRowSubjectFlags");function TV(e,t){let n=e.reviewRequired;return n===void 0||n===!0?[]:[{severity:"error",path:t,code:"review.shape",message:{de:`Feld '${e.key}' setzt reviewRequired auf ${JSON.stringify(n)} \u2014 erlaubt ist nur true; ein nicht pr\xFCfpflichtiges Feld l\xE4sst die Angabe weg.`,en:`Field '${e.key}' sets reviewRequired to ${JSON.stringify(n)} \u2014 only true is allowed; a field that needs no review omits it.`}}]}s(TV,"reviewRequiredShapeIssues");function RV(e,t){if(!e.export)return[];let n=[];return e.type==="docRef"&&n.push({severity:"error",path:t,code:"export.invalid-type",message:{de:`Feld '${e.key}' (docRef) kann nicht exportiert werden \u2014 ein Speicher-Handle ist kein bindbarer Dokumentwert.`,en:`Field '${e.key}' (docRef) cannot be exported \u2014 a storage handle is not a bindable document value.`}}),e.multiple===!0&&n.push({severity:"error",path:t,code:"export.multiple-enum",message:{de:`Feld '${e.key}' ist eine Mehrfachauswahl \u2014 N gew\xE4hlte Optionen sind kein einzelnes zusammengesetztes Blatt, deshalb nicht exportierbar.`,en:`Field '${e.key}' is a multi-select \u2014 N picked options are not one compound leaf, so it cannot be exported.`}}),n}s(RV,"exportGateIssues");function cl(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${$V(r,"de")} '${t}'`,en:`Duplicate ${$V(r,"en")}: '${t}'`}}):e.add(t)}s(cl,"reportIfDup");function $V(e,t){let n=s((r,i)=>t==="de"?r:i,"label");switch(e){case"duplicate.section-id":return n("Abschnitts-ID","section id");case"duplicate.field-key":return n("Feldschl\xFCssel","field key");case"duplicate.effect-id":return n("Effekt-ID","effect id");case"duplicate.outcome-id":return n("Ergebnis-ID","outcome id");case"ref.unknown-required-for-outcome":return n("requiredFor-Ergebnis","requiredFor outcome");default:return e}}s($V,"labelForCode");function wA(e,t,n,r,i,o){e.visibleIf&&(Kr(e.visibleIf,`${t}.visibleIf`,n,r,o),ul(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(Kr(e.requiredIf,`${t}.requiredIf`,n,r,o),ul(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(Kr(e.disabledIf,`${t}.disabledIf`,n,r,o),ul(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&Kr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(wA,"checkFieldAsts");function kA(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(kA,"gatingMeta");function ul(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(EV(o.left,o.right,o.op,t,n,r),EV(o.right,o.left,o.op,t,n,r)),i(o.left),i(o.right);return}case"unary":i(o.operand);return;case"if":i(o.cond),i(o.then),i(o.else);return;case"call":o.args.forEach(i);return;case"arr":o.items.forEach(i);return;default:return}}s(i,"walk"),i(e)}s(ul,"checkGatingExpr");function EV(e,t,n,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);if(a){if(a.isConsent&&t.kind==="bool"&&t.value===!1){o.push({severity:"error",path:r,code:"expr.consent-compare-false",message:{de:`Gating-Ausdruck vergleicht die Zustimmung '${e.path}' mit false \u2014 eine Zustimmung ist true oder leer, nie false. '${e.path} != true' verwenden.`,en:`Gating expression compares the consent '${e.path}' to false \u2014 a consent is true or empty, never false. Use '${e.path} != true'.`}});return}a.isBoolean&&(a.hasDefault||t.kind!=="null"&&t.kind==="bool"&&(a.isYesNo&&n==="=="||o.push({severity:"error",path:r,code:"expr.gating-compare-undefaulted-field",message:{de:`Gating-Ausdruck vergleicht das Boolean-Feld '${e.path}' ohne Standardwert per '${n}' mit einem Bool-Literal. In dreiwertiger Logik ist 'undefined ${n} ${t.value}' ${n==="=="?"false":"true"} \u2014 das Gate greift stillschweigend bei ungesetzten Werten. Dem Feld '${e.path}' einen 'defaultValue' geben (oder den Ausdruck umschreiben \u2014 z. B. '${e.path} != null' als ausdr\xFCckliche Gesetzt-Pr\xFCfung).`,en:`Gating expression compares undefaulted boolean field '${e.path}' to a bool literal via '${n}'. In three-valued logic, 'undefined ${n} ${t.value}' is ${n==="=="?"false":"true"} \u2014 the gate fires silently for unset values. Add a 'defaultValue' to field '${e.path}' (or rewrite the expression \u2014 e.g. '${e.path} != null' for an explicit set-check).`}})))}}s(EV,"inspectEqualityOperand");function Kr(e,t,n,r,i){i.push(...NF(e,n.declaredContext,t)),i.push(...Em(e,n.stageKeys,t));for(let o of qt(e))n.known.has(o)||bb(o)||r&&o.startsWith("$item.")||i.push({severity:"error",path:t,code:"ref.unknown-ident",message:{de:o.startsWith("$")?`Bezeichner '${o}' ist kein Geltungsbereich, den ein Formular liest \u2014 Umgebungsvariablen sind '$env.<key>.<field>', Wiederholungszeilen '$item.*'.`:`Bezeichner '${o}' ist weder als Feld, berechneter Schl\xFCssel noch als $item-Slot deklariert.`,en:o.startsWith("$")?`Identifier '${o}' is no scope a form reads \u2014 environment variables are '$env.<key>.<field>', repeated rows '$item.*'.`:`Identifier '${o}' is not declared as a field, computed key, or $item slot.`}})}s(Kr,"checkAst");function IV(e,t,n,r){let i=[];e.nameFrom!==void 0&&i.push({severity:"error",path:`${n}.nameFrom`,code:"person.name-from-removed",message:{de:`Effekt '${e.id}': eine Person hat kein nameFrom mehr \u2014 ihr Name ist die Feldzuordnung (fieldMap) auf ${qr.firstName} / ${qr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${qr.firstName} / ${qr.lastName}. Remove nameFrom.`}});let o=wV(e.id,t);bV(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${qr.firstName} oder ${qr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${qr.firstName} or ${qr.lastName} \u2014 the person would get no name.`}});for(let a of kV(o))r(a)||i.push({severity:"error",path:n,code:"ref.unknown-name-field",message:{de:`Effekt '${e.id}': der Name wird aus '${a}' gelesen, das kein eingegebenes Feld ist.`,en:`Effect '${e.id}': its name is read from '${a}', which is not an entered field.`}});return i}s(IV,"personNameIssues");function SX(e,t){let n=[],r=e.required===!0||e.requiredIf!==void 0;return e.type==="consent"&&(e.defaultValue!=null&&n.push({severity:"error",path:t,code:"config.consent-default",message:{de:`Feld '${e.key}' ist eine Zustimmung mit einem defaultValue \u2014 zustimmen muss die Familie selbst. Den defaultValue entfernen.`,en:`Field '${e.key}' is a consent with a defaultValue \u2014 the family must give it themselves. Remove the defaultValue.`}}),e.sameAs!==void 0&&n.push({severity:"error",path:t,code:"config.consent-computed",message:{de:`Feld '${e.key}' ist eine Zustimmung, die ein anderes Feld spiegelt (sameAs) \u2014 zustimmen muss die Familie selbst. sameAs entfernen.`,en:`Field '${e.key}' is a consent mirroring another field (sameAs) \u2014 the family must give it themselves. Remove sameAs.`}}),r||n.push({severity:"error",path:t,code:"config.consent-not-required",message:{de:`Feld '${e.key}' ist eine Zustimmung, die nie verlangt wird \u2014 required: true oder requiredIf setzen, sonst Typ 'boolean' verwenden.`,en:`Field '${e.key}' is a consent nobody is asked to give \u2014 set required: true or requiredIf, or use type 'boolean'.`}})),e.type==="boolean"&&r&&e.defaultValue?.trim()==="false"&&n.push({severity:"warning",path:t,code:"config.boolean-required-default-false",message:{de:`Feld '${e.key}' ist ein Ja/Nein-Pflichtfeld, vorbelegt mit Nein \u2014 es gilt von Anfang an als ausgef\xFCllt. Ist es eine Zustimmung, Typ 'consent' verwenden.`,en:`Field '${e.key}' is a required yes/no preset to No \u2014 it counts as answered from the start. If it is a consent, use type 'consent'.`}}),n}s(SX,"consentConfigIssues");function AX(e,t){let n=e.exclusiveOptions;if(n===void 0)return[];let r=s((a,l)=>[{severity:"error",path:t,code:"config.exclusive-options",message:{de:a,en:l}}],"refuse");if(e.type!=="enum"||e.multiple!==!0)return r(`Feld '${e.key}' setzt exclusiveOptions ohne Mehrfachauswahl \u2014 exklusive Optionen gibt es nur bei type: 'enum' mit multiple: true.`,`Field '${e.key}' sets exclusiveOptions without a multi-select \u2014 exclusive options exist only on type: 'enum' with multiple: true.`);if(e.enumListKey!==void 0)return r(`Feld '${e.key}' setzt exclusiveOptions auf einer Liste des Mandanten (enumListKey) \u2014 exklusive Optionen brauchen eigene enumOptions.`,`Field '${e.key}' sets exclusiveOptions on a tenant list (enumListKey) \u2014 exclusive options need inline enumOptions.`);if(!Array.isArray(n)||n.length===0||n.some(a=>typeof a!="string"))return r(`Feld '${e.key}' setzt exclusiveOptions auf ${JSON.stringify(n)} \u2014 erwartet ist eine nicht leere Liste von Optionsschl\xFCsseln.`,`Field '${e.key}' sets exclusiveOptions to ${JSON.stringify(n)} \u2014 it must be a non-empty list of option keys.`);let i=e.enumOptions??[],o=n.filter(a=>!i.includes(a));return o.length>0?r(`Feld '${e.key}' nennt in exclusiveOptions ${o.map(a=>`'${a}'`).join(", ")} \u2014 keine Option des Feldes.`,`Field '${e.key}' names ${o.map(a=>`'${a}'`).join(", ")} in exclusiveOptions \u2014 not an option of the field.`):new Set(n).size!==n.length?r(`Feld '${e.key}' nennt eine Option in exclusiveOptions doppelt.`,`Field '${e.key}' names an option twice in exclusiveOptions.`):[]}s(AX,"exclusiveOptionIssues");function Ps(e,t,n){try{return nn(e,t)}catch(r){F(`${n} does not evaluate: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}s(Ps,"evalOrBug");var TX="blocked";function PV(e,t){let n={values:t};for(let r of e.outcomes){let i=Ps(r.when,n,`outcome "${r.id}" when-expression`);if(RX(i))return r.id===TX?null:r.id}return null}s(PV,"resolveActiveOutcome");function RX(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(RX,"truthy");function CV(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(CV,"isScalar");function $X(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(CV(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))CV(a)&&(t[`${r}.${o}`]=a)}EX(e,t,n)}s($X,"mergeRecord");function EX(e,t,n){let r=new Set(n);for(let i of Object.keys(e)){let o=i.indexOf("[");if(o<=0)continue;let a=i.slice(0,o);_o(a).test(i)&&r.add(a)}for(let i of r){let o=hA(e,i),a=0;for(let l=0;l<o;l++)uV(e,i,l)&&a++;t[`${i}.count`]=a}}s(EX,"mergeRepeatedCounts");function DV(e,t,n){let r={...n};return $X(e,r,t),r}s(DV,"flattenValues");function bA(e,t,n){return{code:e,fieldKey:t,text:n}}s(bA,"submitIssue");function FV(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(FV,"truthyEval");function LV(e){if(e==null)return!0;if(typeof e=="string")return e.trim()==="";if(Array.isArray(e))return e.length===0;if(typeof e=="object"){let t=e;if("storageId"in t)return!(typeof t.storageId=="string"&&t.storageId.trim()!=="");let n=t;return!n.street?.trim()||!n.hausnr?.trim()||!n.plz?.trim()||!n.ort?.trim()||!n.land?.trim()}return!1}s(LV,"isEmptyValue");function IX(e,t,n){let r=!!e.required;return!r&&e.requiredIf&&(r=FV(Ps(e.requiredIf,{values:t},`requiredIf of '${e.key}'`))),r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(IX,"fieldIsLiveRequired");function OX(e,t,n){return MV(e,t,n).evalCtx}s(OX,"buildSubmitEvalContext");function MV(e,t,n){let r=_X(e),i=Object.keys(t).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[y,b]of Object.entries(t))(r(y)===null||o.has(y))&&(l[y]=b);let d=qV(e,l,n),c=new Set,u=new Set;jV(e,d,y=>c.add(y.key),y=>u.add(y.key));let p=new Set(i.filter(y=>{let b=r(y);return b.kind==="field"?c.has(y):u.has(b.repeatedKey)}));if(p.size===o.size&&[...p].every(y=>o.has(y))){let y={};for(let b of i)o.has(b)||(y[b]=t[b]);return{visible:l,hidden:y,evalCtx:d}}let h=[...p].sort().join("\0");if(a.has(h)){let y=i.filter(b=>p.has(b)!==o.has(b));F(`[smartForm] visibility of ${y.join(", ")} does not settle \u2014 each depends on whether the other's value counts. The form's visibleIf conditions are contradictory.`)}a.add(h),o=p}}s(MV,"splitWithContext");function _X(e){let t=new Map,n=[];for(let r of lg(e.sections)){for(let i of r.fields)t.set(i.key,i);for(let i of r.groups??[])for(let o of i.fields)t.set(o.key,o);for(let i of r.repeated??[])n.push({key:i.key,pattern:_o(i.key),items:new Map(i.itemTemplate.map(o=>[o.key,o]))})}return r=>{let i=t.get(r);if(i!==void 0)return{kind:"field",field:i};for(let o of n){let a=o.pattern.exec(r);if(a!==null)return{kind:"row",repeatedKey:o.key,field:o.items.get(a[2])}}return null}}s(_X,"fieldOwnership");function qV(e,t,n){let r=[];for(let o of lg(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=DV(t,r,n);for(let o of lg(e.sections))for(let a of o.computed??[])i[a.key]=Ps(a.expression,{values:i},`computed '${a.key}'`);return i}s(qV,"rawEvalContext");function KV(e,t,n){let{values:r,defaulted:i}=NX(e,t,n),o=MV(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(KV,"splitDraftValues");function NX(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of lg(e.sections))for(let d of[...l.fields,...(l.groups??[]).flatMap(c=>c.fields)]){if(!d.defaultValue||t[d.key]!=null||r?.(d.key))continue;a??=qV(e,t,n);let c=Ps(d.defaultValue,{values:a},`defaultValue of '${d.key}'`);c!=null&&(i[d.key]=c,o.add(d.key))}return{values:i,defaulted:o}}s(NX,"applyFieldDefaults");function lg(e){let t=[],n=s(r=>{t.push(r);for(let i of r.subsections??[])n(i)},"walk");for(let r of e)n(r);return t}s(lg,"walkSectionsDeep");function PX(e,t,n,r=!1){if(LV(t))return null;let i=n.fields[e.type];i||F(`[fieldFormatIssue] no field provider registered for type "${e.type}" (field "${e.key}"). Register it in the domain form registry.`);let o=i.validate(e,t,{state:{values:{},computed:{}},testMode:r});return o.length>0?o[0].message:null}s(PX,"fieldFormatIssue");function CX(e,t){return LV(t)||e.type==="consent"&&t!==!0}s(CX,"isUnanswered");function ag(e,t){return e?FV(Ps(e,{values:t},"visibleIf")):!0}s(ag,"isVisibleUnder");function jV(e,t,n,r){let i=s(o=>{if(ag(o.visibleIf,t)){for(let a of o.fields)ag(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(ag(a.visibleIf,t))for(let l of a.fields)ag(l.visibleIf,t)&&n(l);if(r!==void 0)for(let a of o.repeated??[])r(a);for(let a of o.subsections??[])i(a)}},"walk");for(let o of e.sections)i(o)}s(jV,"forEachVisibleField");function VV(e,t,n,r={}){let i=OX(e,t,n),o=[],a=PV(e,i);a===null&&r.requireOutcome!==!1&&o.push(bA("no-outcome",null,{de:"Die Angaben ergeben keinen g\xFCltigen Abschluss \u2014 bitte pr\xFCfen Sie das Formular.",en:"The answers do not lead to a valid outcome \u2014 please check the form."}));let l=new Set(r.exemptFromRequired??[]);return jV(e,i,d=>{let c=t[d.key];if(CX(d,c)){!l.has(d.type)&&IX(d,i,a)&&o.push(bA("required",d.key,sd([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=PX(d,c,r.registry,r.testMode===!0);u!==null&&o.push(bA("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(VV,"checkSubmittable");function UV(){return[...Ge,null].flatMap(t=>zw.map(n=>({language:t,channel:n})))}s(UV,"applicantVariants");function GV(e,t){let n=new Map;for(let r of e){let i={};for(let a of t)r[a]===void 0&&F(`[scenario/environment] the host supplied no "${a}"`),i[a]=r[a];let o=JSON.stringify(t.map(a=>i[a]));n.has(o)||n.set(o,i)}return[...n.values()]}s(GV,"projectEnvironments");var BV={"self-service":{de:"online",en:"online"},staff:{de:"durch die Schule",en:"by the school"}};function zV(e){let t=[];for(let n of[e.offer?.title,e.unit?.name,e.stage?.name,e.run?.name])n!==void 0&&t.push({de:n,en:n});if(e.applicant){let{language:n,channel:r}=e.applicant;t.push({de:`${n===null?"ohne Konto":`Konto ${n}`}, ${BV[r].de}`,en:`${n===null?"no account":`account ${n}`}, ${BV[r].en}`})}return{de:t.map(n=>n.de).join(" \xB7 "),en:t.map(n=>n.en).join(" \xB7 ")}}s(zV,"describeEnvironment");var WV=6;function YV(e,t){let n=e.slice(0,WV).map(i=>i[t]).join("; "),r=e.length-WV;return r<=0?n:t==="de"?`${n} und ${r} weitere`:`${n} and ${r} more`}s(YV,"listed");function HV(e,t){let n=e.testScenarios??[];if(n.length===0)return[];let r=_F(e).filter(mo),i=r.length===0?[{}]:t??[];if(r.length>0&&t===void 0)return[{severity:"warning",path:"testScenarios",code:"scenario.unjudged",message:{de:`Die Testszenarien werden hier nicht gepr\xFCft: das Formular liest ${r.join(", ")}, und welche Klassenstufen und Schuljahre das Angebot hat, ist hier nicht bekannt \u2014 die Ver\xF6ffentlichung pr\xFCft sie.`,en:`The test scenarios are not judged here: the form reads ${r.join(", ")}, and which grades and school years the offer has is not known here \u2014 publishing judges them.`}}];if(i.length===0)return[{severity:"warning",path:"testScenarios",code:"scenario.no-environment",message:{de:"Das Angebot hat noch keine Klassenstufe mit Schuljahr \u2014 die Testszenarien sind gegen keine Umgebung gepr\xFCft. Nach dem Anlegen erneut ver\xF6ffentlichen.",en:"The offer has no grade with a school year yet \u2014 the test scenarios are judged against no environment. Publish again once one exists."}}];let{compiled:o}=Ka(e),a=[];for(let l of n){let d=l.prefill??{},c=new Map,u=s((p,h)=>{let y=`${p.path}\0${p.message.de}`,b=c.get(y);b===void 0?c.set(y,{...p,where:[h]}):b.where.some(k=>k.de===h.de)||b.where.push(h)},"add");for(let p of i){let h=OF(p,r),{visible:y}=KV(o,d,h),b=VV(o,y,h,{exemptFromRequired:["docRef"]}),k=zV(p);for(let v of b.issues){if(v.code==="no-outcome"){u({path:`scenario:${l.id}`,code:"scenario.no-outcome",message:{de:`Szenario "${l.label.de}" erreicht kein g\xFCltiges Outcome \u2013 der Testfall ist nicht absendbar.`,en:`Scenario "${l.label.en}" reaches no valid outcome \u2013 the test case cannot be submitted.`}},k);continue}if(v.code==="required"){u({path:`scenario:${l.id}/${v.fieldKey}`,code:"scenario.required-field-unfilled",message:{de:`Szenario "${l.label.de}" l\xE4sst das Pflichtfeld ${v.fieldKey} unbef\xFCllt \u2013 kein g\xFCltiges Outcome.`,en:`Scenario "${l.label.en}" leaves the required field ${v.fieldKey} empty \u2013 no valid outcome.`}},k);continue}u({path:`scenario:${l.id}/${v.fieldKey}`,code:"scenario.invalid-value",message:sd([l.label,v.text],([A,T],I)=>I==="de"?`Szenario "${A}": ${T}`:`Scenario "${A}": ${T}`)},k)}}for(let p of c.values())a.push({severity:"error",path:p.path,code:p.code,message:r.length===0?p.message:{de:`${p.message.de} \u2014 in: ${YV(p.where,"de")}`,en:`${p.message.en} \u2014 in: ${YV(p.where,"en")}`}})}return a}s(HV,"validateScenarios");function dg(e){return e.filter(t=>(t.severity??"error")==="error")}s(dg,"blockingIssues");function cg(e,t={}){return[...OV(e,t),...HV(e,t.scenarioEnvironments)]}s(cg,"runFormValidators");function ug(e){return dg(e)}s(ug,"blockingFormErrors");function JV(e,t,n){return HL(e,t,n)}s(JV,"runWorkflowValidators");function QV(e){return dg(e)}s(QV,"blockingWorkflowErrors");var DX=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"];var ZV={join:{required:[],optional:[]},end:{required:[],optional:[]},eventTrigger:{required:[],optional:[]},form:{required:[],optional:["adoptForm","formExports"]},roleAssign:{required:[],optional:[]},setFlag:{required:[],optional:[]},if:{required:["condition"],optional:[]},countersign:{required:["contract"],optional:["signing","titles"]},engagePush:{required:["form"],optional:["contract","engage","payment"]},decision:{required:[],optional:["commentRequired","decisionAsTask","reads","requiresOneOf","view"]},review:{required:[],optional:["commentRequired","decisionAsTask","form"]},waitlist:{required:[],optional:[]},completenessCheck:{required:["deadline","requires"],optional:[]},collectPayment:{required:[],optional:[]},governedDocument:{required:["approval","production","responseStrategy"],optional:["confirmBeforeIssue","confirmContractTerms","contractTermsQuestionText","form","generatorStamp","reads","responseLabels","templateStamp","titles"]}},Rn={id:m.string(),label:Ui,actionTeams:m.optional(m.any()),artifacts:m.optional(m.any()),assign:m.optional(m.any()),inputs:m.optional(m.any()),library:m.optional(m.any()),next:m.optional(m.any()),notifications:m.optional(m.any()),optionalActions:m.optional(m.any()),outcomes:m.optional(m.any()),outputLabels:m.optional(m.any()),sublabel:m.optional(m.any()),tasks:m.optional(m.any())},FX=m.object({...Rn,type:m.literal("join")}),LX=m.object({...Rn,type:m.literal("end")}),MX=m.object({...Rn,type:m.literal("eventTrigger")}),qX=m.object({...Rn,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),KX=m.object({...Rn,type:m.literal("roleAssign")}),jX=m.object({...Rn,type:m.literal("setFlag")}),VX=m.object({...Rn,type:m.literal("if"),condition:m.optional(m.any())}),BX=m.object({...Rn,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),UX=m.object({...Rn,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),GX=m.object({...Rn,type:m.literal("decision"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),reads:m.optional(m.any()),requiresOneOf:m.optional(m.any()),view:m.optional(m.any()),formView:m.optional(m.any())}),zX=m.object({...Rn,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),WX=m.object({...Rn,type:m.literal("waitlist")}),YX=m.object({...Rn,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),HX=m.object({...Rn,type:m.literal("collectPayment")}),JX=m.object({...Rn,type:m.literal("governedDocument"),approval:m.optional(m.any()),confirmBeforeIssue:m.optional(m.any()),confirmContractTerms:m.optional(m.any()),contractTermsQuestionText:m.optional(m.any()),form:m.optional(m.any()),generatorStamp:m.optional(m.any()),production:m.optional(m.any()),reads:m.optional(m.any()),responseLabels:m.optional(m.any()),responseStrategy:m.optional(m.any()),templateStamp:m.optional(m.any()),titles:m.optional(m.any())}),OGe=m.union(FX,LX,MX,qX,KX,jX,VX,BX,UX,GX,zX,WX,YX,HX,JX);function XV(e){let t=[];return e.forEach((n,r)=>{if(n===null||typeof n!="object"||Array.isArray(n)){t.push(`graph.nodes[${r}]: a node must be an object`);return}let i=n,o=`graph.nodes[${r}]${typeof i.id=="string"?` (${i.id})`:""}`;(typeof i.id!="string"||i.id==="")&&t.push(`${o}: \`id\` must be a non-empty string`);let a=i.type;if(typeof a!="string"||!(a in ZV)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=ZV[a],d=new Set(["id","type","label",...DX,...l.required,...l.optional]);for(let c of Object.keys(i))d.has(c)||t.push(`${o}: \`${c}\` is not a field of a ${a} node. Delete the line.`)}),t}s(XV,"workflowNodeEnvelopeIssues");var eB=s(e=>e,"asEffectId"),No=s(e=>e,"asOutcomeId"),fl=s(e=>e,"asSectionId"),yn=s(e=>e,"asFieldKey");var jr=["string","boolean","consent","date","enum","email","tel","address","docRef"],Cc=["person","organization","relationship","fieldMap"],Po=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],pl=["fresh","keyed","manual"];function Cs(e,t,n,r){if(e===void 0||e===""){if(t!==void 0&&t!=="")throw new g(`${n}: ${r}-en needs ${r} too`);return}return pt(e,t,n,r)}s(Cs,"optionalLocalizedText");function ln(e,t){if(!(e===void 0||e===""))try{Mt(e)}catch(n){throw new g(`offer form: ${t} is not a valid expression: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}s(ln,"assertExpression");function Dc(e){return Object.keys(e.smartforms??{})}s(Dc,"carriedFormSlugs");function vA(e){let n=e.workflow?.graph?.nodes??[],r=[];for(let i of n){if(i.type!=="form")continue;let o=i.inputs?.smartForm;o?.kind==="literal"&&typeof o.value=="string"&&o.value&&r.push(o.value)}return r}s(vA,"boundFormSlugs");function fg(e,t){let n=Dc(e);if(t){if(!n.includes(t))throw new g(`offer form: no smartform "${t}" in this bundle (have: ${n.join(", ")||"none"})`);return t}if(n.length===0)throw new g("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(n.length>1)throw new g(`offer form: bundle carries ${n.length} smartforms \u2014 pass --form <key> (one of: ${n.join(", ")})`);return n[0]}s(fg,"resolveFormSlug");function pg(e,t){let n=e.smartforms?.[t];if(!n)throw new g(`offer form: smartform "${t}" not found in bundle`);return n}s(pg,"getForm");function nr(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(nr,"walkSections");function vr(e,t){return nr(e).find(n=>n.id===t)}s(vr,"findSection");function Ds(e,t){for(let n of nr(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Ds,"findField");function Fs(e){let t=new Set;for(let n of nr(e))n.fields.forEach(r=>t.add(r.key)),n.groups?.forEach(r=>r.fields.forEach(i=>t.add(i.key))),n.repeated?.forEach(r=>r.itemTemplate.forEach(i=>t.add(i.key))),n.computed?.forEach(r=>t.add(r.key));return t}s(Fs,"allFieldKeys");function QX(e){let t=pt(e.label,e.labelEn,"offer form add"),n={id:fl("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:No("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(QX,"buildSkeletonSmartForm");function mg(e,t){let{key:n,label:r}=t;if(Dc(e).includes(n))throw new g(`offer form add: smartform "${n}" already exists in this bundle`);let i=QX({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(mg,"addForm");function tB(e,t){if(!Dc(e).includes(t))throw new g(`offer form rm: smartform "${t}" not found in bundle`);if(vA(e).includes(t))throw new g(`offer form rm: smartform "${t}" is still bound by a form node \u2014 remove the form node first (offer workflow node rm), then the form`);return delete e.smartforms[t],e.index.smartforms&&delete e.index.smartforms[t],t}s(tB,"removeForm");function nB(e,t){let n=pg(e,t.slug);if(t.label===void 0&&t.labelEn===void 0)throw new g("offer form set: nothing to change \u2014 pass --label/--label-en");if(t.label==="")throw new g("offer form set: --label cannot be empty");St(n,"label",{de:t.label,en:t.labelEn},"offer form set")}s(nB,"setForm");function rB(e,t){let n=e.workflow?.graph?.nodes;if(!Array.isArray(n))throw new g(`${t}: the bundle carries no workflow graph (workflow.json)`);return n}s(rB,"nodesOf");function iB(e,t,n){let r=rB(e,n),i=r.find(o=>o.id===t);if(i===void 0)throw new g(`${n}: no node "${t}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(iB,"nodeOf");function oB(e){return e.flatMap(t=>{if(t.type!=="form"||Pn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(oB,"creatingFormNodes");function sB(e){return ug(cg(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(sB,"formErrors");function hg(e){let t="offer workflow restamp-exports",n=rB(e,t),r=[];for(let{node:i,slug:o}of oB(n)){let a=e.smartforms?.[o];if(a===void 0)throw new g(`${t}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=sB(l);if(d.length>0)throw new g(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
11851
11851
  ${d.join(`
11852
11852
  `)}`);let c=Gk(l),u=Array.isArray(i.formExports)?i.formExports.map(h=>h.key):null,p=i.formExports===void 0||Ce(i.formExports)!==Ce(c);i.formExports=c,r.push({node:i.id,form:o,before:u,after:c.map(h=>h.key),changed:p})}for(let i of n)if(i.type==="form"&&Pn(i)&&"formExports"in i){let o=i.formExports?.map(a=>a.key)??null;delete i.formExports,r.push({node:i.id,form:"(adoptForm)",before:o,after:[],changed:!0})}return r}s(hg,"restampFormExports");function aB(e){let t=e.workflow?.graph?.nodes??[];return oB(t).flatMap(({node:n,slug:r})=>{if(n.formExports===void 0)return[];let i=e.smartforms?.[r];if(i===void 0)return[];let o=i;return sB(o).length>0?[]:Ce(n.formExports)===Ce(Gk(o))?[]:[{node:n.id,form:r}]})}s(aB,"staleFormExports");var xA=["string","number","boolean","date"];function lB(e,t){let n="offer form field export";for(let r of nr(e)){let i=[...r.fields,...(r.groups??[]).flatMap(a=>a.fields)].find(a=>a.key===t.key);if(i!==void 0){if(t.type!==void 0)throw new g(`${n}: --type is for a computed field; "${t.key}" is an entered ${i.type} field and exports as its own type`);if(t.on&&!dm(i.type))throw new g(`${n}: "${t.key}" is a ${i.type} field \u2014 that type has no exported value (export.invalid-type)`);if(t.on&&i.multiple===!0)throw new g(`${n}: "${t.key}" is a multi-select \u2014 N picked options are no single leaf (export.multiple-enum)`);let a=i.export===!0,l=i;return t.on?l.export=!0:delete l.export,{kind:"field",before:a,after:t.on}}let o=(r.computed??[]).find(a=>a.key===t.key);if(o!==void 0){let a=o.export===!0,l=o;if(!t.on){if(t.type!==void 0)throw new g(`${n}: --type goes with an export, not with --off`);return delete l.export,delete l.exportType,{kind:"computed",before:a,after:!1}}let d=t.type??o.exportType;if(d===void 0)throw new g(`${n}: "${t.key}" is a computed field \u2014 name its type with --type (${xA.join("|")}); an expression has none to infer`);if(!xA.includes(d))throw new g(`${n}: --type "${d}" is no computed export type (${xA.join("|")})`);return l.export=!0,l.exportType=d,{kind:"computed",before:a,after:!0}}if((r.repeated??[]).some(a=>a.itemTemplate.some(l=>l.key===t.key)))throw new g(`${n}: "${t.key}" sits in a repeated block \u2014 a row value is no per-application leaf (export.in-repeated)`)}throw new g(`${n}: the form has no field "${t.key}"`)}s(lB,"setFieldExport");function dB(e,t,n){let r="offer workflow node set-generator",i=iB(e,t,r);if(ng(i)!=="resolver")throw new g(`${r}: "${t}" generates no contract from a generator (${i.type==="governedDocument"?`production ${String(i.production)}`:String(i.type)}) \u2014 a pin belongs on a governedDocument with production resolver`);let a=n.key.trim();if(a==="")throw new g(`${r}: the ${n.kind} key is empty`);let l=Ti(i),d=l!==null&&l.key===a&&l.kind===n.kind&&l.revision===void 0,c=!d&&"generatorStamp"in i;c&&delete i.generatorStamp,i.inputs={...i.inputs??{},[en]:{kind:"literal",value:{kind:n.kind,key:a}}};let u=d?[]:Object.keys(i.inputs).filter(p=>p!==en&&p!==Jn);return{before:l,after:{key:a,kind:n.kind},droppedStamp:c,keptParameterCells:u}}s(dB,"setGeneratorPin");function cB(e,t,n){let r="offer workflow node set-cockpit-fields",i=iB(e,t,r),o=ng(i);if(o!=="resolver"&&o!=="template")throw new g(`${r}: "${t}" fills no document from a generator or a Word template (${i.type==="governedDocument"?`production ${String(i.production)}`:String(i.type)})`);if(!(o==="resolver"?Ti(i)!==null:_r(i)!==null))throw new g(o==="resolver"?`${r}: "${t}" names no generator yet \u2014 name one first (offer workflow node set-generator)`:`${r}: "${t}" names no Word template yet \u2014 name one first (inputs.documentTemplate)`);let l=new Set;for(let p of n){if(l.has(p))throw new g(`${r}: --fields names "${p}" twice`);l.add(p)}let d={...i.inputs??{}},c=Object.keys(d).filter(p=>d[p]?.kind==="cockpit"),u=n.flatMap(p=>{let h=d[p];return h===void 0||h.kind==="cockpit"||h.kind==="unset"?[]:[{field:p,cell:h}]});for(let p of c)l.has(p)||delete d[p];for(let p of n)d[p]={kind:"cockpit"};return i.inputs=d,{pin:o,before:c,after:[...n],replaced:u}}s(cB,"setCockpitFields");var ZX=new Set(["graph","progressLayout","progressWiring"]);function uB(e){let{label:t,...n}=e;return n}s(uB,"definitionOf");function XX(e){let t=[];for(let o of Object.keys(e))ZX.has(o)||t.push(`workflow.json: unknown key \`${o}\` \u2014 the file carries only graph, progressLayout, progressWiring. Delete the line.`);let n=e.graph;if(n===null||typeof n!="object"||Array.isArray(n))return t.push("workflow.json: `graph` must be an object."),t;for(let o of Object.keys(n)){if(yN.has(o))continue;let a=o==="id"||o==="label"?" (the title is the offer's, bundle.yaml `label`)":o==="dataFlow"?" (publish derives it)":"";t.push(`workflow.json: \`graph.${o}\` is no longer part of the workflow graph${a}. Delete the line.`)}let r=n;Array.isArray(r.nodes)?t.push(...XV(r.nodes).map(o=>`workflow.json: ${o}`)):t.push("workflow.json: `graph.nodes` must be a list."),r.assignmentRules===void 0&&t.push("workflow.json: `graph.assignmentRules` is required (who becomes responsible).");let i=e.progressWiring;return i!=null&&typeof i=="object"&&"layoutId"in i&&t.push("workflow.json: `progressWiring.layoutId` is no longer part of the wiring (the layout is the workflow's own). Delete the line."),t}s(XX,"workflowShapeIssues");function fB(e){let t=e.nodes??[],n=new Map;for(let r of t){let i=oP(r);i!==void 0&&n.set(r.id,i)}return n}s(fB,"formNodeSlugById");function e7(e,t){let n=e.smartforms??{},r=new Map;for(let[i,o]of fB(t)){let a=n[o];if(a===void 0)return;r.set(i,uB(a))}return qF(r)}s(e7,"readinessContext");function t7(e){return[...fB(e).values()]}s(t7,"formNodeSlugs");function gg(e){let t=e.code?`[${e.code}] `:"",n=e.path?`${e.path}: `:"",r=e.reason??e.message;return`${t}${n}${r===void 0?JSON.stringify(e):r.de}`}s(gg,"describe");function jn(e){let t=[];for(let l of Fp(e.manifest))t.push({severity:"error",area:"manifest",message:l});let n=Ft(e.index.label);(n==="not-localized"||n.length>0)&&t.push({severity:"error",area:"manifest",message:`[i18n/missingTranslation] bundle.yaml label fehlt in: ${n==="not-localized"?"de, en":n.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`});let{manifest:r,workflow:i}=e.index.slugs;i!==void 0&&i!==r&&t.push({severity:"error",area:"workflow",message:`slugs.workflow '${i}' must equal slugs.manifest '${r}' \u2014 the workflow belongs to the offer family, and export writes the family key`});for(let l of xp(e.index.program?.stages??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of vp(e.index.program?.runs??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of Mh(e.index.program?.runs??[],e.index.program?.stages?.map(d=>d.key)))t.push({severity:"error",area:"program",message:l});if(e.workflow!==void 0){for(let A of XX(e.workflow))t.push({severity:"error",area:"workflow",message:A});let l=e.workflow.graph,d=e.workflow.progressLayout,c=e.workflow.progressWiring;if(d!==void 0)for(let A of gN(d))t.push({severity:"error",area:"workflow",message:A});let u=[];for(let{node:A,key:T,kind:I}of rg(e))A.generatorStamp?.schemaDigest===void 0&&(u.push(A.id),t.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped] Knoten "${A.id}" pinnt ${I}:${T} ohne Stempel \u2014 ob er \u201Econtract\u201C oder \u201Econtracts\u201C liefert und welche Parameter er hat, pr\xFCft erst \`offer plan\` (stempelt den Pin von der Umgebung).`}));for(let A of l.nodes)A.type!=="governedDocument"||A.production!=="template"||A.templateStamp!==void 0||t.push({severity:"warning",area:"workflow",message:`[template/notStamped] Knoten "${A.id}" f\xFCllt die Vorlage ${_r(A)??"\u2014"} ohne ihre Parameter \u2014 welche Felder sie hat, pr\xFCft erst \`offer plan\` (stempelt sie vom Vorlagen-Datensatz der Umgebung).`});for(let{node:A,form:T}of aB(e))t.push({severity:"warning",area:"workflow",message:`[formExports/stale] Knoten "${A}": der Stempel formExports passt nicht mehr zum Formular "${T}" \u2014 die Adresspr\xFCfung liest den alten Stand; \`offer workflow restamp-exports\` stempelt ihn neu (publish tut es ohnehin).`});let p=e.index.program?.stages?.map(A=>A.key),h={...e7(e,l),...p===void 0?{}:{stageKeys:new Set(p)}},y=s(A=>{let T=JV(A,{layout:d,wiring:c},h),I=new Set(QV(T));return{issues:T,isError:s(C=>I.has(C)||(C.severity??"error")==="error","isError")}},"blockingOf"),{issues:b,isError:k}=y(l),v=new Set;if(u.length>0){let A=structuredClone(l);for(let L of A.nodes)u.includes(L.id)&&(L.generatorStamp={...L.generatorStamp??{},parts:[{partKey:"?"}]});let T=y(A),I=new Set(T.issues.filter(T.isError).map(gg)),C=s(L=>u.some(N=>L.includes(`$node.${N}.contract`)),"namesOutput");for(let L of b){let N=gg(L);k(L)&&!I.has(N)&&C(N)&&v.add(N)}}for(let A of b){let T=gg(A);if(v.has(T)){t.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped \u2192 offer plan] ${T}`});continue}t.push({severity:k(A)?"error":"warning",area:"workflow",message:T})}}let o=e.index.program?.stages,a=o===void 0?void 0:new Set(o.map(l=>l.key));for(let[l,d]of Object.entries(e.smartforms??{})){let c=Ft(d.label);(c==="not-localized"||c.length>0)&&t.push({severity:"error",area:"smartform",message:`${l}: [i18n/missingTranslation] \`label\` muss ein zweisprachiger Text ({ de, en }) sein.`});let u=uB(d);for(let k of wN(u,`smartforms/${l}.json`))t.push({severity:"error",area:"smartform",message:k.de});let p=u,h=n7(e,p),y=cg(p,{stageKeys:a,...h===void 0?{}:{scenarioEnvironments:h}}),b=new Set(ug(y));for(let k of y)t.push({severity:b.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${gg(k)}`});for(let k of[...lV(p),...aV(p)])t.push({severity:"error",area:"smartform",message:`${l}: [${k.code}] ${k.path}: ${k.message}`})}if(e.workflow!==void 0){let l=e.workflow.graph,d=new Set(t7(l)),c=new Set(Object.keys(e.smartforms??{}));for(let u of d)c.has(u)||t.push({severity:"error",area:"consistency",message:`form node binds smartForm "${u}" but the bundle carries no smartforms/${u}.json`});for(let u of c)d.has(u)||t.push({severity:"warning",area:"consistency",message:`smartform "${u}" is carried but no form node binds it`})}return t}s(jn,"validateBundle");function n7(e,t){let n=(t.env??[]).filter(d=>mo(d));if(n.length===0)return[{}];if(n.includes("offer")||n.includes("unit"))return;let r=e.index.program,i=r?.stages,o=r?.runs;if(n.includes("stage")&&i===void 0||n.includes("run")&&o===void 0)return;let a=n.includes("applicant")?UV():[{language:null,channel:"staff"}],l=[];for(let d of a){let c=d.language??"de",u=s(y=>({key:y.key,name:y.name[c],gradeLevel:y.gradeLevel??null}),"stageOf"),p=s(y=>({key:y.key,name:y.name[c],startDate:y.startDate??null}),"runOf"),h=[];if(i!==void 0&&o!==void 0)for(let y of o){let b=y.capacities===void 0?i:i.filter(k=>y.capacities[k.key]!==void 0);for(let k of b)h.push({stage:u(k),run:p(y)})}else if(i!==void 0)for(let y of i)h.push({stage:u(y)});else if(o!==void 0)for(let y of o)h.push({run:p(y)});else h.push({});for(let y of h)l.push({...y,applicant:d})}return GV(l,n)}s(n7,"bundleScenarioEnvironments");async function SA(e,t,n){let r=rg(n);if(r.length===0)return{rows:[],issues:[]};let i=[...new Map(r.map(({key:c,kind:u,revision:p})=>[`${u}:${c}:${p??"current"}`,{key:c,kind:u,...p===void 0?{}:{revision:p}}])).values()],o=await e.query(S.workflow.getResolverPinStamps,{client:t,unitKey:n.index.links?.unitKey??null,pins:i}).catch(c=>{throw c instanceof Error&&c.message.includes("Could not find public function")?Lt(c,()=>`offer: ${e.convexUrl} has no workflow:getResolverPinStamps \u2014 that deployment is older than this CLI; release it first (or use a CLI of its release).`):c}),a=new Map(o.map(c=>[`${c.kind}:${c.key}:${c.revision??"current"}`,c])),l=[],d=[];for(let{node:c,key:u,kind:p,revision:h}of r){let y=a.get(`${p}:${u}:${h??"current"}`);if(y===void 0)throw new Error(`offer: the environment answered no stamp for ${p}:${u}`);if(y.stamp===null){if(y.refusal===null)throw new Error(`offer: the environment answered neither a stamp nor a refusal for ${p}:${u}`);d.push({severity:"error",area:"workflow",message:`[resolver/pinRefused] Knoten "${c.id}": ${y.refusal.de}`});continue}hN(c,structuredClone(y.stamp),{freezeRevision:!0}),l.push({target:`stamp:${c.id}`,detail:y.stamp.parts===void 0?`${p}:${u} Dokument`:`${p}:${u} kombiniert (${y.stamp.parts.map(b=>b.partKey).join(", ")})`})}return{rows:l,issues:d}}s(SA,"stampResolverPins");async function AA(e,t,n){let r=(n.workflow?.graph?.nodes??[]).filter(d=>d.type==="governedDocument"&&d.production==="template"),i=[...new Set(r.flatMap(d=>{let c=_r(d);return c===null?[]:[c]}))];if(i.length===0)return{rows:[],issues:[]};let o=new Map((await e.query(S.workflow.getTemplateStamps,{client:t,keys:i})).map(d=>[d.key,d])),a=[],l=[];for(let d of r){let c=_r(d);if(c===null)continue;let u=o.get(c);if(u===void 0)throw new Error(`offer: the environment answered nothing for template ${c}`);if(ej(d,u.parameters),u.parameters!==null){a.push({target:`stamp:${String(d.id)}`,detail:`template:${c} (${u.parameters.fields.length} Parameter)`});continue}l.push({severity:"error",area:"workflow",message:u.exists?`[governedDocument/templateWithoutParameters] Knoten "${String(d.id)}": die Vorlage ${c} deklariert keine Parameter (plexus-cli catalog apply, documentTemplates[].parameters).`:`[governedDocument/unknownTemplate] Knoten "${String(d.id)}": eine Vorlage ${c} gibt es in dieser Umgebung nicht.`})}return{rows:a,issues:l}}s(AA,"stampTemplatePins");async function pB(e,t,n){let r=je(n),i=await SA(e,t,r),o=await AA(e,t,r),a=[...i.rows,...o.rows],l=[...i.issues,...o.issues];if(l.length>0)return{rows:a,refused:l,open:[]};if(a.length===0)throw new g("offer workflow restamp-pins: the bundle pins no contract generator or package (offer workflow node set-generator) and fills no Word template");Mn(r);let d=a.map(p=>p.target.slice(6)),c=s(p=>d.some(h=>p.includes(`nodes.${h}.`)||p.includes(`node.${h}.`)||p.includes(`"${h}"`)),"onStamped"),u=jn(r).filter(p=>p.severity==="error"&&c(p.message));return{rows:a,refused:[],open:u}}s(pB,"restampPinsOnDisk");var r7=H.join("contract","resolver-setup.json"),gi="resolver setup",ml=s((e,t)=>Bt(e,t,gi),"record"),Co=s((e,t)=>Qe(e,t,gi),"text");function i7(e,t){let n=ml(e,"Datei"),r=ml(n.contractTemplate,"contractTemplate"),i=ml(n.resolver,"resolver");return{dir:t,contractTemplate:{key:Co(r.key,"contractTemplate.key"),name:Tn(r.name,"contractTemplate.name",gi,"Vorlagennamen"),file:Co(r.file,"contractTemplate.file"),role:Co(r.role,"contractTemplate.role")},revenueAccounts:ah(n.revenueAccounts,gi),billingItems:lh(n.billingItems,gi),resolver:{key:Co(i.key,"resolver.key"),name:Tn(i.name,"resolver.name",gi,"Generatornamen"),description:i.description===void 0?null:Tn(i.description,"resolver.description",gi,"Beschreibungen"),legalText:i.legalText??{},source:Co(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:Zn(i.feeGroups,"resolver.feeGroups",gi)).map((o,a)=>{let l=ml(o,`resolver.feeGroups[${a}]`);return{key:Co(l.key,"feeGroup.key"),name:Tn(l.name,"feeGroup.name",gi,"Geb\xFChrengruppen"),billingItemKeys:TA(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:TA(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:TA(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:o7(i.scenarios??[]),config:ml(i.config,"resolver.config")}}}s(i7,"parseResolverSetup");function TA(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||n.trim()==="")||new Set(e).size!==e.length)throw new g(`generator setup: ${t} must be a list of unique keys.`);return e}s(TA,"stringList");function o7(e){if(!Array.isArray(e)||e.length>20)throw new g("generator setup: scenarios must be a list of at most 20 reviewed examples.");return e.map(t=>{let n=ml(t,"scenario");if(!("input"in n)||!("expected"in n))throw new g("generator setup: each scenario needs input and reviewed expected output.");return{key:Co(n.key,"scenario.key"),input:n.input,expected:n.expected}})}s(o7,"parseScenarios");function yg(e){let t=H.resolve(e);return i7(Be(t,gi),H.dirname(t))}s(yg,"readResolverSetup");function s7(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!(r in n))throw new g(`resolver setup: resolver.config.${t} existiert nicht.`);n=n[r]}return n}s(s7,"configValue");function mB(e){let t=s(()=>Co(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),n=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...RA(e.resolver.config),...e.resolver.billingItemKeys])].filter(r=>!n.has(r)),billingItems:e.billingItems.map(r=>{if(r.programs!==void 0)throw new g(`resolver setup: Artikel ${r.key}: "programs" verwaltet nur die Katalog-Datei (plexus-cli catalog), nicht resolver-setup.json.`);if("tree"in r.price)throw new g(`resolver setup: Artikel ${r.key}: Tarife werden im Katalog verwaltet.`);let i=r.price.amount,o=typeof i=="object"&&i!==null&&typeof i.$config=="string"?s7(e.resolver.config,i.$config):i;if(typeof o!="number"||!Number.isFinite(o))throw new g(`resolver setup: Artikel ${r.key}: Preis ist keine Zahl (${JSON.stringify(i)}).`);return{key:r.key,name:r.name,itemType:r.itemType,revenueAccountCode:r.revenueAccount,taxTreatment:r.taxTreatment,config:r.config,price:{amount:o,currency:r.price.currency,effectiveFrom:t(),period:r.price.period}}})}}s(mB,"billingSetupPayload");function hB(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=Object.entries(e);if(t.length!==1||t[0][0]!=="$billingItem")return;let n=t[0][1];if(typeof n!="string")throw new g(`resolver setup: $billingItem ${JSON.stringify(n)} ist kein Schl\xFCssel.`);return n}s(hB,"billingItemRef");function RA(e){if(Array.isArray(e))return e.flatMap(RA);if(typeof e!="object"||e===null)return[];let t=hB(e);return t!==void 0?[t]:Object.values(e).flatMap(RA)}s(RA,"billingItemRefs");function $A(e,t,n={}){let r=s(i=>{if(Array.isArray(i))return i.map(r);if(typeof i=="object"&&i!==null){let o=Object.entries(i);if(o.length===1&&o[0][0]==="$grantTemplate"){let l=o[0][1];if(typeof l!="string"||n[l]===void 0)throw new g(`generator setup: grant template ${String(l)} is not declared.`);return n[l]}let a=hB(i);if(a!==void 0){if(!(a in t))throw new g(`resolver setup: $billingItem "${a}" ist weder in billingItems deklariert noch ein Katalogartikel.`);return t[a]}return Object.fromEntries(Object.entries(i).map(([l,d])=>[l,r(d)]))}return i},"walk");return r(e)}s($A,"renderResolverConfig");function a7(e,t){let n=Array.isArray(e.documentPlaceholderKeys)?e.documentPlaceholderKeys:[],r=new Set(t.placeholders),i=new Set(n.map(String)),o=[...r].filter(l=>!i.has(l)),a=[...i].filter(l=>!r.has(l));if(o.length>0||a.length>0)throw new g("resolver setup: resolver.config.documentPlaceholderKeys weicht vom DOCX ab"+(o.length>0?` \u2014 fehlt: ${o.join(", ")}`:"")+(a.length>0?` \u2014 nicht im DOCX: ${a.join(", ")}`:"")+". Liste aus dem DOCX \xFCbernehmen.")}s(a7,"assertPlaceholderParity");function l7(e,t){let n=[...e].filter(r=>r.status==="sealed").sort((r,i)=>i.versionNumber-r.versionNumber)[0];if(n!==void 0)return n.coverLetter===void 0&&n.source===t.source&&n.pinnedDocumentTemplateId===t.documentTemplateId&&Ce(n.config)===Ce(t.config)&&Ce(n.legalText)===Ce(t.legalText)&&Ce([...n.billingItemDefinitionIds].sort())===Ce([...t.billingItemDefinitionIds].sort())&&Ce([...n.grantTemplateIds].sort())===Ce([...t.grantTemplateIds].sort())&&Ce(n.feeGroups)===Ce(t.feeGroups)?n:void 0}s(l7,"matchingSealedRevision");async function Fc(e,t,n){if(n.resolver.source===null)throw new g("generator setup requires a self-contained source file.");let r=Ne(H.join(n.dir,n.resolver.source),"utf8"),i=await zd(H.join(n.dir,n.contractTemplate.file));a7(n.resolver.config,i);let o=await e.query(S.contractSetup.planBillingSetup,{client:t,...mB(n)}),a=await e.query(S.contractSetup.wordTemplateState,{client:t,configKey:n.contractTemplate.key}),l=a===null||a.sha256!==i.sha256,d=await e.query(S.contractConfig.model,{client:t}),c={};for(let T of n.resolver.grantTemplateKeys){let I=d.grantTemplates.find(C=>C.configKey===T);if(I===void 0)throw new g(`Unknown grant template ${T}`);c[T]=I.id}let u=$A(n.resolver.config,o.billingItemIds,c),h=(await e.query(S.contractGeneratorVersions.model,{client:t})).find(T=>T.definition.key===n.resolver.key),y=h?.currentRevisionId?await e.query(S.contractGeneratorVersions.detail,{client:t,id:h.currentRevisionId}):null,b=h?.revisions.find(T=>T.status==="draft"),k=b?await e.query(S.contractGeneratorVersions.detail,{client:t,id:b.id}):null,v=l||y===null?void 0:l7([y],{source:r,config:u,legalText:n.resolver.legalText,documentTemplateId:a.id,billingItemDefinitionIds:n.resolver.billingItemKeys.map(T=>o.billingItemIds[T]??`not-created:${T}`),grantTemplateIds:Object.values(c),feeGroups:n.resolver.feeGroups.map(T=>({key:T.key,name:T.name,billingItemDefinitionIds:T.billingItemKeys.map(I=>o.billingItemIds[I]??`not-created:${I}`)}))}),A=o.rows.map(T=>({step:T.kind,target:T.key,action:T.action,detail:T.detail}));return A.push({step:"wordTemplate",target:n.contractTemplate.key,action:l?"create":"same",detail:H.basename(i.file)}),A.push({step:"generatorVersion",target:n.resolver.key,action:v?"same":"create",detail:v?`Current sealed revision ${v.versionNumber}`:"Save source, review scenarios and seal a new revision"}),{rows:A,docx:i,source:r,renderedConfig:u,billingItemIds:o.billingItemIds,grantTemplateIds:c,head:h,current:y,draft:k,match:v,template:{documentTemplateId:a?.id??null,upload:l}}}s(Fc,"planResolverSetup");async function gB(e,t,n){let r=await Fc(e,t,n);if(r.rows.every(p=>p.action==="same"))return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}};if(!r.match&&n.resolver.scenarios.length===0)throw new g("A new generator revision requires reviewed scenarios.");let i=await e.mutation(S.contractSetup.applyBillingSetup,{client:t,...mB(n)});if(r.match)return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}};let o=r.template.upload?await sh(e,t,r.docx,{name:n.contractTemplate.name,role:n.contractTemplate.role,configKey:n.contractTemplate.key}):r.template.documentTemplateId,a=r.draft?._id;if(a===void 0)if(r.head===void 0)a=(await e.mutation(S.contractGeneratorVersions.create,{client:t,key:n.resolver.key,name:n.resolver.name,description:n.resolver.description??{de:"",en:""}})).revisionId;else{if(r.current===null)throw new Error("Generator has neither draft nor sealed revision.");a=await e.mutation(S.contractGeneratorVersions.cloneDraft,{client:t,id:r.current._id})}let l=await e.query(S.contractGeneratorVersions.detail,{client:t,id:a}),d=await e.mutation(S.contractGeneratorVersions.save,{client:t,id:a,expectedSourceRevision:l.sourceRevision,config:$A(n.resolver.config,i.billingItemIds,r.grantTemplateIds),legalText:n.resolver.legalText,documentTemplateId:o}),c=await e.action(S.contractGeneratorVersionActions.saveSource,{client:t,id:a,expectedSourceRevision:d,source:r.source,billingItemDefinitionIds:n.resolver.billingItemKeys.map(p=>i.billingItemIds[p]),grantTemplateIds:Object.values(r.grantTemplateIds),feeGroups:n.resolver.feeGroups.map(p=>({key:p.key,name:p.name,billingItemDefinitionIds:p.billingItemKeys.map(h=>i.billingItemIds[h])}))});if(c.diagnostics.length>0)throw new g(`generator setup: the source does not compile:
11853
11853
  ${c.diagnostics.join(`
@@ -12033,7 +12033,7 @@ ${n.length} unusable ${o}:
12033
12033
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
12034
12034
  `),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>
12035
12035
  `)}else this.context.stdout.write(`No unusable identities.
12036
- `);return n.length>0?1:0}},PE=class extends Tr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=E.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=f.String({required:!0});async execute(){let n=await(await this.caller()).mutation(S.platformAdmin.relinkAuthAccount,{email:this.email}),r=n.changed?`Relinked ${this.email} to live auth account ${n.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(n,r),0}};function Uz(e,t){if(e===t)throw new g("Pass exactly one of --on or --off.");return e}s(Uz,"requireOnOff");var Gz=[gE,yE,wE,kE,bE,vE,xE,SE,AE,TE,af,RE,$E,EE,IE,OE,_E,NE,PE];function zz(e){return e.de??e.en??Object.values(e)[0]??""}s(zz,"titleDe");function Lte(e){return{id:e._id,kind:e.kind,status:e.status,title:zz(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(Lte,"row");var Mte=["id","kind","status","title","assignee","group","outcome"],FE=class extends P{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=E.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=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 t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:ee(this.application,"application")}:{},...this.group?{queueGroupId:ee(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:ee(this.assignee,"user")}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(Lte),Mte),0}},LE=class extends P{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=E.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.get,{client:n,workItemId:ee(this.workItemId,"work item")});if(r===null)throw new g(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:zz(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}},ME=class extends P{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=E.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 t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:ee(this.application,"application")}:{},...this.group?{queueGroupId:ee(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:ee(this.assignee,"user")}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},qE=class extends P{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=E.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=f.String({required:!0,name:"workItemId"});outcome=f.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.complete,{client:n,workItemId:ee(this.workItemId,"work item"),...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}},KE=class extends P{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=E.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=f.String({required:!0,name:"workItemId"});user=f.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.assign,{client:n,workItemId:ee(this.workItemId,"work item"),...this.user?{userId:ee(this.user,"user")}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},Wz=[FE,LE,ME,qE,KE];var Tl=[...D_,...oM,...mM,...bq,...Aq,...kq,...Jq,...rK,...nK,...Vz,...Gz,...jz,...xG,...EG,...PG,...B0,...zq,...Iz,...N_,...uN,...E0,...sK,...oK,...dK,...fK,...Uq,...Oq,...Wz,...PB,...xU,...bG,...SU,...pz,...bz,...CG,...BG,...zG,...JG,...ZG,...Sz,...Cz,...tN];for(let e of Tl){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:YI(e.usage.category,t.join(" "))})}var Yz="0.1.353";function jE(){return Tl.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=UI[Go(n)];return{path:n,effect:vi(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(jE,"plexusCommandCatalog");import js from"node:path";function qte(e){let t=mt()?.workspaceRoot??process.cwd(),n=js.resolve(t,e),r=js.relative(t,n);if(js.isAbsolute(e)||r===".."||r.startsWith(`..${js.sep}`))throw new g("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(qte,"workspacePath");function Kte(e){let{absolute:t,relative:n}=qte(e.path??".");if(e.operation==="list"){if(!Re(t))return{files:[]};let r=[],i=s(o=>{for(let a of zr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new g("plexus: workspace symlinks are not supported.");let l=js.join(o,a.name);if(a.isDirectory()?i(l):r.push(js.relative(t,l)),r.length>200)throw new g("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new g("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=Ne(t);if(r.length>10*1024*1024)throw new g("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new g("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new g("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new g("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 g("plexus: the edited file exceeds 10 MB.");return Ze(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new g("plexus: file content is missing or too large.");return Gt(js.dirname(t),{recursive:!0}),Ze(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Gs(t),{path:n,removed:!0};throw new g("plexus: unknown workspace operation.")}s(Kte,"plexusWorkspace");function Hz(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new g("plexus: tool input must be an object.");let i=r,o=od[n];if(!o||!Object.hasOwn(od,n))throw new g("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new g("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new g("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(Dw,i.path))throw new g("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:Dw[i.path],skillHash:kp}}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 g("plexus: invalid workspace input.");return Kte(i)},"executePlexusAgentTool")}s(Hz,"createPlexusAgentToolExecutor");var jte=["--env","--tenant"];function Jz(e){let t=[],n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i==="--"){t.push(...e.slice(r));break}let o=jte.find(l=>i===l||i.startsWith(`${l}=`)),a=e[r+1];o===void 0?t.push(i):i!==o?n.push({name:o,value:i.slice(o.length+1)}):a!==void 0&&!a.startsWith("-")?(n.push({name:o,value:a}),r++):t.push(i)}return{rest:t,given:n}}s(Jz,"splitGlobalOptions");function Qz(e,t){let n=Yy(e)==="offline";if(n&&vi(e)==="read")return t.map(i=>`plexus-cli: ${i.name} ${i.value} has no effect: \`${e}\` runs offline (this CLI's own files, no deployment).
12036
+ `);return n.length>0?1:0}},PE=class extends Tr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=E.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=f.String({required:!0});async execute(){let n=await(await this.caller()).mutation(S.platformAdmin.relinkAuthAccount,{email:this.email}),r=n.changed?`Relinked ${this.email} to live auth account ${n.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(n,r),0}};function Uz(e,t){if(e===t)throw new g("Pass exactly one of --on or --off.");return e}s(Uz,"requireOnOff");var Gz=[gE,yE,wE,kE,bE,vE,xE,SE,AE,TE,af,RE,$E,EE,IE,OE,_E,NE,PE];function zz(e){return e.de??e.en??Object.values(e)[0]??""}s(zz,"titleDe");function Lte(e){return{id:e._id,kind:e.kind,status:e.status,title:zz(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(Lte,"row");var Mte=["id","kind","status","title","assignee","group","outcome"],FE=class extends P{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=E.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=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 t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:ee(this.application,"application")}:{},...this.group?{queueGroupId:ee(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:ee(this.assignee,"user")}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(Lte),Mte),0}},LE=class extends P{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=E.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.get,{client:n,workItemId:ee(this.workItemId,"work item")});if(r===null)throw new g(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:zz(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}},ME=class extends P{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=E.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 t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:ee(this.application,"application")}:{},...this.group?{queueGroupId:ee(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:ee(this.assignee,"user")}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},qE=class extends P{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=E.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=f.String({required:!0,name:"workItemId"});outcome=f.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.complete,{client:n,workItemId:ee(this.workItemId,"work item"),...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}},KE=class extends P{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=E.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=f.String({required:!0,name:"workItemId"});user=f.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.assign,{client:n,workItemId:ee(this.workItemId,"work item"),...this.user?{userId:ee(this.user,"user")}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},Wz=[FE,LE,ME,qE,KE];var Tl=[...D_,...oM,...mM,...bq,...Aq,...kq,...Jq,...rK,...nK,...Vz,...Gz,...jz,...xG,...EG,...PG,...B0,...zq,...Iz,...N_,...uN,...E0,...sK,...oK,...dK,...fK,...Uq,...Oq,...Wz,...PB,...xU,...bG,...SU,...pz,...bz,...CG,...BG,...zG,...JG,...ZG,...Sz,...Cz,...tN];for(let e of Tl){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:YI(e.usage.category,t.join(" "))})}var Yz="0.1.354";function jE(){return Tl.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=UI[Go(n)];return{path:n,effect:vi(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(jE,"plexusCommandCatalog");import js from"node:path";function qte(e){let t=mt()?.workspaceRoot??process.cwd(),n=js.resolve(t,e),r=js.relative(t,n);if(js.isAbsolute(e)||r===".."||r.startsWith(`..${js.sep}`))throw new g("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(qte,"workspacePath");function Kte(e){let{absolute:t,relative:n}=qte(e.path??".");if(e.operation==="list"){if(!Re(t))return{files:[]};let r=[],i=s(o=>{for(let a of zr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new g("plexus: workspace symlinks are not supported.");let l=js.join(o,a.name);if(a.isDirectory()?i(l):r.push(js.relative(t,l)),r.length>200)throw new g("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new g("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=Ne(t);if(r.length>10*1024*1024)throw new g("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new g("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new g("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new g("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 g("plexus: the edited file exceeds 10 MB.");return Ze(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new g("plexus: file content is missing or too large.");return Gt(js.dirname(t),{recursive:!0}),Ze(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Gs(t),{path:n,removed:!0};throw new g("plexus: unknown workspace operation.")}s(Kte,"plexusWorkspace");function Hz(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new g("plexus: tool input must be an object.");let i=r,o=od[n];if(!o||!Object.hasOwn(od,n))throw new g("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new g("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new g("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(Dw,i.path))throw new g("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:Dw[i.path],skillHash:kp}}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 g("plexus: invalid workspace input.");return Kte(i)},"executePlexusAgentTool")}s(Hz,"createPlexusAgentToolExecutor");var jte=["--env","--tenant"];function Jz(e){let t=[],n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i==="--"){t.push(...e.slice(r));break}let o=jte.find(l=>i===l||i.startsWith(`${l}=`)),a=e[r+1];o===void 0?t.push(i):i!==o?n.push({name:o,value:i.slice(o.length+1)}):a!==void 0&&!a.startsWith("-")?(n.push({name:o,value:a}),r++):t.push(i)}return{rest:t,given:n}}s(Jz,"splitGlobalOptions");function Qz(e,t){let n=Yy(e)==="offline";if(n&&vi(e)==="read")return t.map(i=>`plexus-cli: ${i.name} ${i.value} has no effect: \`${e}\` runs offline (this CLI's own files, no deployment).
12037
12037
  `);let r=[...new Set(t.map(i=>i.name))].join(", ");throw new g(n?`\`${e}\` does not take ${r}: it never targets a chosen deployment \u2014 drop the option.`:`\`${e}\` does not take ${r}.`)}s(Qz,"globalOptionNotes");var ky=Hz({inspectCommand:Xz,executeCommand:eW});function by(){let e=new Hs({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:Yz});e.register(Ll.HelpCommand),e.register(Ll.VersionCommand);for(let r of Tl)e.register(r);function t(r,i){try{return{command:e.process(r,i),notes:[]}}catch(o){let{rest:a,given:l}=Jz(r);if(l.length===0)throw o;let d;try{d=e.process(a,i)}catch{throw o}if(!Tl.some(u=>d instanceof u))return{command:d,notes:[]};let c=d.path.join(" ");if(!jE().some(u=>u.path===c))throw o;return{command:d,notes:Qz(c,l)}}}s(t,"resolve");async function n(r,i){let o=i.stderr??process.stderr,a;try{a=t(r,i)}catch(l){return o.write(e.error(l,{colored:!1})),2}for(let l of a.notes)o.write(l);return Ute(a.command,o),e.run(a.command,i)}return s(n,"run"),{process(r,i){return t(r,i).command},run:n,async runExit(r,i){process.exitCode=await n(r,i)}}}s(by,"createPlexusCli");function Ute(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&Bl[n]===r&&ft(t,n,r),n in Bl&&vi(n)==="confirm"&&!Ul(e)&&t.write(`plexus-cli: \`${Bl[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
12038
12038
  `)}s(Ute,"noteRetiredPath");function Xz(e){let t=by().process(El(e),{executePlexusAgentTool:ky}),n=t.path.join(" ");if(n.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=jE().find(l=>l.path===n);if(!r){if(n===""||n==="--help"||n==="--version")return{path:n,writes:!1,host:"shared"};throw new Error(`plexus: command ${n} has no host classification.`)}let i=t,o=r.effect==="callKind"?_h(sl(al),i.fn??"",i.kind):void 0,a=Vf(n,{confirm:Ul(t),callKind:o});return{...r,writes:a}}s(Xz,"inspectPlexusCommand");async function eW(e,t){if(t)return YE(t,()=>eW(e));if(!Array.isArray(e.argv)||e.argv.length===0||e.argv.length>128||e.argv.some(l=>typeof l!="string"||l.length>128e3)||(e.stdin?.length??0)>1e6)throw new Error("plexus: invalid command invocation.");let n="",r="",i=by();if(mt()){let l=Xz(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(El(e.argv),{executePlexusAgentTool:ky,stdin:Bte.from(e.stdin===void 0?[]:[e.stdin]),stdout:new Zz({write(l,d,c){n+=String(l),c()}}),stderr:new Zz({write(l,d,c){r+=String(l),c()}})}),stdout:n,stderr:r}}s(eW,"executePlexusCommand");zE();XE({source:Gte.join(import.meta.dirname,"skill")});by().runExit(El(process.argv.slice(2)),{executePlexusAgentTool:ky});
12039
12039
  //# sourceMappingURL=cli.mjs.map