@smartkomm/plexus-cli 0.1.41 → 0.1.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -10341,7 +10341,7 @@ ${i.map(d=>` ${id(d)}
10341
10341
  `),0}},AC=[Ck,Dk,Fk];var Lk=class extends C{static{s(this,"LeadsListCommand")}static paths=[["leads","list"],["interessenten","list"]];static usage=T.Usage({category:"Admission",description:"List Interessenten (leads) for the active tenant",details:"Lists the tenant's OPEN Interessenten (program interests), newest first. Converted leads are Bewerbungen (listed under applications); withdrawn/declined leads are removed. Use --json for the rich shape.",examples:[["List open Interessenten","plexus-cli leads list"],["As JSON","plexus-cli leads list --json"]]});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.leads.listForManagement,{client:n});return this.print(r,i=>i.map(o=>({name:o.personDisplayName??"\u2014",angebot:o.programName===null?"\u2014":_e(o.programName),stufe:o.stageName===null?"\u2014":_e(o.stageName),lauf:o.runName===null?"\u2014":_e(o.runName)})),["name","angebot","stufe","lauf"]),0}},EC=[Lk];function zk(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(zk,"ts");function $C(e){return e==null?"":`${Math.round((Date.now()-e)/6e4)}m`}s($C,"ago");var TC=["queued","running","succeeded","failed","canceled"];function QH(e){let t=TC.find(n=>n===e);if(t===void 0)throw new Error(`jobs list: --status must be one of ${TC.join(" | ")}, got "${e}".`);return t}s(QH,"jobStatus");var Mk=class extends C{static{s(this,"JobsListCommand")}static paths=[["jobs","list"]];static usage=T.Usage({category:"Jobs",description:"List jobs newest-first (platform-admin). --status / --kind filter."});status=p.String("--status",{description:"queued | running | succeeded | failed | canceled"});kind=p.String("--kind",{description:"import | dummy | document_template_export"});limit=p.String("--limit",{description:"Max rows (default 100)."});all=p.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)."});async execute(){let t=await this.caller(),n=this.all?void 0:$u(this.limit,100),r=await this.paginate(t,S.jobs.listPage,this.status?{status:QH(this.status)}:{},{max:n,pageSize:Math.min(n??100,100)}),i=this.kind?r.filter(o=>o.kind===this.kind):r;return this.print(i,o=>o.map(a=>({id:a.id,kind:a.kind,status:a.status,tenant:a.tenantSlug??"",phase:a.phase,progress:a.progress?`${a.progress.current}/${a.progress.total}`:"",tries:`${a.attempts}/${a.maxAttempts}`,worker:a.leasedBy??"",updated:$C(a.updatedAt)})),["id","kind","status","tenant","phase","progress","tries","worker","updated"]),0}},qk=class extends C{static{s(this,"JobsShowCommand")}static paths=[["jobs","show"]];static usage=T.Usage({category:"Jobs",description:"Show one job's full detail + per-attempt run timeline."});jobId=p.String({required:!0});async execute(){let n=await(await this.caller()).query(S.jobs.getDetail,{jobId:this.jobId});if(n===null)throw new Error(`Job ${this.jobId} not found.`);return this.print(n),0}},Kk=class extends C{static{s(this,"JobsLogsCommand")}static paths=[["jobs","logs"]];static usage=T.Usage({category:"Jobs",description:"Tail a job's captured worker output (oldest-first)."});jobId=p.String({required:!0});limit=p.String("--limit",{description:"Max lines (default 500, max 2000)."});async execute(){let n=await(await this.caller()).query(S.jobs.tailLog,{jobId:this.jobId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(n,r=>r.map(i=>({at:zk(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},jk=class extends C{static{s(this,"JobsCancelCommand")}static paths=[["jobs","cancel"]];static usage=T.Usage({category:"Jobs",description:"Cancel a queued/running job (the worker aborts; the domain row is failed) \u2014 irreversible, plan unless --confirm."});jobId=p.String({required:!0});confirm=p.Boolean("--confirm",!1,{description:"Cancel (without it, only the plan is printed)."});async execute(){let t=await this.caller();if(!this.confirm){let n=await t.query(S.jobs.getDetail,{jobId:this.jobId});if(n===null)throw new Error(`Job ${this.jobId} not found.`);return this.print({jobId:this.jobId,kind:n.kind,status:n.status,canceled:!1},r=>[{key:"would cancel",value:`${r.jobId} (${r.kind}, ${r.status})`},{key:"next",value:"re-run with --confirm"}]),0}return await t.mutation(S.jobs.cancel,{jobId:this.jobId}),this.print({canceled:this.jobId}),0}},Bk=class extends C{static{s(this,"WorkersLogsCommand")}static paths=[["platform","workers","logs"],["workers","logs"]];static usage=T.Usage({category:"Platform",description:"Tail one worker's captured stdout/stderr."});workerId=p.String({required:!0});limit=p.String("--limit",{description:"Max lines (default 500, max 2000)."});async execute(){let n=await(await this.caller()).query(S.workers.tailLog,{workerId:this.workerId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(n,r=>r.map(i=>({at:zk(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},Uk=class extends C{static{s(this,"WorkersReaperStatusCommand")}static paths=[["platform","workers","reaper-status"],["workers","reaper-status"]];static usage=T.Usage({category:"Platform",description:"Show the last worker-reaper tick (confirm the cron is firing)."});async execute(){let n=await(await this.caller()).query(S.workers.reaperStatus,{});return n===null?(this.print({reaper:"no tick recorded yet"}),0):(this.print({...n,ranAt:zk(n.ranAt)}),0)}},Vk=class extends C{static{s(this,"WorkersReapCommand")}static paths=[["platform","workers","reap"],["workers","reap"]];static usage=T.Usage({category:"Platform",description:"Force a reaper pass NOW (free dead leases / fail stalled jobs)."});async execute(){let n=await(await this.caller()).mutation(S.workers.reap,{});return this.print(n),0}},Gk=class extends C{static{s(this,"ImportsCleanupOrphansCommand")}static paths=[["platform","imports","cleanup-orphaned"],["imports","cleanup-orphaned"]];static usage=T.Usage({category:"Imports",description:"Find/fail orphaned import runs (status 'running' with no active job). Dry-run unless --confirm."});allTenants=p.Boolean("--all-tenants",!1,{description:"Scan every tenant (default: the active --tenant only)."});confirm=p.Boolean("--confirm",!1,{description:"Actually mark orphans failed (default: dry-run preview)."});async execute(){let t=await this.caller(),n=this.allTenants?void 0:this.requireTenant(t),r=await t.mutation(S.imports.failOrphanedRuns,{...n?{tenantSlug:n}:{},confirm:this.confirm});return this.print(r,i=>i.orphans.map(o=>({id:o.id,tenant:o.tenantSlug,importRunId:o.importRunId,phase:o.phase??"",updated:$C(o.updatedAt),action:i.confirmed?"failed":"would-fail"})),["id","tenant","importRunId","phase","updated","action"]),0}},RC=[Mk,qk,Kk,jk,Bk,Uk,Vk,Gk];var ZH=/^(\d+)([mhd])$/,XH={m:6e4,h:36e5,d:864e5};function xp(e,t=Date.now()){let n=e.trim(),r=ZH.exec(n);if(r!==null)return t-Number(r[1])*XH[r[2]];let i=/^\d{4}-\d{2}-\d{2}/.test(n)?Date.parse(n):Number.NaN;if(Number.isNaN(i))throw new Error(`--since "${e}": expected 90m, 24h, 2d or an ISO date like 2026-10-13T11:40Z`);return i}s(xp,"parseSince");function Sp(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(Sp,"ts");function ib(e,t){if(e===void 0)throw new Error(`notifications ${t}: --locale is required (${ze.join("|")}) \u2014 every letter exists in each language, and each is worded on its own`);if(!Xf(e))throw new Error(`notifications: --locale "${e}" is not a supported locale (${ze.join("|")})`);return e}s(ib,"parseLocale");function eJ(e,t){let n={},r=s((i,o,a)=>{let l=o.indexOf("=");if(l<=0)throw new Error(`notifications letters: malformed ${i} "${o}" (expected <blockKey>=<value>)`);let d=o.slice(0,l).trim();if(!d)throw new Error(`notifications letters: malformed ${i} "${o}" (empty block key)`);if(d in n)throw new Error(`notifications letters: block "${d}" given twice \u2014 one value per block.`);n[d]=a(o.slice(l+1))},"put");for(let i of e??[])r("--slot",i,o=>o);for(let i of t??[])r("--slot-file",i,o=>ye(o.trim(),"utf8"));return n}s(eJ,"parseSlots");var Wk=class extends C{static{s(this,"NotificationsListCommand")}static paths=[["platform","notifications","list"],["notifications","list"]];static usage=T.Usage({category:"Notifications",description:"List mail deliveries newest-first (platform-admin). Filter by --status, --template, --to, --since; the smtp column is the relay's answer (`250 \u2026 queued as <id>` = accepted).",examples:[["Dead-letters only","$0 notifications list --status dead"],["Everything still in flight","$0 notifications list --status queued"],["Did the login-page link to this address go out today?","$0 notifications list --template account.loginLink --to steffi@schule.example --since 24h"]]});status=p.String("--status",{description:"queued | sending | sent | skipped | dead"});template=p.String("--template",{description:"Only this letter, e.g. account.loginLink."});to=p.String("--to",{description:"Only deliveries to this address."});since=p.String("--since",{description:"Created since: 90m, 24h, 2d or an ISO date/time."});limit=p.String("--limit",{description:"Max rows (default 100)."});all=p.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)."});async execute(){let t=await this.caller(),n=this.all?void 0:$u(this.limit,100),r=await this.paginate(t,S.notifications.listPage,{...this.status?{status:this.status}:{},...this.template?{templateId:this.template}:{},...this.to?{recipientEmail:this.to}:{},...this.since?{since:xp(this.since)}:{}},{max:n,pageSize:Math.min(n??100,100)});return this.print(r,i=>i.map(o=>({id:o.id,template:o.templateId,status:o.status,tenant:o.tenantSlug??"",to:o.recipientEmail,files:o.attachmentCount>0?String(o.attachmentCount):"",tries:`${o.attempts}/${o.maxAttempts}`,error:o.errorCode??"",mode:o.transportMode??"",dup:o.possibleDuplicate?"!":"",created:Sp(o.createdAt),settled:Sp(o.settledAt),smtp:o.lastSmtpResponse??""})),["id","template","status","tenant","to","files","tries","error","mode","dup","created","settled","smtp"]),0}};function tJ(e){if(e.letter===null)return{...e,attachments:[]};let{attachments:t,...n}=e.letter;return{...e,attachments:t.map(({filename:r,contentType:i,size:o})=>({filename:r,contentType:i,size:o})),letter:n}}s(tJ,"showView");var Yk=class extends C{static{s(this,"NotificationsShowCommand")}static paths=[["platform","notifications","show"],["notifications","show"]];static usage=T.Usage({category:"Notifications",description:"Show one delivery in full: SMTP evidence, lease, sweeper bookkeeping, template summary."});deliveryId=p.String({required:!0});async execute(){let n=await(await this.caller()).query(S.notifications.getDetail,{deliveryId:this.deliveryId});if(n===null)throw new Error(`Delivery ${this.deliveryId} not found.`);return this.print(tJ(n)),0}},Hk=class extends C{static{s(this,"NotificationsRetryCommand")}static paths=[["platform","notifications","retry"],["notifications","retry"]];static usage=T.Usage({category:"Notifications",description:"Retry a DEAD delivery: a fresh attempt through the normal claim path. Check `show` first \u2014 a `possibleDuplicate` row may already have reached the recipient."});deliveryId=p.String({required:!0});async execute(){return await(await this.caller()).mutation(S.notifications.retry,{deliveryId:this.deliveryId}),this.print({deliveryId:this.deliveryId,status:"queued"}),0}},Jk=class extends C{static{s(this,"NotificationsSweeperStatusCommand")}static paths=[["platform","notifications","sweeper-status"],["notifications","sweeper-status"]];static usage=T.Usage({category:"Notifications",description:"Last tick of the notification sweeper cron (deadLastHour is the number to watch)."});async execute(){let n=await(await this.caller()).query(S.notifications.sweeperStatus,{});return n===null?(this.print({ranAt:null,note:"sweeper has not run since deploy"}),0):(this.print({...n,ranAt:Sp(n.ranAt),lastDeadAt:Sp(n.lastDeadAt)}),0)}},Qk=class extends C{static{s(this,"NotificationsSelfTestCommand")}static paths=[["platform","notifications","self-test"],["notifications","self-test"]];static usage=T.Usage({category:"Notifications",description:"Resolve the deployment's mail config, verify the SMTP connection + credentials, and send ONE test mail to --to with the raw SMTP transcript. A redirect deployment redirects the test too; dry sends nothing.",examples:[["Probe staging","$0 --env staging notifications self-test --to you@example.com"]]});to=p.String("--to",{required:!0,description:"Explicit recipient (never defaulted)."});async execute(){let n=await(await this.caller()).action(S.notificationActions.selfTest,{recipient:this.to});return this.print(n),n.ok?0:1}},Zk=class extends C{static{s(this,"NotificationsLettersListCommand")}static paths=[["notifications","letters","list"]];static usage=T.Usage({category:"Notifications",description:"The letter catalog for one school: what it can reword, and what it already did.",details:"Only the letters a school may actually write are listed \u2014 addressed to families, and with blocks to rewrite. A staff-internal letter or a retired one is not offered at all. `reworded` names the languages in which this school has already deviated from a letter.",examples:[["The catalog","$0 --tenant test notifications letters list"],["Only the reworded ones","$0 --tenant test notifications letters list --json"]]});async execute(){let t=await this.caller(),n=await t.query(S.notifications.letterWorkspace,{tenantSlug:this.requireTenant(t),locale:"de"});return this.print(n.letters,r=>r.map(i=>({template:i.id,label:i.label,blocks:i.slots.map(o=>o.key).join(", "),reworded:i.rewordedIn.join(", ")})),["template","label","blocks","reworded"]),0}},Xk=class extends C{static{s(this,"NotificationsLettersShowCommand")}static paths=[["notifications","letters","show"]];static usage=T.Usage({category:"Notifications",description:"One letter block by block: the current text, whether it deviates, and the placeholders it may use.",examples:[["The welcome letter","$0 --tenant test notifications letters show applicant.welcome --locale de"],["Its English version","$0 --tenant test notifications letters show applicant.welcome --locale en"]]});templateId=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});async execute(){let t=await this.caller(),n=await t.query(S.notifications.letterWorkspace,{tenantSlug:this.requireTenant(t),locale:ib(this.locale,"letters show")}),r=n.letters.find(i=>i.id===this.templateId);if(r===void 0)throw new Error(`notifications letters show: "${this.templateId}" is not a letter this school may reword \u2014 known: ${n.letters.map(i=>i.id).join(", ")}`);if(!this.json){let i=r.placeholders.map(o=>`{{${o.key}}}${o.required?" (Pflicht)":""}`).join(", ");this.context.stdout.write(`${r.label} \u2014 ${r.occasion.de}
10342
10342
  Platzhalter: ${i||"\u2014"}
10343
10343
 
10344
- `)}return this.print(r,i=>i.slots.map(o=>{let a=i.override?.[o.key];return{block:o.key,label:o.label,deviates:a===void 0?"":"yes",text:(a??o.default).replace(/\s+/g," ").slice(0,80)}}),["block","label","deviates","text"]),0}},eb=class extends C{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=T.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=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=p.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let t=eJ(this.slot,this.slotFile);if(Object.keys(t).length===0)throw new Error("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:ib(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}},tb=class extends C{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=T.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=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"Block key to reset (repeatable)"});all=p.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 Error("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&t.length===0)throw new Error("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:ib(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}},ad=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function Ap(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":ad(t[r],""),...n===null?{}:{platform:ad(n[r],"")}}))}s(Ap,"chromeTextRows");var nb=class extends C{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=T.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=>[...Ap("greeting",r.greeting,r.defaults.greeting),...Ap("closing",r.closing,r.defaults.closing),{field:"senderName",school:ad(r.senderName,"\u2014 (platform)"),platform:ad(r.defaults.senderName,"")}],["field","school","platform"]),0}},rb=class extends C{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=T.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=p.String("--greeting-de",{description:"Opening line, German"});greetingEn=p.String("--greeting-en",{description:"Opening line, English"});closingDe=p.String("--closing-de",{description:"Sign-off, German"});closingEn=p.String("--closing-en",{description:"Sign-off, English"});senderName=p.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 Error(`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 Error("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=>[...Ap("greeting",l.greeting,null),...Ap("closing",l.closing,null),{field:"senderName",school:ad(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},IC=[Wk,Yk,Hk,Jk,Qk,Zk,Xk,eb,tb,nb,rb];var nJ="-stufe-",rJ=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ob(e){return`${e}${nJ}`}s(ob,"stageKeyPrefix");function sb(e,t){return`${ob(e)}${t}`}s(sb,"stageStorageKey");function PC(e,t){let n=ob(e);return t.startsWith(n)&&t.length>n.length}s(PC,"isUnderProgram");function Fr(e,t){let n=ob(e);return PC(e,t)||ae("CONFLICT",{de:`[stage/foreignKey] Der Stufenschl\xFCssel \u201E${t}\u201C liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C). F\xFChren Sie die Stufe in bundle.yaml unter einem neuen Schl\xFCssel auf; der n\xE4chste Apply archiviert diese Zeile (hinter der Archivsperre) und legt die Stufe mit dem neuen Schl\xFCssel an.`,en:`[stage/foreignKey] The level key "${t}" is not under the program "${e}" (expected: "${n}<key>"). List the level in bundle.yaml under a new key; the next apply archives this row (behind the archive lock) and creates the level with the new key.`}),t.slice(n.length)}s(Fr,"bareStageKey");function Ep(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=Et(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.stages[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"stage/nameMissing",index:i,message:{de:`[stage/nameMissing] ${l}: jede Klassenstufe braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[stage/nameMissing] ${l}: every stage needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"stage/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"stage/keyMissing",index:i,message:{de:`[stage/keyMissing] ${l}: jede Klassenstufe braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[stage/keyMissing] ${l}: every stage needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!rJ.test(d)){t.push({code:"stage/keyInvalid",index:i,message:{de:`[stage/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[stage/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"stage/duplicateKey",index:i,message:{de:`[stage/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.stages[${c}] verwendet`,en:`[stage/duplicateKey] ${l}: key "${d}" is already used by program.stages[${c}]`}});return}n.set(d,i)}),t}s(Ep,"stageSpecIssues");function OC(e){return{de:e.de.trim(),en:e.en.trim()}}s(OC,"trimmedText");function iJ(e,t){let n=[];return e.de!==t.de&&n.push(`"${e.de}" \u2192 "${t.de}"`),e.en!==t.en&&n.push(`en "${e.en}" \u2192 "${t.en}"`),n.join(", ")}s(iJ,"describeNameChange");function Tp(e,t,n){if(e===null)return t.length>0&&N("planStageReconcile: stages exist but the offer has no program key"),n.map((a,l)=>({op:"insert",key:a.key,name:OC(a.name),...a.gradeLevel!==void 0?{gradeLevel:a.gradeLevel}:{},sequence:l+1}));let r=new Map(t.map(a=>[a.key,a])),i=new Set,o=[];n.forEach(({name:a,...l},d)=>{let c={...l,name:OC(a)},u=sb(e,c.key);i.add(u);let f=d+1,m=r.get(u);if(m===void 0){o.push({op:"insert",key:c.key,name:c.name,...c.gradeLevel!==void 0?{gradeLevel:c.gradeLevel}:{},sequence:f});return}let y={};as(m.name,c.name)||(y.name=[m.name,c.name]);let k=m.gradeLevel??null,g=c.gradeLevel??null;k!==g&&(y.gradeLevel=[k,g]),m.sequence!==f&&(y.sequence=[m.sequence,f]),(Object.keys(y).length>0||m.archived)&&o.push({op:"update",key:c.key,stageId:m.stageId,name:c.name,changes:y,unarchive:m.archived})});for(let a of[...t].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:PC(e,a.key)?Fr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(Tp,"planStageReconcile");function $p(e){switch(e.op){case"insert":return`+stage ${e.key} (${e.name.de})`;case"archive":{let t=e.occupancy,n=[...t&&t.activeApplications>0?[`REFUSED: ${t.activeApplications} active application(s) \u2014 [stage/hasActiveApplications]`]:[],...t&&t.openLeads>0?[`${t.openLeads} open lead(s)`]:[]];return`-stage ${e.key} (${e.name.de})${n.length>0?` \u2014 ${n.join("; ")}`:""}`}case"update":{let t=[];if(e.unarchive&&t.push("restored"),e.changes.name&&t.push(iJ(e.changes.name[0],e.changes.name[1])),e.changes.gradeLevel){let[n,r]=e.changes.gradeLevel;t.push(`grade ${n??"\u2013"} \u2192 ${r??"\u2013"}`)}return e.changes.sequence&&t.push(`position ${e.changes.sequence[0]} \u2192 ${e.changes.sequence[1]}`),`~stage ${e.key} (${t.join(", ")})`}}}s($p,"describeStageStep");var oJ=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ni(e,t){return`${e}-${t}`}s(ni,"runStorageKey");function _C(e,t){typeof t!="string"&&ae("CONFLICT",{de:`[run/keyNotServed] Das Deployment liefert f\xFCr ein Schuljahr von \u201E${e}\u201C keinen Schl\xFCssel \u2014 es l\xE4uft ein \xE4lteres Release als die CLI. Nach dem n\xE4chsten Release erneut versuchen.`,en:`[run/keyNotServed] The deployment provides no key for a school year of "${e}" \u2014 it runs an older release than the CLI. Try again after the next release.`});let n=`${e}-`;return(!t.startsWith(n)||t.length===n.length)&&ae("CONFLICT",{de:`[run/foreignKey] Der Schl\xFCssel \u201E${t}\u201C des Schuljahrs liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C).`,en:`[run/foreignKey] The key "${t}" of the school year is not under the program "${e}" (expected: "${n}<key>").`}),t.slice(n.length)}s(_C,"bareRunKey");function Rp(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=Et(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.runs[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"run/nameMissing",index:i,message:{de:`[run/nameMissing] ${l}: jedes Schuljahr braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[run/nameMissing] ${l}: every run needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"run/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"run/keyMissing",index:i,message:{de:`[run/keyMissing] ${l}: jedes Schuljahr braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[run/keyMissing] ${l}: every run needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!oJ.test(d)){t.push({code:"run/keyInvalid",index:i,message:{de:`[run/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[run/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"run/duplicateKey",index:i,message:{de:`[run/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.runs[${c}] verwendet`,en:`[run/duplicateKey] ${l}: key "${d}" is already used by program.runs[${c}]`}});return}n.set(d,i)}),t}s(Rp,"runSpecIssues");var sJ={capacity:null,isOpen:!1},aJ={capacity:null,isOpen:!0};function lJ(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(lJ,"isCapacity");function Ip(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)||!lJ(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(Ip,"capacitySpecIssues");function CC(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(Fr(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(f=>f.key===ni(r,c.key));if(u===void 0&&!a.has(c.key))throw new Error(`offer[admission]: run "${c.key}" does not exist and is not created by this apply`);for(let[f,m]of Object.entries(c.capacities)){let y=i.get(f);if(y===void 0&&!o.has(f))throw new Error(`offer[admission]: capacities of run "${c.key}" name stage "${f}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let k={capacity:m.capacity,isOpen:m.isOpen},g=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,v=g!==void 0?{capacity:g.capacity,isOpen:g.isOpen}:u===void 0?sJ:aJ;v.capacity===k.capacity&&v.isOpen===k.isOpen||d.push({run:c.key,stageKey:f,from:v,to:k})}}return d}s(CC,"planRunCapacities");function NC(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(NC,"describeCell");function Op(e){return`~cap ${e.run}\xD7${e.stageKey} ${NC(e.from)} \u2192 ${NC(e.to)}`}s(Op,"describeCapacityStep");function DC(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(DC,"assertBackendHasStageKeys");async function ab(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}));DC(i);let a=Tp(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 f=c.get(u.stageId);if(f===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:f.activeApplications,openLeads:f.openLeads}}})}s(ab,"planStages");async function Pp(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});DC(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Fr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return CC(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===ni(d,c)))})}s(Pp,"planCapacities");async function dJ(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===ni(a,d)&&c.status==="archived"));if(l.length>0)throw new Error(`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(dJ,"assertNoArchivedRunKey");var lb={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...Ep(o??[]),...Rp(n.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(g=>g.message.de).join("; ")}`);let l=Ip(n.program?.runs??[],o?.map(g=>g.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await dJ(e,i,t,n);let d=await Pp(e,i,t,n),c=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=cJ(n);if(!u)throw new Error("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let f=c.units.find(g=>g.key===u);if(!f)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(g=>g.key===null?[]:[g.key]).join(", ")||"(none)"}`);let m=[];if(r.dryRun||(await e.mutation(S.programAdmin.ensurePedagogyUnit,{client:i,unitId:f.unitId}),await e.mutation(S.programAdmin.createProgramForAngebot,{client:i,offerKey:t,unitId:f.unitId,...n.program?.key!==void 0?{programKey:n.program.key}:{}})),m.push(`unit=${u}`),o!==void 0)if(r.dryRun){let g=await ab(e,i,t,o);m.push(...g.map($p))}else{let g=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}:{}}))});m.push(...g.steps,...g.warnings.map(v=>`warning ${v}`))}let y=r.dryRun?c:await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t});for(let g of n.program?.runs??[]){let v=y.programKey===null?void 0:y.runs.find($=>$.key===ni(y.programKey,g.key));if(v!==void 0){as(v.name,g.name)||(r.dryRun||await e.mutation(S.programAdmin.updateProgramRun,{client:i,offerKey:t,runId:v.runId,name:g.name}),m.push(`~run ${g.key} ("${_e(v.name)}" \u2192 "${_e(g.name)}")`));continue}r.dryRun||await e.mutation(S.programAdmin.addProgramRun,{client:i,offerKey:t,key:g.key,name:g.name,isOpen:g.capacities!==void 0?!1:g.isOpen??!0,...g.startDate?{startDate:g.startDate}:{},...g.endDate?{endDate:g.endDate}:{}}),m.push(`+run ${g.key} (${_e(g.name)})`)}let k=r.dryRun?d:await Pp(e,i,t,n);if(!r.dryRun&&k.length>0){let g=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),v=g.programKey;if(v===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let $ of k){let R=g.runs.find(O=>O.key===ni(v,$.run))?.runId,A=g.stages.find(O=>Fr(v,O.key)===$.stageKey)?.stageId;if(R===void 0||A===void 0)throw new Error(`offer[admission]: cell ${$.run}\xD7${$.stageKey} vanished between plan and write`);await e.mutation(S.programAdmin.setRunStageCapacity,{client:i,offerKey:t,runId:R,stageId:A,capacity:$.to.capacity,isOpen:$.to.isOpen})}}return m.push(...k.map(Op)),m.join(", ")}};function cJ(e){let t=e.program?.unitKey,n=e.links?.unitKey;if(t!==void 0&&n!==void 0&&t!==n)throw new Error(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${t}" and links.unitKey "${n}"; keep one`);return t??n}s(cJ,"bundleUnitKey");var FC={role:"control",effect:"pure",cardinality:"N-to-1"};var _p=["add","remove","replace"];function LC(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(LC,"roleAssignLiteral");var MC={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=LC(e,"roleKey")?.trim()??"",o=LC(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"}),_p.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 ${_p.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${_p.join(" | ")}.`},severity:"error"}),r},"validate")};var uJ=["event","effect","outcomes"],db=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),qC={outcomes:[{id:dr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of uJ)i in r&&n.push(db(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${dr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${dr}" itself.`));return On(t.nodes).some(i=>i.target===e.id)&&n.push(db(`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?.[dr]===void 0&&n.push(db(`nodes.${e.id}.next.${dr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${dr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${dr}" nowhere.`)),n},"validate")};var fJ="submit",KC=[{id:fJ,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function jC(e){return e==="draft"}s(jC,"isWritableSmartFormState");var cb=["draft","committed"],WSe=cb.filter(e=>jC(e));async function BC(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&&N(`application ${t}: two form instances for node "${n}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(BC,"getSmartFormInstance");var UC="form:fill",ub="request:collectPayment";var pJ={key:UC,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},VC={key:"bearbeitung",label:ne("In Bearbeitung","In progress"),scope:"node"},GC={[F$]:{label:ne("In Bearbeitung","In progress"),tone:"neutral",phase:VC,external:Ze(ne("Entwurf","Draft"),"neutral",ne("Bewerbung fortsetzen","Continue application"),ne("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."),ne("Bewerbung fortsetzen","Continue application"),"continue-form")},[Du]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:VC,external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung ist eingereicht","Your application has been submitted"),ne("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."))}},zC={role:"user-action",effect:"side-effect",progressDefaults:GC,progressEvents:Pt(GC),actions:s(()=>KC,"actions"),workItemTemplates:s(()=>[pJ],"workItemTemplates"),states:cb,currentState:s(async(e,t)=>{let n=await BC(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=>kn(e)?[]:[{id:Fu,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 WC={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Tt.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Tt.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Tt.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:rI(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[];e.inputs?.[Tt.flagKey]?.kind==="literal"&&rf(e)===null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Tt.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?.[Tt.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Tt.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 mJ="true",hJ="false",fb=[{id:mJ,label:{de:"Ja",en:"Yes"}},{id:hJ,label:{de:"Nein",en:"No"}}];var YC={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:fb,validate:s((e,t,n)=>gJ(e,t,n),"validate")};function gJ(e,t,n){let r=s(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${d.de}`,en:`[if/condition] Node "${e.id}": ${d.en}`},severity:"error"}),"issue"),i=fb.filter(d=>e.next?.[d.id]===void 0).map(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${d.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${d.label.de}\u201C (${d.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${d.label.en}" (${d.id}) leads nowhere.`},severity:"error"}));if(typeof e.condition!="string"||e.condition.trim()==="")return[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})];let o=Q$(t),a=_f(e.condition,o).filter(d=>d.severity==="error").map(d=>r(d.message)),l=[...i,...a];if(a.length>0||n?.liveEnvKeys===void 0)return l;for(let d of Fy(e.condition,o)){let c=DO(d.path,n.liveEnvKeys);c===null&&N(`[if/condition] no live-key universe for '${d.path}' \u2014 extend liveKeyUniverse`),c.has(d.value)||l.push(r({de:`$env.${d.path} == '${d.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${d.path} == '${d.value}' names no key of this school.`}))}return l}s(gJ,"ifNodeIssues");var ld="decision",yJ=new Set(["decision","review"]),kAe=new Set([...yJ,"governedDocument"]);var JC=[{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"}];var HC={released:{label:ne("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:ne("Freigabe","Release"),scope:"node"},external:Ze(ne("Freigegeben","Released"),"green",ne("Ihre Bewerbung wurde freigegeben","Your application has been released"),ne("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."))}},Li={inputs:s(()=>[{id:"allowSkipInTest",label:{de:"Im Testmodus \xFCberspringbar",en:"Skippable in test mode"},type:"boolean",defaultValue:!0,inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:JC,progressDefaults:HC,progressEvents:Pt(HC),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,...vi(t.semantic)?{semantic:t.semantic}:{}})),...mP(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:ld,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===ld&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),validate:pb};function pb(e,t,n){let r=[],i=e.inputs?.allowSkipInTest;i?.kind==="literal"&&typeof i.value!="boolean"&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.allowSkipInTest`,reason:{de:`[decision/allowSkipInTestType] Knoten "${e.id}": \u201EIm Testmodus \xFCberspringbar\u201C ist ein Ja/Nein-Wert (true/false).`,en:`[decision/allowSkipInTestType] Node "${e.id}": "Skippable in test mode" is a yes/no value (true/false).`},severity:"error"});let o=e.outcomes??[];o.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 a=new Set(o.map(d=>d.id));for(let d of o){let c=d.label;(typeof c=="string"?c.trim().length>0:c!=null&&typeof c=="object"&&Object.values(c).some(m=>typeof m=="string"&&m.trim().length>0))||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${d.id}`,reason:{de:`[decision/outcomeMissingLabel] Outcome "${d.id}" von "${e.id}" hat keine Beschriftung \u2014 sie ist der Text des Knopfs im Cockpit.`,en:`[decision/outcomeMissingLabel] Outcome "${d.id}" of "${e.id}" has no label \u2014 it is the text of the button in the cockpit.`},severity:"error"});let f=d.semantic;f===void 0?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${d.id}.semantic`,reason:{de:`[decision/outcomeSemanticMissing] Outcome "${d.id}" von "${e.id}" sagt nicht, was es bedeutet \u2014 eines von ${wn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${d.id}" of "${e.id}" does not say what it means \u2014 one of ${wn.join(", ")}.`},severity:"error"}):vi(f)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${d.id}.semantic`,reason:{de:`[decision/outcomeSemanticUnknown] Outcome "${d.id}" von "${e.id}" hat die Bedeutung "${String(f)}" \u2014 erlaubt: ${wn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${d.id}" of "${e.id}" has the meaning "${String(f)}" \u2014 allowed: ${wn.join(", ")}.`},severity:"error"})}for(let d of Object.keys(e.commentRequired??{}))a.has(d)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.commentRequired.${d}`,reason:{de:`[decision/commentRequiredUnknownOutcome] Unbekanntes Outcome "${d}" in commentRequired; erlaubt: ${[...a].join(", ")}`,en:`[decision/commentRequiredUnknownOutcome] Unknown outcome "${d}" in commentRequired; allowed: ${[...a].join(", ")}`},severity:"error"});let l=e.decisionAsTask?.title;return l!==void 0&&(l!==null&&typeof l=="object"&&Object.values(l).some(c=>typeof c=="string"&&c.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(pb,"validateDecisionNode");var mb=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],QC=[{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 Jn="processFooter";var hb="promoted";var ZC="promote",XC="Nachr\xFCcken";var gb={key:"warteliste",label:ne("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},eD={waitlisted:{label:ne("Warteliste","Waitlisted"),tone:"amber",phase:gb,external:Ze(ne("Warteliste","Waiting list"),"amber",ne("Sie stehen auf der Warteliste","You are on the waiting list"),ne("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:ne("Nachger\xFCckt","Promoted"),tone:"green",phase:gb,external:Ze(ne("Nachger\xFCckt","Moved up"),"green",ne("Sie sind nachger\xFCckt","You have moved up"),ne("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:ne("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:gb,external:Ze(ne("Warteliste geschlossen","Waiting list closed"),"red",ne("Die Warteliste wurde geschlossen","The waiting list has been closed"),ne("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},tD={outcomes:mb,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Gn.map(e=>({value:e,label:lR[e]}))},{id:"autoPromoteOnVacancy",label:{de:"Bei freiem Platz automatisch nachr\xFCcken",en:"Promote automatically when a place frees up"},type:"boolean",required:!0,inspector:"literal-only"}],"inputs"),validate:s((e,t)=>{let n=Pg(e);if(n===null)return[];let r=t.nodes.filter(o=>o.type==="waitlist"&&o.id!==e.id),i=t.nodes.indexOf(e);for(let o of r){if(t.nodes.indexOf(o)>i)continue;let a=Pg(o);if(a!==null&&!(a.waitlistOrder===n.waitlistOrder&&a.autoPromoteOnVacancy===n.autoPromoteOnVacancy))return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${o.id}" und "${e.id}" nennen verschiedene Regeln (Reihenfolge, automatisches Nachr\xFCcken) \u2014 eine Kohorte hat EINE Warteliste.`,en:`[waitlist/policyConflict] Waiting lists "${o.id}" and "${e.id}" state different rules (order, automatic promotion) \u2014 a cohort has ONE waiting list.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:eD,progressEvents:Pt(eD),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:mb).some(n=>n.id===hb)?[{id:ZC,kind:"advance",outcome:hb,semantic:"other",label:{de:XC,en:"Promote from waitlist"},surface:Jn,superUserOnly:!0}]:[],"actions")};var wJ="complete",Np="acceptedIncomplete",Cp="rejected",kJ="absage",nD="closeWithoutDocuments",rD="rejectAtCompleteness",iD="Ohne Nachreichung abschlie\xDFen",oD="Ablehnen",sD="awaitingDocuments",yb="documentsComplete",wb="closedWithoutDocuments",kb="rejected",bb="withdrawn",aD="requested",BAe={[wJ]:{event:yb,status:"complete",endsRole:!0},[Np]:{event:wb,status:"acceptedIncomplete",endsRole:!1},[Cp]:{event:kb,status:"rejected",endsRole:!0},[kJ]:{event:bb,status:"withdrawn",endsRole:!0}};var dd=s(()=>nl[0],"beneficiary"),vb=366;function bJ(e){let t=e.reads,n=rl(e).flatMap(({address:r})=>at(r)&&!nl.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(at):[],...n]}s(bJ,"printedFields");function vJ(e,t){let n=se(t);return e.nodes.filter(r=>r.type==="governedDocument"&&bJ(r).some(i=>se(i)===n))}s(vJ,"documentsPrinting");function xJ(e,t){if(!at(t)||t.path!==dd())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!kn(n)}s(xJ,"isCreatedFormBeneficiary");function Gt(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Gt,"issue");var xb={key:"unterlagen",label:ne("Unterlagen nachreichen","Outstanding documents"),scope:"node"},lD={[sD]:{label:ne("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:xb,external:Ze(ne("Unterlagen fehlen","Documents missing"),"amber",ne("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),ne("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."))},[yb]:{label:ne("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:xb,external:Ze(ne("Unterlagen vollst\xE4ndig","Documents complete"),"green",ne("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),ne("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[wb]:{label:ne("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:xb,external:Ze(ne("Abgeschlossen","Closed"),"neutral",ne("Die Nachreichung ist abgeschlossen","The document request is closed"),ne("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[kb]:{label:ne("Abgelehnt","Rejected"),tone:"red",phase:qI,external:Ze(ne("Abgelehnt","Rejected"),"red",ne("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),ne("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."))},[bb]:{label:ne("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:wf,external:Ze(ne("Zur\xFCckgezogen","Withdrawn"),"red",ne("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),ne("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},dD={outcomes:QC,progressDefaults:lD,progressEvents:Pt(lD),notificationEvents:s(()=>[{id:aD,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(Np)&&n.push({id:nD,kind:"advance",outcome:Np,semantic:"other",label:{de:iD,en:"Close without documents"},surface:Jn,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(Cp)&&n.push({id:rD,kind:"advance",outcome:Cp,semantic:"rejected",label:{de:oD,en:"Reject application"},surface:Jn,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($=>Be(t,$,"de"),"shown"),l=s($=>Be(t,$,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Gt(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 $=new Set;for(let R of d){if(!be(R))continue;let A=se(R);if($.has(A)){r.push(Gt(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(R)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(R)} appears twice in \`requires\`.`}));continue}if($.add(A),!at(R)){r.push(Gt(e,"requires",{de:`[completenessCheck/unknownField] ${a(R)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(R)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let O=Pr(n,R);if(O==null)continue;let F=Oi("requires",Ii(O));F==="computed"||F==="repeated"?r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(R)} ist ${O.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(R)} is ${O.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):F==="untranslated"&&r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(R)} (\u201E${Ri(O,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 der Brief \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l(R)} ("${Ri(O,"de")}") has no English name (field or person/section) \u2014 the letter "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},f="inDays"in u,m="until"in u;if(f===m)r.push(Gt(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(f){let $=u.inDays;(typeof $!="number"||!Number.isInteger($)||$<0||$>vb)&&r.push(Gt(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String($)}" ist keine ganze Zahl von 0 bis ${vb} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String($)}" is not a whole number from 0 to ${vb} days.`}))}else typeof u.until!="string"||xy(u.until)===null?r.push(Gt(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<rO(Date.now())&&r.push({...Gt(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 $=new Map(d.filter(at).map(R=>[se(R),R]));for(let R of $.values())for(let A of vJ(t,R))r.push(Gt(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(R)} flie\xDFt in das Dokument \u201E${A.label?.de??A.id}" (${A.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(R)} flows into the document "${A.label?.en||A.id}" (${A.id}) \u2014 once it is issued, the family can no longer submit it later. Remove the field from \`requires\` or from the document.`}))}let y=e.inputs?.guestRole,k=y?.kind==="literal"?y.value:void 0,g=e.inputs?.person,v=g?.kind==="binding"?g.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Gt(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(k)?r.push(Gt(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${k}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${k}" does not exist in this school's role catalog. Known roles: ${[...n.roleKeys].sort().join(", ")}.`})):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(k)&&r.push(Gt(e,"inputs.guestRole",{de:`[completenessCheck/nonLeafRole] Rolle "${k}" hat untergeordnete Rollen und ist nicht vergebbar.`,en:`[completenessCheck/nonLeafRole] Role "${k}" has sub-roles and cannot be assigned.`})),v===null&&r.push(Gt(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${tn}.${dd()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${tn}.${dd()}).`}))),be(v)&&!xJ(t,v)&&r.push(Gt(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>.${tn}.${dd()}).`,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>.${tn}.${dd()}).`})),v!==null&&k===void 0&&r.push(Gt(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 $ of["complete","rejected"])e.next?.[$]===void 0&&r.push(Gt(e,`next.${$}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${$}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${$}" nowhere.`}));return r},"validate")};var SJ=[{id:cR,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],cd=s(e=>e,"asDecision"),cD={[uR]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:ne("In Pr\xFCfung","In review"),scope:"node"},external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),ne("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."))}},uD={role:"user-action",effect:"side-effect",outcomes:SJ,progressDefaults:cD,progressEvents:Pt(cD),notificationEvents:s(e=>Li.notificationEvents(cd(e)),"notificationEvents"),actions:s(e=>[...Li.actions(cd(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:Cg,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Li.optionalActionKinds,workItemTemplates:s(e=>Li.workItemTemplates(cd(e)).map(t=>t.key===ld?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,Cg]}:t),"workItemTemplates"),taskDocuments:s((e,t)=>Li.taskDocuments(cd(e),t),"taskDocuments"),validate:s((e,t,n)=>{let r=pb(cd(e),t,n),i=Array.isArray(e.reads)?e.reads:[];for(let o of e.outcomes??[]){let a=o.semantic;typeof a!="string"||!Hu.includes(a)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/rejectingOutcome] Pr\xFCf-Knoten "${e.id}" deklariert das Outcome "${o.id}" mit der Bedeutung "${String(a)}" \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 "${o.id}" meaning "${String(a)}" \u2014 a review neither rejects nor waitlists; that is the decision of the approval or "Reject application".`},severity:"error"})}for(let o of i){if(!at(o))continue;let a=Pr(n,o);a==null||Oi("nodeReads",Ii(a),e.type)!=="computed"||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.reads`,reason:{de:`[review/readsNotTickable] Pr\xFCf-Knoten \u201E${e.label?.de??e.id}\u201C (${e.id}) soll das berechnete Feld ${se(o)} abhaken lassen \u2014 nur eingegebene Felder haben einen Wert, den jemand pr\xFCfen kann.`,en:`[review/readsNotTickable] Review node "${e.label?.en||e.id}" (${e.id}) is to tick off the computed field ${se(o)} \u2014 only entered fields have a value someone can check.`},severity:"error"})}return r},"validate")};var fD=["awaitingAnswer","answered"];async function pD(e,t){return(await gl(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(pD,"externalRequestState");var gD=[{id:As,label:{de:"Bezahlt",en:"Paid"}}],AEe=new Set(gD.map(e=>e.id));var AJ=As,mD=[{id:AJ,kind:"advance",outcome:As,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],EJ={id:dy,kind:"advance",outcome:As,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:Jn,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"}}},TJ={id:dy,kind:"advance",outcome:As,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:Jn,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 Sb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Sb,"literalOf");function Zs(e){let t=Sb(e,zn);return lf(t)?t:null}s(Zs,"settlementOrNull");function $J(e){let t=Sb(e,Ti);return typeof t=="string"&&t.length>0?t:null}s($J,"articleKeyOrNull");function RJ(e){let t=Sb(e,Wn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(RJ,"payeeKeyOrNull");var IJ={id:Ti,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},OJ={id:zn,label:{de:"Abrechnung",en:"Settlement"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"separate",label:{de:"Separat (Schule)",en:"Separately (school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},PJ={id:$i,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},_J={id:Wn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function NJ(e){return[IJ,OJ,...Zs(e)==="online"?[_J]:[],PJ]}s(NJ,"collectPaymentInputs");var CJ=["amount","currency","settlement"];function DJ(e,t){if(Zs(e)!=="online")return[];let n=RJ(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] Abrechnung \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 \u201Eseparat" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Settlement "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 "separate".`})]:[]}s(DJ,"payeeIssues");var hD={awaitingPayment:{label:ne("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:ne("Zahlung","Payment"),scope:"node"},external:Ze(ne("Zahlung offen","Payment due"),"amber",ne("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),ne("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},yD={outputs:s(()=>[{name:WR,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>NJ(e),"inputs"),outcomes:gD,progressDefaults:hD,progressEvents:Pt(hD),notificationEvents:s(e=>Zs(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=Zs(e);return t==="online"?[...mD,TJ]:t==="separate"?[EJ]:[]},"actions"),states:fD,currentState:s((e,t)=>pD(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:ub}),"currentState"),workItemTemplates:s(e=>{let t=e;return Zs(t)!=="online"?[]:[{key:ub,recipient:"external",title:t.label,unlocks:mD.map(n=>n.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 CJ)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"), die Abrechnung ist der Parameter \u201EAbrechnung" (inputs.settlement).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and settlement is the parameter "Settlement" (inputs.settlement).`});r.push(...DJ(e,n)),Zs(e)===null&&i(`inputs.${zn}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${Ss.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[zn])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${Ss.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[zn])}.`});let o=e.inputs?.[$i];if(o?.kind==="literal"){let d=af(o.value);d!==null&&i(`inputs.${$i}`,{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=$J(e);if(a===null)return i(`inputs.${Ti}`,{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.${Ti}`;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 ${cy.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${cy.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")};var Fn="traeger",wD={de:"Tr\xE4ger",en:"Provider"};function Dp(e){let t=e.inputs?.[Fn];return t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0?t.value:null}s(Dp,"traegerKeyOfNode");var Fp={name:"input.traeger.name",address:"input.traeger.anschrift"},$Ee=Object.values(Fp);var kD="governedDocument",Io="prepareDocument",ud="prepareDocument:revision",Lr="releaseApproval",Oo="documentResponse",Mr="responseCheck",Lp="returnSigned";var bD="requestApproval";var vD="issueDocument",xD="correctInPlace",SD="rescindAndReissue",Mp="requestChange";var Xs="releaseArtifact",cn="signingRecovery",Po="resendESignature",_o="switchToPaper";var Ab=new Set([Io,ud]),AD=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],qp=["upload","resolver","template","none"],No=1,Co=366,ri="responseDueInDays";function Eb(e){let t=e.inputs?.[ri];return t?.kind==="literal"&&fd(t.value)?t.value:void 0}s(Eb,"responseDueInDaysForVocabulary");function fd(e){return typeof e=="number"&&Number.isInteger(e)&&e>=No&&e<=Co}s(fd,"isValidResponseDueInDays");var Kp=["generatedAt","responseDueInDays"],Do=["release","none"],jp=["confirm","signedUpload","signedUploadChecked","eSignature"];function ED(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(ED,"localeFieldMissingText");var Tb=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),TD=/^[a-z][a-z0-9_]*$/;function $D(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"||!TD.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(!Ei(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 (${xs.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 (${xs.join(", ")}).`}});continue}if(Tb.has(a.type)||n.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${t}" hat den Typ "${a.type}" \u2014 ein Brief druckt nur ${[...Tb].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a letter only prints ${[...Tb].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!TD.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!==void 0&&!Kp.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Kp.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Kp.join(", ")}.`}})}return n.push(...FJ(e,t)),n}s($D,"templateParameterIssues");function FJ(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:ED(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=>!ze.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${ze.join(", ")})`,en:`has options that are not a language (allowed: ${ze.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(FJ,"localeFieldIssues");function RD(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(RD,"applyTemplateStamp");var $b=50;async function Bp(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take($b+1);return n.length>$b&&N(`signing_returns: Vorgang ${t} has more than ${$b} returns`),n}s(Bp,"returnsOf");var Rb=50;async function Ib(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(Rb+1);return n.length>Rb&&N(`signing_returns: return ${t} has more than ${Rb} files`),n.length===0&&N(`[signing/noDocument] return ${t} carries no file`),n}s(Ib,"returnDocumentsOf");async function ID(e,t){let n=await Ib(e,t);return n.length!==1&&N(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(ID,"soleReturnDocumentOf");var Up=200,YEe=Up*20;async function LJ(e,t){let n=await e.db.get(t);return n===null&&N(`[process] application ${t} not found`),n.redactedAt!==void 0}s(LJ,"processRedacted");async function Ob(e,t){await LJ(e,t)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(Ob,"assertProcessReadable");function MJ(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(MJ,"rowOf");async function OD(e,t,n){await Ob(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(Up+1);return r.length>Up&&N(`[process] application ${t} has more than ${Up} results of ${n.scope}.${n.owner}.${n.key}`),r.map(MJ)}s(OD,"storeHistory");async function qJ(e,t,n){if(n.key===tn){await Ob(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 OD(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(qJ,"nodeResultAt");async function Vp(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return KJ(await qJ(e,t.applicationId,n),n,t.applicationId)}s(Vp,"readOwnResult");function KJ(e,t,n){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&N(`[process] ${se(t)} of application ${n} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(KJ,"refOf");var Pb={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},jJ=Object.keys(Pb),BJ=jJ.filter(e=>Pb[e]==="open"),rTe=BJ.filter(e=>e!=="pending");function PD(e){return Pb[e]==="terminal"}s(PD,"isTerminalSigningStatus");var Mi=["docusign","insign"];var pd={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var VJ=PD;function ND(e){return!VJ(e.status)&&e.voidRequestedAt===void 0}s(ND,"holdsContract");async function CD(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(CD,"traegerLegalEntityOfParty");async function GJ(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(GJ,"isOrganizationParty");async function DD(e,t){return await CD(e,t)!==null?"traeger":await GJ(e,t)?"organization":"person"}s(DD,"signerKindOf");async function FD(e,t){t.length===0&&N("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await zJ(e,n.partyId)==="family")return"family";return"traeger"}s(FD,"signingSideOf");async function zJ(e,t){return await DD(e,t)==="traeger"?"traeger":"family"}s(zJ,"sideOfParty");var FTe=16*1024;var LTe=15*6e4;var MTe=10*6e4;var _b={contractSnapshotId:Ut.restrict(w.id("contract_snapshots")),storageId:Ut.restrict(w.id("_storage")),sha256:w.string(),filename:w.string(),uploadedAt:w.number(),signers:w.array(w.object({partyId:Ut.history(w.id("parties")),role:w.string()}))},t$e=Vr({tenantId:Ut.tenant(w.id("tenants")),signingRequestDocumentId:Ut.belongsTo(w.id("signing_request_documents")),..._b}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var s$e=w.object(_b);var Nb=200;async function YJ(e,t,n,r){t.length>Nb&&N(`${r} is carried by more than ${Nb} 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&&N(`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(YJ,"requestsOfMembers");async function LD(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(Nb+1);return await YJ(e,r,n,`revision ${t}`)}s(LD,"requestsOfSnapshot");var MD=100;async function HJ(e,t){let n=await LD(e,t);n.length>MD&&N(`requestsBySideOf: revision ${t} has more than ${MD} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await FD(e,i.signers)].push(i);return r}s(HJ,"requestsBySideOf");async function Cb(e,t){return(await HJ(e,t)).family}s(Cb,"familyRequestsOf");var Db=100;async function JJ(e,t){let n=await e;return n.length>Db&&N(`contractChain: more than ${Db} ${t}`),n}s(JJ,"bounded");async function QJ(e,t,n){let r=await Vp(e,{applicationId:t,nodeId:n,key:ws});return r.state==="pending"?null:(r.ref.kind!=="contract"&&N(`contractChain: $node.${n}.${ws} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(QJ,"nodeContractRef");async function qD(e,t){return await JJ(e.db.query("contract_snapshots").withIndex("by_contractId_and_revisionNumber",n=>n.eq("contractId",t)).take(Db+1),`revisions on contract ${t}`)}s(qD,"snapshotsAsc");async function Fb(e,t){let n=(await Cb(e,t)).filter(ND);return n.length>1&&N(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s(Fb,"openFamilyRequest");async function ZJ(e,t){for(let n of await qD(e,t))if((await Cb(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(ZJ,"familyRoute");async function KD(e,t){for(let n of t)if(await ZJ(e,n)==="paper")return"paper";return"provider"}s(KD,"familyRouteOf");async function XJ(e,t){let n=await ID(e,t._id),r=await e.db.system.get("_storage",n.storageId);return r===null&&N(`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(XJ,"toReturn");function Gp(e){async function t(a,l){return await QJ(a,l,e.id)}s(t,"contractOrNull");async function n(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),f=u===null?null:await a.db.get(u),m=await t(a,l);return(f===null||m===null||f.contractId!==m)&&N(`${c}: ${d} is no revision of node "${e.id}"'s contract ${m??"(none yet)"} \u2014 corrupt arc`),f}s(n,"snapshotOf");async function r(a,l){let d=await t(a,l);return d===null?null:(await qD(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;N(`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 Fb(a,c._id);if(u===null)return null;let f=(await Bp(a,u._id)).filter(m=>m.review.status==="pending"&&m._id!==d.rejected);return f.length>1&&N(`returned(${d.where}): Vorgang ${u._id} has ${f.length} returns pending \u2014 one is checked at a time`),f[0]===void 0?null:await XJ(a,f[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(Gp,"contractNodeReads");function zp(e){return e.addedParts??[]}s(zp,"addedPartsOf");var Lb=50;async function e6(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(Lb+1);return n.length>Lb&&N(`groupRunsOf: generation group ${t} has more than ${Lb} runs`),n.length===0&&N(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(e6,"groupRunsOf");async function jD(e,t){let n=await e6(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)&&N(`groupRunsInOrder: package group ${t} has inconsistent members`);let i=await e.db.get(r);i===null&&N(`groupRunsInOrder: package run ${t} is missing`);let o=await e.db.query("contract_package_parts").withIndex("by_packageRevisionId_and_position",l=>l.eq("packageRevisionId",i.packageRevisionId)).take(51),a=[...o.map(l=>l.partKey),...zp(i).map(l=>l.partKey)];return(o.length>50||n.some(l=>!a.includes(l.partKey)))&&N(`groupRunsInOrder: package group ${t} names an unknown part`),n.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}N(`Package run ${t} has no package reference.`)}s(jD,"groupRunsInOrder");function BD(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(BD,"isCompleteGroup");var Mb=200;function t6(e){let t=e.generatorStamp?.parts;return t===void 0&&N(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),t.map(n=>n.partKey)}s(t6,"groupPartKeys");async function n6(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(Mb+1);return r.length>Mb&&N(`groupChain: more than ${Mb} generation runs on node ${n}`),r}s(n6,"nodeRuns");async function r6(e,t,n){let r=t6(n),i=new Set;for(let a of await n6(e,t,n.id))a.packageRunId===void 0&&N(`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 jD(e,a);if(!BD(l))continue;let d=await e.db.get(a);d===null&&N(`groupChain: generation group ${a} has no package run`);let c=new Set(zp(d).map(f=>f.partKey)),u=[];for(let f of l){!r.includes(f.partKey)&&!c.has(f.partKey)&&N(`groupChain: run ${f._id} renders part "${f.partKey}", which node "${n.id}"'s pin does not declare and nobody added`);let m=await e.db.get(f.contractSnapshotId);m===null&&N(`groupChain: run ${f._id} names revision ${f.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:f,snapshot:m})}o.push({packageRunId:a,startedAt:Math.min(...l.map(f=>f._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(r6,"groupRevisionRows");async function qb(e,t,n){let r=await Vp(e,{applicationId:t,nodeId:n,key:ks});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&N(`groupChain: $node.${n}.${ks} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(qb,"nodeGroupContracts");async function i6(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await Fb(e,r._id);i!==null&&n.set(i._id,i)}return n.size>1&&N(`groupChain: generation group ${t.packageRunId} is held by ${n.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...n.values()][0]??null}s(i6,"openGroupRequest");async function o6(e,t){let n=[];for(let i of await Ib(e,t._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&N(`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(o6,"toGroupReturn");function UD(e){async function t(i,o,a,l){let d=(await r6(i,o,e)).find(c=>c.members[0]?.snapshot._id===a);return d===void 0&&N(`${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;N(`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 i6(i,l);if(d===null)return null;let c=(await Bp(i,d._id)).filter(u=>u.review.status==="pending"&&u._id!==a.rejected);return c.length>1&&N(`returned(${a.where}): Vorgang ${d._id} has ${c.length} returns pending \u2014 one is checked at a time`),c[0]===void 0?null:await o6(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await qb(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(UD,"groupNodeReads");var s6={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},VD={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},GD={...VD,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},a6={...GD,kind:"eSignature",issuesBy:"provider"},ii={confirm:s6,signedUpload:VD,signedUploadChecked:GD,eSignature:a6};function qi(e){let t=e.responseStrategy;if(typeof t=="string"&&t in ii)return ii[t];N(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(t)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(qi,"responseStrategyOf");function zD(e){if(e.type!==kD||e.production!=="resolver")return!1;let t=e.responseStrategy;return typeof t=="string"&&t in ii?ii[t].acceptEvent==="contractEvent":!1}s(zD,"isFamilySignedContractNode");function md(e){return e.label}s(md,"governedDocTitle");function Kb(e){return e.approval==="release"?bD:vD}s(Kb,"submitActionId");function WD(e,t,n){return{key:t,recipient:"internal",title:n,unlocks:[Kb(e)],gatesNode:!0,advancesNode:!0}}s(WD,"producerTemplate");function l6(e){return e.titles?.respond??e.label}s(l6,"responseTitle");var ea={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function jb(e){let t=qi(e),n=[];if(e.production!=="none"&&n.push(WD(e,Io,e.titles?.prepare??ea),WD(e,ud,e.titles?.revise??ea)),e.approval==="release"&&n.push({key:Lr,recipient:"internal",title:e.titles?.approve??ea,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),n.push({key:Oo,recipient:"external",title:l6(e),unlocks:t.producesResponseArtifact?[t.checksReturn?Lp:t.acceptOutcomeId,t.declineOutcomeId,Mp]:[t.acceptOutcomeId,t.declineOutcomeId],advancesNode:!0,...Eb(e)!==void 0?{dueInDays:Eb(e)}:{}}),t.checksReturn&&n.push({key:Mr,recipient:"internal",title:e.titles?.check??ea,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),t.issuesBy==="provider"){let r=md(e);n.push({key:cn,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Po,_o],gatesNode:!1,advancesNode:!1})}return n}s(jb,"governedDocIntrinsicTemplates");function d6(e){e.production==="none"&&N(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let t=e.artifacts??[];t.length!==1&&N(`governedDocSlot: node "${e.id}" declares ${t.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let n=t[0];return(typeof n.key!="string"||n.key.length===0)&&N(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),n}s(d6,"governedDocSlot");function Wp(e){return d6(e).key}s(Wp,"governedDocSlotKey");function c6(e){let t=e.lifecycle.kind==="draft"?void 0:e.lifecycle.kind;return{_id:e._id,_creationTime:e._creationTime,versionNumber:e.versionNumber,...t!==void 0?{status:t}:{},origin:e.origin.kind,storageId:e.storageId,mimeType:e.mimeType,...e.filename!==void 0?{filename:e.filename}:{}}}s(c6,"toRevision");function u6(e){let t=c6(e);return{_id:t._id,_creationTime:t._creationTime,storageId:t.storageId,...t.filename!==void 0?{filename:t.filename}:{},...t.mimeType!==void 0?{mimeType:t.mimeType}:{},round:t.versionNumber}}s(u6,"toReturn");function YD(e){let t=Wp(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;ae("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(f=>f._id===l.rejected);if(u===void 0&&N(`returned(${l.where}): the handed-back scan ${l.rejected} is no version of slot "${t}"`),c.versionNumber<=u.versionNumber)return null}return u6(c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(YD,"artifactNodeReads");function Yp(e){return e.production==="none"&&N(`documentChainKind: node "${e.id}" has production 'none' \u2014 it keeps no document`),e.production!=="resolver"?"artifact":e.generatorStamp?.parts!==void 0?"group":"contract"}s(Yp,"documentChainKind");function HD(e){switch(Yp(e)){case"contract":return Gp(e).reads;case"group":return UD(e).reads;case"artifact":return YD(e).reads}}s(HD,"documentReadsFor");var f6={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function hd(e){let t=e.responseStrategy;return typeof t=="string"&&t in ii?ii[t].producesResponseArtifact:!1}s(hd,"returnsSignedCopy");function p6(e){return hd(e)&&e.confirmContractTerms!==!1}s(p6,"asksContractTerms");function JD(e){return p6(e)?{title:e.contractTermsQuestionText??f6,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(JD,"contractTermsConfirm");async function m6(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:Cy(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Mr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&N(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${Mr} row`),a}s(m6,"rejectedReturnOfAsk");async function QD(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await m6(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(QD,"returnedCopyOfAsk");var Bb=new Set([...Ab,Lr,Oo,Mr,cn]),tF={id:Ft,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},nF={id:lo,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function h6(e){let t=[],n=[{slot:tF,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:nF,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(Re(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(Re(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=il(a.value,{type:r.type});d!==null&&t.push(Re(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return t}s(h6,"referenceInputIssues");var g6={id:ri,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},y6={id:Fn,type:"legalEntity",label:wD,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function w6(e,t){let n=`inputs.${Fn}`,r=e.inputs?.[Fn];if(r!==void 0&&r.kind==="binding")return[Re(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=Dp(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(Re(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(Re(e,n,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Fp.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 (${Fp.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(w6,"traegerIssues");function Jp(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}}:(ki(r)||N(`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(Jp,"generatorFields");function k6(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(k6,"deferredToCockpit");function b6(e){return Ei(e.type)?e.type:void 0}s(b6,"resolverSlotType");function v6(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=md(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(v6,"issueConfirmation");function Re(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Re,"issue");function Hp(e){return qp.includes(e.production)&&Do.includes(e.approval)&&jp.includes(e.responseStrategy)}s(Hp,"hasValidModes");async function Ub(e,t){let n=await gl(e,{applicationId:t.applicationId,nodeId:t.node.id});if(n.length===0)return"pending";let r=n.filter(l=>l.isOpen&&l.kind==="admission"),i=r.filter(l=>l.templateKey!==void 0&&Ab.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";let o=r.find(l=>l.templateKey===Lr);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===cn))return"signatureStalled";let a=r.find(l=>l.templateKey===Oo);if(a!==void 0){if(qi(t.node).issuesBy==="provider"){let d=Yp(t.node)==="group"?(await qb(e,t.applicationId,t.node.id)).map(c=>c.contractId):[await Gp(t.node).contractOrNull(e,t.applicationId)].flatMap(c=>c===null?[]:[c]);if(d.length===0&&N(`governedDocCurrentState: eSignature node "${t.node.id}" has an open ask but no contract`),await KD(e,d)==="provider")return"awaitingSignature"}return qi(t.node).producesResponseArtifact?await QD(e,{chain:HD(t.node),applicationId:t.applicationId,ask:a,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${t.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(l=>l.templateKey===Mr)?"responseInCheck":"done"}s(Ub,"governedDocCurrentState");function ZD(e){return e.production!=="none"&&Yp(e)!=="artifact"}s(ZD,"keepsDocumentInContractDomain");function x6(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!be(r)||r.scope!=="env"||!ar(r.key))return[];let i=ao(r.key);if(t.type!==i.type)return[Re(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" ist ${t.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${se(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${t.key}" is ${t.type}, the environment variable "${i.label.en}" (${se(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?[]:[Re(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(x6,"envCoverageIssues");function rF(e,t){let n=[];for(let r of Jp(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...x6(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${be(a.address)?se(a.address):JSON.stringify(a.address)}`,en:`a binding to ${be(a.address)?se(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:k6(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(rF,"fieldSourceIssues");function S6(e){let t=lr(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=$D(e.templateStamp,t).map(({path:r,reason:i})=>Re(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...rF(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(S6,"templateIssues");function A6(e,t){return(t?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(n=>{if(n.documentAnchors===null)return[Re(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?[]:[Re(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(A6,"eSignatureAnchorIssues");function E6(e,t){return t===void 0||t.sendable?[]:qi(e).issuesBy!=="provider"?[]:[Re(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(E6,"eSignatureProviderIssues");var XD={key:"dokument",label:ne("Dokument","Document"),scope:"node"},eF={producing:{label:ne("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:XD,external:Ze(ne("In Vorbereitung","In preparation"),"blue",ne("Ihr Dokument wird vorbereitet","Your document is being prepared"),ne("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:ne("Dokument bereitgestellt","Document issued"),tone:"blue",phase:XD,external:Ze(ne("Dokument bereit","Document ready"),"amber",ne("Ihr Dokument liegt bereit","Your document is ready"),ne("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."),ne("Dokument beantworten","Respond to the document"))}},iF={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>Io,"processHoldTemplate"),progressDefaults:eF,progressEvents:Pt(eF),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:"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(!Hp(e))return[];let t=qi(e),n=[],r=t.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=t.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=t.checksReturn?[...i,"responseInCheck"]:i;return e.production!=="none"&&(n.push({id:Kb(e),kind:"internal",surface:Xs,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...v6(e)??{}}),n.push({id:xD,kind:"internal",surface:Xs,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:SD,kind:"internal",surface:Xs,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:Lp,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:i,external:{emphasis:"decline",event:"userTaskResolved"}}),t.producesResponseArtifact&&n.push({id:Mp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:Po,kind:"internal",surface:Xs,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:_o,kind:"internal",surface:Xs,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:AD,currentState:Ub,workItemTemplates:s(e=>{let t=e;return Hp(t)?jb(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e;if(!Hp(n)||n.production==="none")return[];let r=jb(n).find(i=>i.key===t);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:Wp(n)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[tF,y6]:[],...e.production==="template"?[nF]:[],g6,...Jp(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=b6(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"&&xi(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:el,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===Oo||t===ud||t===Mr||t===cn){let n=t===Oo?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===Mr?{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===cn?{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: ${Io}${e.approval==="release"?`, ${Lr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${Io}${e.approval==="release"?`, ${Lr}`:""}.`}}return t===Lr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Lr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Lr}" 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(ZD(t.node))return!1;let n=await Ub(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&qi(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=JD(t.node);if(n===null||ZD(t.node))return null;let r=await Ub(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Hp(e))return r.push(Re(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${qp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Do.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${jp.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 {${qp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Do.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${jp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=ii[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Re(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(Re(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(Re(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 v of o)v.visibility!=="external"&&r.push(Re(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${v.key}" auf Knoten "${e.id}" hat visibility "${v.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${v.key}" on node "${e.id}" has visibility "${v.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(v=>v.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(v=>l.includes(v)))&&r.push(Re(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(v=>`"${v}"`).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(v=>`"${v}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(v=>{let $=c?.[v];return $===null||typeof $!="object"||!Object.values($??{}).some(R=>typeof R=="string"&&R.length>0)},"missingTitle"),f=[];e.production!=="none"&&f.push("prepare","revise"),e.approval==="release"&&f.push("approve"),i.checksReturn&&f.push("check");let m=f.filter(u);m.length>0&&r.push(Re(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${m.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 ${m.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let y=e.assign??{};if(e.production!=="none"){let v=y.prepareDocument;(typeof v!="string"||v.length===0)&&r.push(Re(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.`}))}if(e.approval==="none"&&(y.releaseApproval!==void 0&&r.push(Re(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(Re(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){let v=y.responseCheck;(typeof v!="string"||v.length===0)&&r.push(Re(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(Re(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(Re(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(Re(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[v,$]of[["assign.responseCheck",y.responseCheck!==void 0],["titles.check",c?.check!==void 0]])$&&r.push(Re(e,v,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${v} \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 ${v} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"){let v=y.signingRecovery;(typeof v!="string"||v.length===0)&&r.push(Re(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.`}))}else y.signingRecovery!==void 0&&r.push(Re(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'.`}));if(i.issuesBy==="provider"&&r.push(...A6(e,n),...E6(e,n?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Re(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(Re(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(Re(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.`})),hd(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Re(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[v,$]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])$&&r.push(Re(e,v,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${v} \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 ${v} \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[v,$]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",y.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])$&&r.push(Re(e,v,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${v} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${v} \u2014 without a production phase there is nothing to carry it.`}));for(let v of e.tasks??[])Bb.has(v.key)&&r.push(Re(e,`tasks.${v.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${v.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...Bb].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${v.key}" on node "${e.id}" collides with an intrinsic template (${[...Bb].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...w6(e,n)):e.inputs?.[Fn]!==void 0&&r.push(Re(e,`inputs.${Fn}`,{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(...h6(e)),e.production==="resolver"){let v=Yr(e);if(v!==null){let $=nR(v);for(let R of Jp(e)){if(!Ei(R.type)){r.push(Re(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/unknownFieldType] Generator "${$}" typisiert das Feld "${R.key}" als "${String(R.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${xs.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${$}" types the field "${R.key}" as "${String(R.type)}" \u2014 that is not part of the platform's value vocabulary (${xs.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(R.type==="personList"){r.push(Re(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${$}" deklariert das Feld "${R.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 "${$}" declares the field "${R.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}R.type==="party"&&(R.key.endsWith("PartyId")||r.push(Re(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${R.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 "${R.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...rF(e,{de:`"${$}"`,en:`"${$}"`}))}}else e.generatorStamp!==void 0&&r.push(Re(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(...S6(e)):e.templateStamp!==void 0&&r.push(Re(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 k=e.inputs?.[ri],g=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return g!==void 0&&!fd(g)&&r.push(Re(e,`inputs.${ri}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(g)} \u2014 erlaubt ist eine ganze Zahl von ${No} bis ${Co} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(g)} \u2014 a whole number from ${No} to ${Co} days is allowed.`})),g===void 0&&Jp(e).some(v=>v.processSource==="responseDueInDays")&&r.push(Re(e,`inputs.${ri}`,{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 Qp="countersign",Vb="countersign",oF="countersigned",sF="countersigning",aF="countersigned",lF={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},gd=["scan","eSignature"],Zp="service_provider:1",dF=["countersigning","awaitingSignature","signatureStalled","done"],cF={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function uF(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(uF,"traegerSignatoryMissingReason");function Qn(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Qn,"issue");function mF(e,t){return e.nodes.filter(n=>{let r=n.contract;return n.type==="countersign"&&be(r)&&r.scope==="node"&&r.owner===t})}s(mF,"countersignersOf");function yd(e){return e.signing==="eSignature"}s(yd,"isElectronic");function T6(e,t){if(t===void 0||t.sendable||!yd(e))return[];let n=e.label?.de??e.id,r=e.label?.en||e.id;return[Qn(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${n}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${t.reason.en}`})]}s(T6,"countersignProviderIssues");function $6(e,t,n){if(n.scope!=="node")return[];let r=e.nodes.find(o=>o.id===n.owner);if(r===void 0)return[];let i=[];return zD(r)||i.push("sourceNotCheckedContract"),mF(e,r.id).some(o=>o.id!==t)&&i.push("twice"),i}s($6,"countersignContractRefusals");function fF(e){let t=e.inputs?.dueInDays;return t?.kind==="literal"&&typeof t.value=="number"&&Number.isInteger(t.value)&&t.value>=1?t.value:void 0}s(fF,"validDueInDays");function R6(e,t,n){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!gd.includes(o))return[Qn(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[cn];if(!yd(e))return a===void 0?[]:[Qn(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(Qn(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...I6(e,t,n),...O6(e,t,n),...T6(e,n?.signingProvider)),l}s(R6,"signingIssues");function hF(e,t){let n=e.contract;if(!(!be(n)||n.scope!=="node"))return t.nodes.find(r=>r.id===n.owner)}s(hF,"contractNodeOf");function I6(e,t,n){let r=hF(e,t),i=r===void 0?null:Dp(r),o=i===null?void 0:n?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[Qn(e,"signing",uF(o.name))]}s(I6,"traegerSignatoryIssues");function O6(e,t,n){let r=hF(e,t);if(r===void 0)return[];let i=n?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(Qn(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(Zp)||l.push(Qn(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Zp}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${Zp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(O6,"traegerAnchorIssues");var Gb=100;async function P6(e,t){let n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",t.applicationId).eq("context.anchor.nodeId",t.node.id)).take(Gb+1);n.length>Gb&&N(`countersign node "${t.node.id}" of ${t.applicationId} holds more than ${Gb} rows`);let r=n.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===cn)?"signatureStalled":r.some(o=>i(o)===Qp)?"countersigning":yd(t.node)?"awaitingSignature":"done"}s(P6,"countersignCurrentState");var pF={[sF]:{label:ne("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:ne("Gegenzeichnung","Countersignature"),scope:"node"},external:Ze(ne("Vertrag unterschrieben","Contract signed"),"blue",ne("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),ne("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},gF={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:oF,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:pF,progressEvents:Pt(pF),notificationEvents:s(()=>[{id:aF,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:Vb,kind:"internal",label:lF,surface:Jn,availableIn:["countersigning"]},...yd(e)?[{id:Po,kind:"internal",surface:Jn,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:_o,kind:"internal",surface:Jn,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Qp,recipient:"internal",title:e.titles?.countersign??ea,unlocks:[Vb],advancesNode:!0,...fF(e)!==void 0?{dueInDays:fF(e)}:{}},...yd(e)?[{key:cn,recipient:"internal",title:cF,unlocks:[Po,_o],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:dF,currentState:P6,validate:s((e,t,n)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[Qp];(typeof a!="string"||a.length===0)&&r.push(Qn(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),ki(e.titles?.countersign)||r.push(Qn(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(Qn(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...R6(e,t,n));let d=e.contract;if(!be(d))return r;let c=$6(t,e.id,d);if(c.length===0)return r;let u=t.nodes.find(f=>d.scope==="node"&&f.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(Qn(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let f=mF(t,u.id).filter(m=>m.id!==e.id);r.push(Qn(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${f.map(m=>`"${m.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${f.map(m=>`"${m.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};var yF={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:{}}};function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ln,"isRecord");var zb=["field","join","literal","address","payment","contract"],_6=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),N6=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function Zn(e){return typeof e=="string"&&e.trim().length>0}s(Zn,"nonEmptyString");function Xp(e,t,n,r,i="value"){if(!Ln(e)||!Ln(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=zb.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${zb.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${zb.join(" | ")}).`}});return}let[l]=a;l==="field"&&!Zn(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(Zn))&&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)||Zn(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"&&!(be(o.address)&&o.address.scope==="env"&&ar(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&&!_6.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&&!(Zn(e.lookup)&&Ln(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"||Ln(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Ln(d)&&N6.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(Xp,"checkMapping");function Ki(e,t,n,r,i){if(!Ln(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=yF[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))Xp(l,`${t}.${a}`,r,i)}s(Ki,"checkBody");function wF(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(!Ln(o)||!Zn(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),Xp(o.value,`${l}.value`,n,r),o.unless!==void 0&&Xp(o.unless,`${l}.unless`,n,r,"condition")})}s(wF,"checkAif");function Wb(e){let t=[];if(!Ln(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=Ln(e.lookups)?e.lookups:{};Ln(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))(!Ln(i)||!Object.values(i).every(Zn))&&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(Zn(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Ki(e.pupil,"engage.pupil","addPupil",n,t),Ki(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&Ki(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&Ki(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&Ki(e.medical,"engage.medical","addMedical",n,t),wF(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(!Ln(i)||!Zn(i.key)||!Zn(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),Ki(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&Ki(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,f)=>Ki(u,`${a}.${l}[${f}]`,d,n,t))}}wF(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&Xp(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Ln(r)||!Zn(r.repeated)||!Zn(r.field)||!Zn(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(Wb,"engagePushConfigIssues");function*Yb(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(Yb,"mappingsOf");function kF(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of Yb(e))for(let i of C6(n.from))t.add(D6(i,r));return[...t]}s(kF,"configFieldKeys");function C6(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(C6,"formFieldsOf");function D6(e,t){return e.startsWith(".")?(t===void 0&&N(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(D6,"resolveFieldKey");function bF(e,t){for(let{mapping:n}of Yb(e))if(t in n.from)return!0;return!1}s(bF,"configReadsSource");function vF(e){let t=new Set;for(let{mapping:n}of Yb(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(vF,"configEnvLeaves");var xF="done",SF=["sandbox","production"];var em="engagePush",uIe=660*1e3;function ji(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(ji,"issue");function Hb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Hb,"literal");function AF(e){return Wb(e.engage).length===0?e.engage:null}s(AF,"validConfig");function F6(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(F6,"bypassingPath");var EF={role:"system-action",effect:"side-effect",outcomes:[{id:xF,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=AF(e);return t===null?[]:vF(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=Hb(e,"target");SF.includes(a)||o.push(ji(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=Hb(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(ji(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`}));let d=e.assign?.[em];(typeof d!="string"||d.length===0)&&o.push(ji(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${em}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${em}\` names the team.`}));for(let g of Wb(e.engage))o.push(ji(e,g.path,{de:`[engagePush/config] \u201E${r}": ${g.message.de}`,en:`[engagePush/config] "${i}": ${g.message.en}`}));let c=t.nodes.filter(g=>g.id!==e.id&&g.type==="engagePush"&&Hb(g,"target")===a);c.length>0&&o.push(ji(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${c.map(g=>`"${g.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${c.map(g=>`"${g.id}"`).join(", ")} already transfers to the same target.`})),F6(t,e.id)&&o.push(ji(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 u=AF(e),f=e;for(let[g,v,$,R]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!bF(u,g)||f[v]!==void 0||o.push(ji(e,v,{de:Ts("address/missing",{where:`\u201E${r}\u201C \u203A ${$}`},"de"),en:Ts("address/missing",{where:`"${i}" \u203A ${R}`},"en")}));let m=f.form,y=be(m)&&m.scope==="node"?m.owner:void 0,k=y===void 0?void 0:n?.readinessFormFieldsByFormNode?.get(y);if(u!==null&&k!==void 0){let g=new Set(k.keys()),v=kF(u).filter($=>!g.has($)&&!/\[\d+\]\./.test($));if(v.length>0){let $=t.nodes.find(R=>R.id===y);o.push(ji(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${$?.label?.de??y}" nicht \u2014 sie werden nicht \xFCbertragen: ${v.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${$?.label?.en||y}" does not know these fields \u2014 they are not transferred: ${v.join(", ")}.`},"warning"))}}return o},"validate")};var Fo={join:FC,end:jI,roleAssign:MC,eventTrigger:qC,waitlist:tD,completenessCheck:dD,form:zC,setFlag:WC,if:YC,decision:Li,review:uD,collectPayment:yD,governedDocument:iF,countersign:gF,engagePush:EF};BR(Fo);function TF(e,t){let n=e;if(n==null||!Array.isArray(n.nodes))throw new Error(`offer plan: the ${t} carries no workflow graph with nodes`);return e}s(TF,"graphOf");function $F(e){let t=new Map;for(let n of e.nodes)for(let r of Ir(e,n))t.set(se(r.address),r.nodeId);return t}s($F,"producedOf");function RF(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(ho(e,n).map(r=>se(r.address))));return t}s(RF,"readsOf");function IF(e,t){let n=TF(e,"bundle"),r=TF(t.graph,"live head"),i=$F(n),o=$F(r),a={added:[],removed:[],moved:[]};for(let[u,f]of i){let m=o.get(u);m===void 0?a.added.push({address:u,nodeId:f}):m!==f&&a.moved.push({address:u,from:m,to:f})}for(let[u,f]of o)i.has(u)||a.removed.push({address:u,nodeId:f});let l=RF(n),d=RF(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let f=l.get(u)??new Set,m=d.get(u)??new Set,y=[...f].filter(g=>!m.has(g)),k=[...m].filter(g=>!f.has(g));(y.length>0||k.length>0)&&c.push({nodeId:u,added:y,removed:k})}return{headRevision:t.revision,pinnedApplications:t.pinnedApplications,produced:a,reads:c}}s(IF,"planAddresses");function OF(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(OF,"addressPlanRows");function PF(e,t){return t==null?!0:Pe(e)!==Pe(t)}s(PF,"changed");async function _F(e,t,n){if(t.index.module!==lb.name)throw new Error(`offer: unknown module "${t.index.module}"`);return QP(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return lb.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(_F,"applyOffer");async function NF(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(NF,"exportOffer");async function Jb(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,k]of Object.entries(t.smartforms??{})){let g=i?await e.query(S.forms.getSmartFormBySlug,{client:n.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=g?.def?PF(k,{label:g.def.label,...g.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}),k=y?.publishedVersion??y?.draftVersion;l=PF(k&&{graph:us(t.workflow.graph),progressLayout:t.workflow.progressLayout??k.progressLayout,progressWiring:t.workflow.progressWiring??k.progressWiring},k&&{graph:us(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let y=await e.query(S.workflow.getOfferHeadPins,{client:n.tenant,offerKey:n.slugs.manifest});y!==null&&(d=IF(t.workflow.graph,y))}}let c=n.program?.stages,u=c===void 0?[]:i?await ab(e,n.tenant,n.slugs.manifest,c):Tp(null,[],c),f=await Pp(e,n.tenant,i?n.slugs.manifest:null,n),m=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:f,publishPending:m?.draftDiffersFromExternal??null,draftRevision:m?.draftRevision??null,externalHeadRevision:m?.externalHeadRevision??null}}s(Jb,"diffOffer");function tm(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(tm,"contractProductionModeOf");function CF(e){return tm(e)==="resolver"}s(CF,"isResolverCarrierNode");function nm(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=Yr(n);return!CF(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(nm,"authoredPins");var DF={type:"address",dataType:"composite"};var FF={type:"boolean",dataType:"boolean"};var LF={type:"date",dataType:"date"};var MF={type:"docRef",dataType:"file"};var qF={type:"email",dataType:"text"};var KF={type:"enum",dataType:"option"};var jF={type:"string",dataType:"text"};var BF={type:"tel",dataType:"text"};var L6={address:DF.dataType,boolean:FF.dataType,date:LF.dataType,docRef:MF.dataType,email:qF.dataType,enum:KF.dataType,string:jF.dataType,tel:BF.dataType};function Qb(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(Qb,"shapeOf");function UF(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,Qb(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,Qb(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}`,Qb(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(UF,"fieldMapScopes");function M6(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(M6,"computedKeysOf");function VF(e){let t=[],n=M6(e);for(let r of UF(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(VF,"validateFieldMapSources");function GF(e){let t=[],n=new Set;for(let o of UF(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(GF,"validateFieldPersistence");var q6="$";function K6(e){return typeof e=="string"&&e.startsWith(q6)}s(K6,"isRef");function rm(e){return e.slice(1)}s(rm,"stripRef");function*j6(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(j6,"refSlots");function B6(e){let t=new Set;for(let n of j6(e))K6(n)&&t.add(rm(n));return[...t]}s(B6,"collectRefs");function U6(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 B6(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=rm(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&rm(l.target)===a||l.kind==="shareValue"&&rm(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(U6,"buildAdjacency");function zF(e){let{refsOf:t}=U6(e),r=Cf(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(zF,"detectCycle");function WF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(WF,"escapeRegExp");function Bi(e){return new RegExp(`^${WF(e)}\\[(\\d+)\\]\\.(.+)$`)}s(Bi,"repeatedRowKeyPattern");function Zb(e,t){let n=Bi(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(Zb,"countRepeatedRows");function YF(e,t,n){let r=Bi(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(YF,"repeatedRowHasData");function HF(e){return e.endsWith(".count")?e.slice(0,-6):e}s(HF,"readKeyOf");function Xb(e){return{sections:e,fields:[]}}s(Xb,"hiddenSectionsOnly");function JF(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??[])JF(r,t,n)}s(JF,"collectKeys");function QF(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;JF(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(Bi)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(QF,"restrictedSectionsOf");function ZF(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(ZF,"matchesKey");function V6(e,t){return t.find(n=>ZF(e,n))??null}s(V6,"hiddenSectionOfKey");function G6(e,t){for(let n=e;;){if(ZF(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(G6,"fieldOwnsKey");function z6(e,t){return t.find(n=>G6(e,n))??null}s(z6,"restrictedFieldOfKey");function W6(e,t){let n=V6(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=z6(e,t.fields);return r===null?null:{kind:"field",field:r}}s(W6,"hiddenOwnerOfKey");function im(e,t){return W6(e,t)!==null}s(im,"isKeyHidden");function Y6(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(Y6,"visibleToListIssues");function XF(e,t,n){let r=[],i=s((c,u,f)=>{let m=c.visibleTo;m!==void 0&&r.push(...Y6(c.id,m,`${u}.visibleTo`,f,n));let y=f||m!==void 0;if(y){let k=[...c.fields,...(c.groups??[]).flatMap(g=>g.fields),...(c.repeated??[]).flatMap(g=>g.itemTemplate)];for(let g of k)g.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${g.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${g.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,g)=>i(k,`${u}.subsections[${g}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=QF(e);if(o.length===0)return r;let a=s((c,u,f)=>{if(c===void 0)return;let m=Xb(f);for(let y of kt(c)){let k=HF(y);(im(y,m)||im(k,m))&&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,f)=>{a(c.visibleIf,`${u}.visibleIf`,f),a(c.requiredIf,`${u}.requiredIf`,f),a(c.disabledIf,`${u}.disabledIf`,f),a(c.defaultValue,`${u}.defaultValue`,f),c.sameAs!==void 0&&im(c.sameAs.source,Xb(f))&&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,f)=>{let m=c.visibleTo!==void 0?c.id:f,y=o.filter(k=>k.sectionId!==m);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((k,g)=>l(k,`${u}.fields[${g}]`,y)),c.groups?.forEach((k,g)=>{a(k.visibleIf,`${u}.groups[${g}].visibleIf`,y),k.fields.forEach((v,$)=>l(v,`${u}.groups[${g}].fields[${$}]`,y))}),c.repeated?.forEach((k,g)=>{a(k.itemVisibleIf,`${u}.repeated[${g}].itemVisibleIf`,y),k.itemTemplate.forEach((v,$)=>l(v,`${u}.repeated[${g}].itemTemplate[${$}]`,y))}),c.computed?.forEach((k,g)=>a(k.expression,`${u}.computed[${g}]`,y)),c.subsections?.forEach((k,g)=>d(k,`${u}.subsections[${g}]`,m))},"visitCompiled");return t.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(XF,"sectionVisibilityIssues");var qr="#";var eL=s(e=>{let t=Aw.find(n=>n.systemColumn===e);return t===void 0&&N(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),mr={firstName:eL("persons.firstName"),lastName:eL("persons.lastName")};function tL(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===mr.firstName?n.firstName.push(o):a===mr.lastName&&n.lastName.push(o);return n}s(tL,"personNameKeys");function nL(e){return[...e.firstName,...e.lastName]}s(nL,"personNameKeyList");function rL(e){return e.firstName.length>0||e.lastName.length>0}s(rL,"hasPersonName");function ta(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 ta(i.subsections??[],a,i.id))r.push(l)}),r}s(ta,"walkSections");function H6(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(H6,"findFieldInSection");function iL(e,t){for(let n of ta(e.sections)){let r=H6(n.section,t);if(r)return{section:n.section,field:r}}return null}s(iL,"findField");var J6=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],Q6=["blue","rose","amber","violet","teal","emerald","slate"];function oL(e){return J6.includes(e)}s(oL,"isBucketIconName");function sL(e){return Q6.includes(e)}s(sL,"isBucketColorName");var Z6="__clear__";function aL(e){return e===""?"empty":e===Z6?"reserved":null}s(aL,"selectOptionValueDefect");var aPe=Object.freeze({});function X6(e,t){return Object.freeze(If(zr,e,t))}s(X6,"formContextEntries");function lL(e){return e.env??[]}s(lL,"declaredContextKeys");function dL(e,t){return lL(e).every(n=>cL(n,t?.[n]))}s(dL,"scenarioContextComplete");function cL(e,t){return bO(zr,e,t)}s(cL,"contextValueComplete");function uL(e,t){return X6(t??{},lL(e))}s(uL,"scenarioContextEntries");function tv(e){return kl(e)}s(tv,"isContextIdentifier");function e4(e,t,n){let r=Rf(zr,e);if(r!==null)return{severity:"error",path:n,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return t.has(i)?null:{severity:"error",path:n,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(e4,"contextIdentifierIssue");var ev=ju("stage.key");function t4(e){let t=[],n=s(i=>i.kind==="ident"&&i.path===ev,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(n(i.left)&&i.right.kind==="str"&&t.push(i.right.value),n(i.right)&&i.left.kind==="str"&&t.push(i.left.value)),i.op==="in"&&n(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&t.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),t}s(t4,"stageKeyLiterals");function fL(e,t,n){return t===void 0?[]:t4(e).filter(r=>!t.has(r)).map(r=>mL(r,t,n))}s(fL,"stageKeyAstIssues");function pL(e,t){if(t===void 0)return[];let n=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!t.has(i.key)&&n.push(mL(i.key,t,`scenario:${r.id}/env`))}return n}s(pL,"scenarioStageKeyIssues");function mL(e,t,n){let r=[...t].sort();return{severity:"error",path:n,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${ev}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${ev}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(mL,"unknownStageKeyIssue");function hL(e,t,n){let r=[];for(let i of kt(e)){if(!tv(i))continue;let o=e4(i,t,n);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Ly(e,qu))r.push({severity:"error",path:n,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(hL,"contextAstIssues");function gL(e,t){let n=[...n4(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!cs(i)){n.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${ds.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${ds.join(", ")}).`}});continue}t!==void 0&&!t.has(i)&&n.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>cs(a)&&!cL(a,i.env?.[a]));o.length>0&&n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))cs(a)?r.has(a)||n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return n}s(gL,"formContextIssues");function n4(e){let t=[];Object.hasOwn(e,"context")&&t.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let n=e.testScenarios;for(let r of Array.isArray(n)?n:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&t.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return t}s(n4,"retiredContextFields");var nv=J_.docRef.allowedMime;function vL(e,t={}){let n=qs(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 f(P,I){if(i.has(P))return;i.add(P);let B=o.get(P.id);B&&B!==P?r.push({severity:"error",path:`sections[${I.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${P.id}' ist mehrfach deklariert.`,en:`Section id '${P.id}' is declared more than once.`}}):o.set(P.id,P);let D=`sections[${I.join(".")}]`;P.fields.forEach((X,ce)=>{na(a,X.key,`${D}.fields[${ce}]`,"duplicate.field-key",r),l.add(X.key),u.set(X.key,X),c.set(X.key,iv(X)),X.externalFlag&&(X.type!=="boolean"&&r.push({severity:"error",path:`${D}.fields[${ce}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${X.key}' muss den Typ 'boolean' haben (ist '${X.type}').`,en:`External flag '${X.key}' must be type 'boolean' (got '${X.type}').`}}),X.notice!==void 0&&r.push({severity:"error",path:`${D}.fields[${ce}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${X.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${X.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),X.defaultValue==null&&r.push({severity:"error",path:`${D}.fields[${ce}]`,code:"flag.missing-default",message:{de:`Externes Flag '${X.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${X.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...yL(X,`${D}.fields[${ce}]`))}),P.groups?.forEach((X,ce)=>{X.fields.forEach((fe,xe)=>{na(a,fe.key,`${D}.groups[${ce}].fields[${xe}]`,"duplicate.field-key",r),l.add(fe.key),u.set(fe.key,fe),c.set(fe.key,iv(fe)),fe.externalFlag&&r.push({severity:"error",path:`${D}.groups[${ce}].fields[${xe}]`,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(...yL(fe,`${D}.groups[${ce}].fields[${xe}]`))})}),P.repeated?.forEach((X,ce)=>{X.itemTemplate.forEach((fe,xe)=>{na(a,fe.key,`${D}.repeated[${ce}].itemTemplate[${xe}]`,"duplicate.field-key",r),c.set(fe.key,iv(fe)),fe.externalFlag&&r.push({severity:"error",path:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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.notice!==void 0&&r.push({severity:"error",path:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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.`}})})}),P.computed?.forEach(X=>{d.add(X.key),na(a,X.key,`${D}.computed[${X.key}]`,"duplicate.field-key",r),X.export===!0&&X.exportType===void 0&&r.push({severity:"error",path:`${D}.computed[${X.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${X.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${X.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),P.subsections?.forEach((X,ce)=>f(X,[...I,ce]))}s(f,"visitRawSection"),e.sections.forEach((P,I)=>f(P,[I]));let m=new Set;n.effects.forEach((P,I)=>{na(m,P.id,`effects[${I}]`,"duplicate.effect-id",r)});let y=new Set;n.outcomes.forEach((P,I)=>{na(y,P.id,`outcomes[${I}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((P,I)=>{P.output.effectRefs?.forEach((B,D)=>{m.has(B.effect)||r.push({severity:"error",path:`outcomes[${I}].output.effectRefs[${D}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${P.id}' verweist auf den unbekannten Effekt '${B.effect}'.`,en:`Outcome '${P.id}' references unknown effect '${B.effect}'.`}})})}),n.outcomes.forEach((P,I)=>{P.output.fields?.forEach((B,D)=>{iL(n,B.path)||r.push({severity:"error",path:`outcomes[${I}].output.fields[${D}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${P.id}' verweist auf das unbekannte Feld '${B.path}'.`,en:`Outcome '${P.id}' references unknown field '${B.path}'.`}})})});let k=new Set;for(let P of ta(n.sections))for(let I of P.section.repeated??[])k.add(`${I.key}.count`);for(let P of k)(a.has(P)||d.has(P))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${P}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${P}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let g={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...gL(e)),r.push(...XF(e,n,t.visibleToKeys)),r.push(...pL(e,t.stageKeys));for(let P of ta(n.sections)){let I=P.section,B=`sections[${P.path.join(".")}]`;I.visibleIf&&(hr(I.visibleIf,`${B}.visibleIf`,g,!1,r),ra(I.visibleIf,`${B}.visibleIf`,c,r)),I.fields.forEach((D,X)=>rv(D,`${B}.fields[${X}]`,g,!1,c,r)),I.groups?.forEach((D,X)=>{D.visibleIf&&(hr(D.visibleIf,`${B}.groups[${X}].visibleIf`,g,!1,r),ra(D.visibleIf,`${B}.groups[${X}].visibleIf`,c,r)),D.fields.forEach((ce,fe)=>rv(ce,`${B}.groups[${X}].fields[${fe}]`,g,!1,c,r))}),I.repeated?.forEach((D,X)=>{D.itemVisibleIf&&(hr(D.itemVisibleIf,`${B}.repeated[${X}].itemVisibleIf`,g,!0,r),ra(D.itemVisibleIf,`${B}.repeated[${X}].itemVisibleIf`,c,r)),D.itemTemplate.forEach((ce,fe)=>rv(ce,`${B}.repeated[${X}].itemTemplate[${fe}]`,g,!0,c,r)),D.effects?.forEach((ce,fe)=>{ce.when&&hr(ce.when,`${B}.repeated[${X}].effects[${fe}].when`,g,!0,r)})}),I.computed?.forEach((D,X)=>hr(D.expression,`${B}.computed[${X}].expression`,g,!1,r))}n.effects.forEach((P,I)=>{P.when&&hr(P.when,`effects[${I}].when`,g,!1,r)}),n.outcomes.forEach((P,I)=>{hr(P.when,`outcomes[${I}].when`,g,!1,r)});let v=new Set(n.outcomes.map(P=>P.id));function $(P,I){P.requiredFor&&P.requiredFor.forEach((B,D)=>{v.has(B)||r.push({severity:"error",path:`${I}.requiredFor[${D}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${P.key}": requiredFor verweist auf das unbekannte Ergebnis "${B}"`,en:`field "${P.key}": requiredFor references unknown outcome "${B}"`}})})}s($,"checkRequiredFor");for(let P of ta(n.sections)){let I=P.section,B=`sections[${P.path.join(".")}]`;I.fields.forEach((D,X)=>$(D,`${B}.fields[${X}]`)),I.groups?.forEach((D,X)=>{D.fields.forEach((ce,fe)=>$(ce,`${B}.groups[${X}].fields[${fe}]`))}),I.repeated?.forEach((D,X)=>{D.itemTemplate.forEach((ce,fe)=>$(ce,`${B}.repeated[${X}].itemTemplate[${fe}]`))})}function R(P,I){let B=s((D,X)=>{let ce=(D.type==="docRef"?D.docRefConstraints?.mimeType??[]:[]).filter(xe=>!nv.includes(xe));ce.length>0&&r.push({severity:"error",path:X,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${D.key}' erlaubt ${ce.map(xe=>`'${xe}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${nv.join(", ")}).`,en:`Field '${D.key}' allows ${ce.map(xe=>`'${xe}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${nv.join(", ")}).`}}),D.multiple===!0&&D.type!=="enum"&&r.push({severity:"error",path:X,code:"config.multiple-non-enum",message:{de:`Feld '${D.key}' setzt multiple: true, hat aber den Typ '${D.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(D.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${D.key}' sets multiple: true but is type '${D.type}' \u2014 only 'enum' supports multi-select.`+(D.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),D.presentation==="yesNo"&&D.type!=="boolean"&&r.push({severity:"error",path:X,code:"config.yesno-non-boolean",message:{de:`Feld '${D.key}' setzt presentation: 'yesNo', hat aber den Typ '${D.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${D.key}' sets presentation: 'yesNo' but is type '${D.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),D.presentation==="yesNo"&&D.defaultValue!=null&&r.push({severity:"error",path:X,code:"config.yesno-default",message:{de:`Feld '${D.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 '${D.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),typeof D.minSelections=="number"&&typeof D.maxSelections=="number"&&D.minSelections>D.maxSelections&&r.push({severity:"error",path:X,code:"config.min-gt-max-selections",message:{de:`Feld '${D.key}' hat minSelections (${D.minSelections}) > maxSelections (${D.maxSelections}).`,en:`Field '${D.key}' has minSelections (${D.minSelections}) > maxSelections (${D.maxSelections}).`}});let fe=D.enumRef;fe!==void 0&&r.push({severity:"error",path:`${X}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${D.key}' nennt den entfernten Options-Katalog (enumRef '${String(fe)}'). Die Optionen im Formular angeben (enumOptions + enumOptionLabels) oder eine Liste des Mandanten binden (enumListKey).`,en:`Field '${D.key}' names the removed option catalog (enumRef '${String(fe)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(D.enumOptions??[]).forEach((xe,Ge)=>{let ft=aL(xe);ft!==null&&r.push({severity:"error",path:`${X}.enumOptions[${Ge}]`,code:"config.enum-option-value",message:{de:ft==="empty"?`Feld '${D.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 '${D.key}' hat den Enum-Optionswert '${xe}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:ft==="empty"?`Field '${D.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 '${D.key}' has the enum option value '${xe}', which the single select reserves for its clear row. Rename the option.`}})}),(D.attachments??[]).forEach((xe,Ge)=>{if("storageId"in xe){r.push({severity:"error",path:`${X}.attachments[${Ge}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${D.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 '${D.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 ft=xe.fileKey!==void 0&&xe.fileKey!=="",ot=xe.url!==void 0&&xe.url!=="";ft===ot&&r.push({severity:"error",path:`${X}.attachments[${Ge}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${D.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${ft&&ot?"beide":"keines"}).`,en:`Field '${D.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${ft&&ot?"both":"neither"}).`}}),xe.renderAs==="inlineLink"&&xe.label===void 0&&r.push({severity:"error",path:`${X}.attachments[${Ge}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${D.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${D.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");P.fields.forEach((D,X)=>B(D,`${I}.fields[${X}]`)),P.groups?.forEach((D,X)=>{D.fields.forEach((ce,fe)=>B(ce,`${I}.groups[${X}].fields[${fe}]`))}),P.repeated?.forEach((D,X)=>{D.itemTemplate.forEach((ce,fe)=>B(ce,`${I}.repeated[${X}].itemTemplate[${fe}]`))}),P.subsections?.forEach((D,X)=>R(D,`${I}.subsections[${X}]`))}s(R,"visitFieldConfig"),e.sections.forEach((P,I)=>R(P,`sections[${I}]`)),e.effects.forEach((P,I)=>{if(P.kind==="person"){r.push(...bL(P,e.effects,`effects[${I}]`,B=>l.has(B)));return}P.kind==="organization"&&P.nameFrom?.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nameFrom[${D}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${P.id}': nameFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${P.id}' nameFrom references unknown field '${B}'.`}})})});let A=s((P,I)=>{if(P.kind!=="person"&&P.kind!=="organization")return;let B=P.display;if(!B){r.push({severity:"error",path:`${I}.display`,code:"display.missing",message:{de:`Effekt '${P.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${P.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}oL(B.icon)||r.push({severity:"error",path:`${I}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${P.id}': display.icon '${B.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${P.id}' display.icon '${B.icon}' is not a known bucket icon.`}}),sL(B.color)||r.push({severity:"error",path:`${I}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${P.id}': display.color '${B.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${P.id}' display.color '${B.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((P,I)=>A(P,`effects[${I}]`));let O=new Set,F=s(P=>{P.kind==="person"?O.add(P.bucket):P.kind==="organization"&&O.add(P.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(F);let b=new Set,E=s(P=>{for(let I of P)I.repeated?.forEach(B=>B.effects?.forEach(D=>F(D))),E(I.subsections??[])},"collectRepeatedBuckets");E(e.sections);let q=s((P,I)=>{O.size!==0&&P.forEach((B,D)=>{B.bucket===void 0||O.has(B.bucket)||r.push({severity:"error",path:`${I}[${D}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${B.key}' geh\xF6rt zum Bucket '${B.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${B.key}' belongs to bucket '${B.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),_=s((P,I)=>{if(b.has(P))return;b.add(P);let B=`sections[${I.join(".")}]`;q(P.fields,`${B}.fields`),P.groups?.forEach((D,X)=>q(D.fields,`${B}.groups[${X}].fields`)),P.repeated?.forEach((D,X)=>q(D.itemTemplate,`${B}.repeated[${X}].itemTemplate`)),P.subsections?.forEach((D,X)=>_(D,[...I,X]))},"visitBucketSection");e.sections.forEach((P,I)=>_(P,[I]));let H=e.effects.flatMap((P,I)=>P.kind==="person"&&P.subject===!0?[{e:P,i:I}]:[]);H.length>1&&H.slice(1).forEach(({e:P,i:I})=>{r.push({severity:"error",path:`effects[${I}].subject`,code:"subject.duplicate",message:{de:`Effekt '${P.id}' deklariert subject:true, aber '${H[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${P.id}' declares subject:true, but '${H[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((P,I)=>{if(!(P.kind!=="person"||P.nationalityFrom===void 0)){if(P.subject!==!0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${P.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 '${P.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(P.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${P.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${P.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}P.nationalityFrom.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nationalityFrom[${D}]`,code:"nationality.unknown-field",message:{de:`Effekt '${P.id}': nationalityFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${P.id}' nationalityFrom references unknown field '${B}'.`}})})}});let W=e.effects.flatMap((P,I)=>P.kind==="person"&&P.contractParty!==void 0?[{e:P,i:I,decl:P.contractParty}]:[]);if(W.length>0){let P=W.filter(({decl:I})=>I.role==="beneficiary");P.slice(1).forEach(({e:I,i:B})=>{r.push({severity:"error",path:`effects[${B}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${I.id}' deklariert contractParty.role 'beneficiary', aber '${P[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${I.id}' declares contractParty.role 'beneficiary', but '${P[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),P.forEach(({e:I,i:B})=>{I.subject!==!0&&r.push({severity:"error",path:`effects[${B}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${I.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 '${I.id}' setzen.`,en:`Effect '${I.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 '${I.id}'.`}})}),H.forEach(({e:I,i:B})=>{let D=I.contractParty?.role;D!==void 0&&D!=="beneficiary"&&r.push({severity:"error",path:`effects[${B}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${I.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${D}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${I.id}' is the application subject but declares contractParty.role '${D}'. The application subject is the contract beneficiary.`}})}),W.some(({decl:I})=>I.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((P,I)=>{P.kind==="fieldMap"&&P.mappings.forEach((B,D)=>{a.has(B.from)||r.push({severity:"error",path:`effects[${I}].mappings[${D}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${P.id}': fieldMap from '${B.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${P.id}' fieldMap from '${B.from}' references unknown field.`}})})});for(let[P,I]of u){if(!I.sameAs)continue;let B=`fields[${P}].sameAs`,D=u.get(I.sameAs.source);D===void 0||I.sameAs.source===P?r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:I.sameAs.source===P?`Feld '${P}': sameAs.source verweist auf sich selbst.`:`Feld '${P}': sameAs.source verweist auf das unbekannte Feld '${I.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:I.sameAs.source===P?`Field '${P}' sameAs.source references itself.`:`Field '${P}' sameAs.source references unknown field '${I.sameAs.source}' (must be a top-level or group field).`}}):D.type!==I.type?r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}' (${I.type}): sameAs.source '${I.sameAs.source}' hat einen anderen Typ (${D.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${P}' (${I.type}) sameAs.source '${I.sameAs.source}' has a different type (${D.type}) \u2014 the mirror must be shape-identical.`}}):D.sameAs&&r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}': sameAs.source '${I.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${P}' sameAs.source '${I.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let X=u.get(I.sameAs.toggle);(X===void 0||X.type!=="boolean")&&r.push({severity:"error",path:`${B}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:X===void 0?`Feld '${P}': sameAs.toggle verweist auf das unbekannte Feld '${I.sameAs.toggle}'.`:`Feld '${P}': sameAs.toggle '${I.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${X.type}').`,en:X===void 0?`Field '${P}' sameAs.toggle references unknown field '${I.sameAs.toggle}'.`:`Field '${P}' sameAs.toggle '${I.sameAs.toggle}' must be type 'boolean' (got '${X.type}').`}}),I.required===!0&&r.push({severity:"error",path:`fields[${P}].required`,code:"config.sameas-static-required",message:{de:`Feld '${P}' 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: "${I.sameAs.toggle} != true" verwenden.`,en:`Field '${P}' 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: "${I.sameAs.toggle} != true".`}})}{let P=new Map;e.effects.forEach(I=>P.set(I.id,I.kind)),e.effects.forEach((I,B)=>{if(I.kind!=="shareValue")return;[["from",I.from],["to",I.to]].forEach(([ce,fe])=>{let xe=P.get(fe.slice(1));xe!==void 0&&xe!=="person"&&xe!=="organization"&&r.push({severity:"error",path:`effects[${B}].${ce}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${I.id}': shareValue ${ce} '${fe}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${xe}').`,en:`Effect '${I.id}' shareValue ${ce} '${fe}' must reference a person/organization effect (got '${xe}').`}})});let D=I.from.slice(1);e.effects.some(ce=>ce.kind==="fieldMap"&&ce.target.slice(1)===D&&ce.mappings.some(fe=>fe.to===I.field)||ce.kind==="shareValue"&&ce.id!==I.id&&ce.to.slice(1)===D&&ce.field===I.field)||r.push({severity:"error",path:`effects[${B}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${I.id}' teilt das Feld '${I.field}' aus '${I.from}', aber kein fieldMap mit Ziel '${I.from}' bildet auf '${I.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${I.id}' shares field '${I.field}' from '${I.from}', but no fieldMap targeting '${I.from}' maps to '${I.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((P,I)=>{P.kind==="person"&&P.bucket.includes(qr)&&r.push({severity:"error",path:`effects[${I}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': bucket '${P.bucket}' darf '${qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' bucket '${P.bucket}' must not contain '${qr}' (reserved for the per-row namespace).`}}),P.kind==="organization"&&P.orgKind.includes(qr)&&r.push({severity:"error",path:`effects[${I}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': orgKind '${P.orgKind}' darf '${qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' orgKind '${P.orgKind}' must not contain '${qr}' (reserved for the per-row namespace).`}})});let de=new Set;function J(P,I){P.repeated?.forEach((B,D)=>{let X=B.effects??[];if(X.length>0){let ce=`${I}.repeated[${D}]`,fe=new Set(X.map(ie=>ie.id)),xe=new Set(B.itemTemplate.map(ie=>ie.key)),Ge=(B.uniqueBy?.length??0)>0,ft=s(ie=>ie.startsWith("$item.")?xe.has(ie.slice(6)):l.has(ie),"resolvesName"),ot=s(ie=>ie.startsWith("$item.")?xe.has(ie.slice(6)):a.has(ie),"resolvesFrom"),Ht=s(ie=>{let Nt=ie.slice(1);return fe.has(Nt)||m.has(Nt)},"resolvesRef");X.forEach((ie,Nt)=>{let pt=`${ce}.effects[${Nt}]`;if(m.has(ie.id)||de.has(ie.id)?r.push({severity:"error",path:pt,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${ie.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${ie.id}' is declared more than once.`}}):de.add(ie.id),ie.kind==="person"||ie.kind==="organization"){A(ie,pt),ie.kind==="person"&&ie.subject===!0&&r.push({severity:"error",path:`${pt}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${ie.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 '${ie.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.`}}),ie.kind==="person"&&ie.nationalityFrom!==void 0&&r.push({severity:"error",path:`${pt}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${ie.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${ie.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),ie.kind==="person"&&ie.contractParty!==void 0&&r.push({severity:"error",path:`${pt}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${ie.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 '${ie.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ge||r.push({severity:"error",path:ce,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${B.key}' hat einen Parteien erzeugenden Effekt '${ie.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${B.key}' has a party-creating effect '${ie.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Ne=ie.kind==="person"?ie.bucket:ie.orgKind;Ne.includes(qr)&&r.push({severity:"error",path:`${pt}.${ie.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${ie.id}' der Wiederholung: ${ie.kind==="person"?"bucket":"orgKind"} '${Ne}' darf '${qr}' nicht enthalten.`,en:`Repeated effect '${ie.id}' ${ie.kind==="person"?"bucket":"orgKind"} '${Ne}' must not contain '${qr}'.`}}),ie.kind==="person"&&r.push(...bL(ie,X,pt,ft)),ie.kind==="organization"&&ie.nameFrom?.forEach((Ue,Rn)=>{ft(Ue)||r.push({severity:"error",path:`${pt}.nameFrom[${Rn}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${ie.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Ue}'.`,en:`Repeated effect '${ie.id}' nameFrom references unknown field '${Ue}'.`}})}),ie.identity?.strategy==="keyed"&&ie.identity.keyFrom.forEach((Ue,Rn)=>{ot(Ue)||r.push({severity:"error",path:`${pt}.identity.keyFrom[${Rn}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${ie.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Ue}'.`,en:`Repeated effect '${ie.id}' identity.keyFrom references unknown field '${Ue}'.`}})})}else if(ie.kind==="relationship"){if([["from",ie.from],["to",ie.to]].forEach(([Ne,Ue])=>{Ht(Ue)||r.push({severity:"error",path:`${pt}.${Ne}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: ${Ne} verweist auf den unbekannten Effekt '${Ue}'.`,en:`Repeated relationship '${ie.id}' ${Ne} references unknown effect '${Ue}'.`}})}),ie.meta)for(let[Ne,Ue]of Object.entries(ie.meta))typeof Ue=="string"&&Ue.startsWith("$")&&!Ht(Ue)&&r.push({severity:"error",path:`${pt}.meta.${Ne}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: meta.${Ne} verweist auf den unbekannten Effekt '${Ue}'.`,en:`Repeated relationship '${ie.id}' meta.${Ne} references unknown effect '${Ue}'.`}})}else ie.kind==="fieldMap"?(Ht(ie.target)||r.push({severity:"error",path:`${pt}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${ie.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${ie.target}'.`,en:`Repeated fieldMap '${ie.id}' target references unknown effect '${ie.target}'.`}}),ie.mappings.forEach((Ne,Ue)=>{ot(Ne.from)||r.push({severity:"error",path:`${pt}.mappings[${Ue}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${ie.id}' der Wiederholung: from '${Ne.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${ie.id}' from '${Ne.from}' references unknown field.`}})})):ie.kind==="shareValue"&&r.push({severity:"error",path:pt,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${ie.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${ie.id}': shareValue is not supported inside repeated row effects.`}})})}}),P.subsections?.forEach((B,D)=>J(B,`${I}.subsections[${D}]`))}s(J,"visitRepeatedEffects"),e.sections.forEach((P,I)=>J(P,`sections[${I}]`));let oe=zF(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(...r4(e)),r}s(vL,"validateForm");function r4(e){let t={...e,effects:e.effects.map(xL),sections:e.sections.map(SL),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return Lf(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:Gy(n)}))}s(r4,"missingTranslationIssues");function xL(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(xL,"withoutSubjectFlag");function SL(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(xL)})),subsections:e.subsections?.map(SL)}}s(SL,"withoutRowSubjectFlags");function yL(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(yL,"exportGateIssues");function na(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${wL(r,"de")} '${t}'`,en:`Duplicate ${wL(r,"en")}: '${t}'`}}):e.add(t)}s(na,"reportIfDup");function wL(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(wL,"labelForCode");function rv(e,t,n,r,i,o){e.visibleIf&&(hr(e.visibleIf,`${t}.visibleIf`,n,r,o),ra(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(hr(e.requiredIf,`${t}.requiredIf`,n,r,o),ra(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(hr(e.disabledIf,`${t}.disabledIf`,n,r,o),ra(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&hr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(rv,"checkFieldAsts");function iv(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo"}}s(iv,"gatingMeta");function ra(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(kL(o.left,o.right,o.op,t,n,r),kL(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(ra,"checkGatingExpr");function kL(e,t,n,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);a&&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(kL,"inspectEqualityOperand");function hr(e,t,n,r,i){i.push(...hL(e,n.declaredContext,t)),i.push(...fL(e,n.stageKeys,t));for(let o of kt(e))n.known.has(o)||tv(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(hr,"checkAst");function bL(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 ${mr.firstName} / ${mr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${mr.firstName} / ${mr.lastName}. Remove nameFrom.`}});let o=tL(e.id,t);rL(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${mr.firstName} oder ${mr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${mr.firstName} or ${mr.lastName} \u2014 the person would get no name.`}});for(let a of nL(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(bL,"personNameIssues");var i4="blocked";function AL(e,t){let n={values:t};for(let r of e.outcomes){let i;try{i=gt(r.when,n)}catch(o){N(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(o4(i))return r.id===i4?null:r.id}return null}s(AL,"resolveActiveOutcome");function o4(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(o4,"truthy");function EL(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(EL,"isScalar");function s4(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(EL(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))EL(a)&&(t[`${r}.${o}`]=a)}a4(e,t,n)}s(s4,"mergeRecord");function a4(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);Bi(a).test(i)&&r.add(a)}for(let i of r){let o=Zb(e,i),a=0;for(let l=0;l<o;l++)YF(e,i,l)&&a++;t[`${i}.count`]=a}}s(a4,"mergeRepeatedCounts");function TL(e,t,n){let r={...n};return s4(e,r,t),r}s(TL,"flattenValues");function ov(e,t,n){return{code:e,fieldKey:t,text:n}}s(ov,"submitIssue");function $L(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s($L,"truthyEval");function RL(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(RL,"isEmptyValue");function l4(e,t,n){let r=!!e.required;if(!r&&e.requiredIf)try{r=$L(gt(e.requiredIf,{values:t}))}catch{r=!1}return r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(l4,"fieldIsLiveRequired");function d4(e,t,n){return IL(e,t,n).evalCtx}s(d4,"buildSubmitEvalContext");function IL(e,t,n){let r=c4(e),i=Object.keys(t).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[y,k]of Object.entries(t))(r(y)===null||o.has(y))&&(l[y]=k);let d=OL(e,l,n),c=new Set,u=new Set;_L(e,d,y=>c.add(y.key),y=>u.add(y.key));let f=new Set(i.filter(y=>{let k=r(y);return k.kind==="field"?c.has(y):u.has(k.repeatedKey)}));if(f.size===o.size&&[...f].every(y=>o.has(y))){let y={};for(let k of i)o.has(k)||(y[k]=t[k]);return{visible:l,hidden:y,evalCtx:d}}let m=[...f].sort().join("\0");if(a.has(m)){let y=i.filter(k=>f.has(k)!==o.has(k));N(`[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(m),o=f}}s(IL,"splitWithContext");function c4(e){let t=new Map,n=[];for(let r of sm(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:Bi(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(c4,"fieldOwnership");function OL(e,t,n){let r=[];for(let o of sm(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=TL(t,r,n);for(let o of sm(e.sections))for(let a of o.computed??[])try{i[a.key]=gt(a.expression,{values:i})}catch{}return i}s(OL,"rawEvalContext");function PL(e,t,n){let{values:r,defaulted:i}=u4(e,t,n),o=IL(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(PL,"splitDraftValues");function u4(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of sm(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??=OL(e,t,n);let c;try{c=gt(d.defaultValue,{values:a})}catch(u){N(`[smartForm] defaultValue of '${d.key}' does not evaluate: ${u instanceof Error?u.message:String(u)}`)}c!=null&&(i[d.key]=c,o.add(d.key))}return{values:i,defaulted:o}}s(u4,"applyFieldDefaults");function sm(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(sm,"walkSectionsDeep");function f4(e,t,n,r=!1){if(RL(t))return null;let i=n.fields[e.type];i||N(`[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(f4,"fieldFormatIssue");function om(e,t){if(!e)return!0;try{return $L(gt(e,{values:t}))}catch{return!1}}s(om,"isVisibleUnder");function _L(e,t,n,r){let i=s(o=>{if(om(o.visibleIf,t)){for(let a of o.fields)om(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(om(a.visibleIf,t))for(let l of a.fields)om(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(_L,"forEachVisibleField");function NL(e,t,n,r={}){let i=d4(e,t,n),o=[],a=AL(e,i);a===null&&r.requireOutcome!==!1&&o.push(ov("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 _L(e,i,d=>{let c=t[d.key];if(RL(c)){!l.has(d.type)&&l4(d,i,a)&&o.push(ov("required",d.key,Va([d.label],([f],m)=>m==="de"?`${f} ist ein Pflichtfeld.`:`${f} is a required field.`)));return}if(!r.registry)return;let u=f4(d,c,r.registry,r.testMode===!0);u!==null&&o.push(ov("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(NL,"checkSubmittable");function CL(e){let t=e.testScenarios??[];if(t.length===0)return[];let{compiled:n}=qs(e),r=[];for(let i of t){let o=i.prefill??{};if(!dL(e,i.env))continue;let a=uL(e,i.env),{visible:l}=PL(n,o,a),d=NL(n,l,a,{exemptFromRequired:["docRef"]});for(let c of d.issues){if(c.code==="no-outcome"){r.push({severity:"error",path:`scenario:${i.id}`,code:"scenario.no-outcome",message:{de:`Szenario "${i.label.de}" erreicht kein g\xFCltiges Outcome \u2013 der Testfall ist nicht absendbar.`,en:`Scenario "${i.label.en}" reaches no valid outcome \u2013 the test case cannot be submitted.`}});continue}if(c.code==="required"){r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.required-field-unfilled",message:{de:`Szenario "${i.label.de}" l\xE4sst das Pflichtfeld ${c.fieldKey} unbef\xFCllt \u2013 kein g\xFCltiges Outcome.`,en:`Scenario "${i.label.en}" leaves the required field ${c.fieldKey} empty \u2013 no valid outcome.`}});continue}r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.invalid-value",message:Va([i.label,c.text],([u,f],m)=>m==="de"?`Szenario "${u}": ${f}`:`Scenario "${u}": ${f}`)})}}return r}s(CL,"validateScenarios");function am(e){return e.filter(t=>(t.severity??"error")==="error")}s(am,"blockingIssues");function lm(e,t={}){return[...vL(e,t),...CL(e)]}s(lm,"runFormValidators");function dm(e){return am(e)}s(dm,"blockingFormErrors");function DL(e,t,n){return PP(e,t,n)}s(DL,"runWorkflowValidators");function FL(e){return am(e)}s(FL,"blockingWorkflowErrors");var p4=["artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],LL={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"]},review:{required:[],optional:["commentRequired","decisionAsTask","reads"]},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"]}},un={id:w.string(),label:Gs,artifacts:w.optional(w.any()),assign:w.optional(w.any()),inputs:w.optional(w.any()),library:w.optional(w.any()),next:w.optional(w.any()),notifications:w.optional(w.any()),optionalActions:w.optional(w.any()),outcomes:w.optional(w.any()),outputLabels:w.optional(w.any()),sublabel:w.optional(w.any()),tasks:w.optional(w.any())},m4=w.object({...un,type:w.literal("join")}),h4=w.object({...un,type:w.literal("end")}),g4=w.object({...un,type:w.literal("eventTrigger")}),y4=w.object({...un,type:w.literal("form"),adoptForm:w.optional(w.any()),formExports:w.optional(w.any())}),w4=w.object({...un,type:w.literal("roleAssign")}),k4=w.object({...un,type:w.literal("setFlag")}),b4=w.object({...un,type:w.literal("if"),condition:w.optional(w.any())}),v4=w.object({...un,type:w.literal("countersign"),contract:w.optional(w.any()),signing:w.optional(w.any()),titles:w.optional(w.any())}),x4=w.object({...un,type:w.literal("engagePush"),contract:w.optional(w.any()),engage:w.optional(w.any()),form:w.optional(w.any()),payment:w.optional(w.any())}),S4=w.object({...un,type:w.literal("decision"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any()),requiresOneOf:w.optional(w.any())}),A4=w.object({...un,type:w.literal("review"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any())}),E4=w.object({...un,type:w.literal("waitlist")}),T4=w.object({...un,type:w.literal("completenessCheck"),deadline:w.optional(w.any()),requires:w.optional(w.any())}),$4=w.object({...un,type:w.literal("collectPayment")}),R4=w.object({...un,type:w.literal("governedDocument"),approval:w.optional(w.any()),confirmBeforeIssue:w.optional(w.any()),confirmContractTerms:w.optional(w.any()),contractTermsQuestionText:w.optional(w.any()),form:w.optional(w.any()),generatorStamp:w.optional(w.any()),production:w.optional(w.any()),reads:w.optional(w.any()),responseLabels:w.optional(w.any()),responseStrategy:w.optional(w.any()),templateStamp:w.optional(w.any()),titles:w.optional(w.any())}),p_e=w.union(m4,h4,g4,y4,w4,k4,b4,v4,x4,S4,A4,E4,T4,$4,R4);function ML(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 LL)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=LL[a],d=new Set(["id","type","label",...p4,...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(ML,"workflowNodeEnvelopeIssues");function qL(e,t){return e.enumOptionLabels?.[t]??{de:t,en:t}}s(qL,"inlineEnumOptionLabel");var jL={string:"string",boolean:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function BL(e){return jL[e]!==void 0}s(BL,"isExportableFieldType");function I4(e){return e.exportType===void 0&&N(`formExports: computed '${e.key}' is exported without an exportType \u2014 the publish validator should have refused this form.`),{key:e.key,type:e.exportType,label:e.label??{de:e.key,en:e.key}}}s(I4,"leafForComputed");function KL(e){let t=jL[e.type];return t===void 0&&N(`formExports: field '${e.key}' has type '${e.type}', which is not exportable \u2014 the publish validator should have refused this form.`),{key:e.key,type:t,label:e.label,...e.enumOptions!==void 0?{enumOptions:e.enumOptions.map(n=>({value:n,label:qL(e,n)}))}:{}}}s(KL,"leafFor");function sv(e){let t=[],n=s(r=>{for(let i of r.fields)i.export===!0&&t.push(KL(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&t.push(KL(o));for(let i of r.computed??[])i.export===!0&&t.push(I4(i));for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(sv,"exportedFormLeaves");var UL=s(e=>e,"asEffectId"),Ui=s(e=>e,"asOutcomeId"),ia=s(e=>e,"asSectionId"),nn=s(e=>e,"asFieldKey");var oi=["string","boolean","date","enum","email","tel","address","docRef"],wd=["person","organization","relationship","fieldMap"],Vi=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],oa=["fresh","keyed","manual"];function Lo(e,t,n,r){if(e===void 0||e===""){if(t!==void 0&&t!=="")throw new Error(`${n}: ${r}-en needs ${r} too`);return}return ct(e,t,n,r)}s(Lo,"optionalLocalizedText");function zt(e,t){if(!(e===void 0||e===""))try{qt(e)}catch(n){throw new Error(`offer form: ${t} is not a valid expression: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}s(zt,"assertExpression");function kd(e){return Object.keys(e.smartforms??{})}s(kd,"carriedFormSlugs");function av(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(av,"boundFormSlugs");function cm(e,t){let n=kd(e);if(t){if(!n.includes(t))throw new Error(`offer form: no smartform "${t}" in this bundle (have: ${n.join(", ")||"none"})`);return t}if(n.length===0)throw new Error("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(n.length>1)throw new Error(`offer form: bundle carries ${n.length} smartforms \u2014 pass --form <key> (one of: ${n.join(", ")})`);return n[0]}s(cm,"resolveFormSlug");function um(e,t){let n=e.smartforms?.[t];if(!n)throw new Error(`offer form: smartform "${t}" not found in bundle`);return n}s(um,"getForm");function Mn(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(Mn,"walkSections");function Xn(e,t){return Mn(e).find(n=>n.id===t)}s(Xn,"findSection");function Mo(e,t){for(let n of Mn(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Mo,"findField");function qo(e){let t=new Set;for(let n of Mn(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(qo,"allFieldKeys");function O4(e){let t=ct(e.label,e.labelEn,"offer form add"),n={id:ia("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Ui("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(O4,"buildSkeletonSmartForm");function fm(e,t){let{key:n,label:r}=t;if(kd(e).includes(n))throw new Error(`offer form add: smartform "${n}" already exists in this bundle`);let i=O4({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(fm,"addForm");function VL(e,t){if(!kd(e).includes(t))throw new Error(`offer form rm: smartform "${t}" not found in bundle`);if(av(e).includes(t))throw new Error(`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(VL,"removeForm");function GL(e,t){let n=um(e,t.slug);if(t.label===void 0&&t.labelEn===void 0)throw new Error("offer form set: nothing to change \u2014 pass --label/--label-en");if(t.label==="")throw new Error("offer form set: --label cannot be empty");yt(n,"label",{de:t.label,en:t.labelEn},"offer form set")}s(GL,"setForm");function zL(e,t){let n=e.workflow?.graph?.nodes;if(!Array.isArray(n))throw new Error(`${t}: the bundle carries no workflow graph (workflow.json)`);return n}s(zL,"nodesOf");function WL(e,t,n){let r=zL(e,n),i=r.find(o=>o.id===t);if(i===void 0)throw new Error(`${n}: no node "${t}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(WL,"nodeOf");function YL(e){return e.flatMap(t=>{if(t.type!=="form"||kn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(YL,"creatingFormNodes");function HL(e){return dm(lm(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(HL,"formErrors");function pm(e){let t="offer workflow restamp-exports",n=zL(e,t),r=[];for(let{node:i,slug:o}of YL(n)){let a=e.smartforms?.[o];if(a===void 0)throw new Error(`${t}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=HL(l);if(d.length>0)throw new Error(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
10344
+ `)}return this.print(r,i=>i.slots.map(o=>{let a=i.override?.[o.key];return{block:o.key,label:o.label,deviates:a===void 0?"":"yes",text:(a??o.default).replace(/\s+/g," ").slice(0,80)}}),["block","label","deviates","text"]),0}},eb=class extends C{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=T.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=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=p.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let t=eJ(this.slot,this.slotFile);if(Object.keys(t).length===0)throw new Error("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:ib(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}},tb=class extends C{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=T.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=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"Block key to reset (repeatable)"});all=p.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 Error("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&t.length===0)throw new Error("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:ib(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}},ad=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function Ap(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":ad(t[r],""),...n===null?{}:{platform:ad(n[r],"")}}))}s(Ap,"chromeTextRows");var nb=class extends C{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=T.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=>[...Ap("greeting",r.greeting,r.defaults.greeting),...Ap("closing",r.closing,r.defaults.closing),{field:"senderName",school:ad(r.senderName,"\u2014 (platform)"),platform:ad(r.defaults.senderName,"")}],["field","school","platform"]),0}},rb=class extends C{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=T.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=p.String("--greeting-de",{description:"Opening line, German"});greetingEn=p.String("--greeting-en",{description:"Opening line, English"});closingDe=p.String("--closing-de",{description:"Sign-off, German"});closingEn=p.String("--closing-en",{description:"Sign-off, English"});senderName=p.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 Error(`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 Error("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=>[...Ap("greeting",l.greeting,null),...Ap("closing",l.closing,null),{field:"senderName",school:ad(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},IC=[Wk,Yk,Hk,Jk,Qk,Zk,Xk,eb,tb,nb,rb];var nJ="-stufe-",rJ=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ob(e){return`${e}${nJ}`}s(ob,"stageKeyPrefix");function sb(e,t){return`${ob(e)}${t}`}s(sb,"stageStorageKey");function PC(e,t){let n=ob(e);return t.startsWith(n)&&t.length>n.length}s(PC,"isUnderProgram");function Fr(e,t){let n=ob(e);return PC(e,t)||ae("CONFLICT",{de:`[stage/foreignKey] Der Stufenschl\xFCssel \u201E${t}\u201C liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C). F\xFChren Sie die Stufe in bundle.yaml unter einem neuen Schl\xFCssel auf; der n\xE4chste Apply archiviert diese Zeile (hinter der Archivsperre) und legt die Stufe mit dem neuen Schl\xFCssel an.`,en:`[stage/foreignKey] The level key "${t}" is not under the program "${e}" (expected: "${n}<key>"). List the level in bundle.yaml under a new key; the next apply archives this row (behind the archive lock) and creates the level with the new key.`}),t.slice(n.length)}s(Fr,"bareStageKey");function Ep(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=Et(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.stages[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"stage/nameMissing",index:i,message:{de:`[stage/nameMissing] ${l}: jede Klassenstufe braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[stage/nameMissing] ${l}: every stage needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"stage/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"stage/keyMissing",index:i,message:{de:`[stage/keyMissing] ${l}: jede Klassenstufe braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[stage/keyMissing] ${l}: every stage needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!rJ.test(d)){t.push({code:"stage/keyInvalid",index:i,message:{de:`[stage/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[stage/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"stage/duplicateKey",index:i,message:{de:`[stage/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.stages[${c}] verwendet`,en:`[stage/duplicateKey] ${l}: key "${d}" is already used by program.stages[${c}]`}});return}n.set(d,i)}),t}s(Ep,"stageSpecIssues");function OC(e){return{de:e.de.trim(),en:e.en.trim()}}s(OC,"trimmedText");function iJ(e,t){let n=[];return e.de!==t.de&&n.push(`"${e.de}" \u2192 "${t.de}"`),e.en!==t.en&&n.push(`en "${e.en}" \u2192 "${t.en}"`),n.join(", ")}s(iJ,"describeNameChange");function Tp(e,t,n){if(e===null)return t.length>0&&N("planStageReconcile: stages exist but the offer has no program key"),n.map((a,l)=>({op:"insert",key:a.key,name:OC(a.name),...a.gradeLevel!==void 0?{gradeLevel:a.gradeLevel}:{},sequence:l+1}));let r=new Map(t.map(a=>[a.key,a])),i=new Set,o=[];n.forEach(({name:a,...l},d)=>{let c={...l,name:OC(a)},u=sb(e,c.key);i.add(u);let f=d+1,m=r.get(u);if(m===void 0){o.push({op:"insert",key:c.key,name:c.name,...c.gradeLevel!==void 0?{gradeLevel:c.gradeLevel}:{},sequence:f});return}let y={};as(m.name,c.name)||(y.name=[m.name,c.name]);let k=m.gradeLevel??null,g=c.gradeLevel??null;k!==g&&(y.gradeLevel=[k,g]),m.sequence!==f&&(y.sequence=[m.sequence,f]),(Object.keys(y).length>0||m.archived)&&o.push({op:"update",key:c.key,stageId:m.stageId,name:c.name,changes:y,unarchive:m.archived})});for(let a of[...t].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:PC(e,a.key)?Fr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(Tp,"planStageReconcile");function $p(e){switch(e.op){case"insert":return`+stage ${e.key} (${e.name.de})`;case"archive":{let t=e.occupancy,n=[...t&&t.activeApplications>0?[`REFUSED: ${t.activeApplications} active application(s) \u2014 [stage/hasActiveApplications]`]:[],...t&&t.openLeads>0?[`${t.openLeads} open lead(s)`]:[]];return`-stage ${e.key} (${e.name.de})${n.length>0?` \u2014 ${n.join("; ")}`:""}`}case"update":{let t=[];if(e.unarchive&&t.push("restored"),e.changes.name&&t.push(iJ(e.changes.name[0],e.changes.name[1])),e.changes.gradeLevel){let[n,r]=e.changes.gradeLevel;t.push(`grade ${n??"\u2013"} \u2192 ${r??"\u2013"}`)}return e.changes.sequence&&t.push(`position ${e.changes.sequence[0]} \u2192 ${e.changes.sequence[1]}`),`~stage ${e.key} (${t.join(", ")})`}}}s($p,"describeStageStep");var oJ=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ni(e,t){return`${e}-${t}`}s(ni,"runStorageKey");function _C(e,t){typeof t!="string"&&ae("CONFLICT",{de:`[run/keyNotServed] Das Deployment liefert f\xFCr ein Schuljahr von \u201E${e}\u201C keinen Schl\xFCssel \u2014 es l\xE4uft ein \xE4lteres Release als die CLI. Nach dem n\xE4chsten Release erneut versuchen.`,en:`[run/keyNotServed] The deployment provides no key for a school year of "${e}" \u2014 it runs an older release than the CLI. Try again after the next release.`});let n=`${e}-`;return(!t.startsWith(n)||t.length===n.length)&&ae("CONFLICT",{de:`[run/foreignKey] Der Schl\xFCssel \u201E${t}\u201C des Schuljahrs liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C).`,en:`[run/foreignKey] The key "${t}" of the school year is not under the program "${e}" (expected: "${n}<key>").`}),t.slice(n.length)}s(_C,"bareRunKey");function Rp(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=Et(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.runs[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"run/nameMissing",index:i,message:{de:`[run/nameMissing] ${l}: jedes Schuljahr braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[run/nameMissing] ${l}: every run needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"run/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"run/keyMissing",index:i,message:{de:`[run/keyMissing] ${l}: jedes Schuljahr braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[run/keyMissing] ${l}: every run needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!oJ.test(d)){t.push({code:"run/keyInvalid",index:i,message:{de:`[run/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[run/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"run/duplicateKey",index:i,message:{de:`[run/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.runs[${c}] verwendet`,en:`[run/duplicateKey] ${l}: key "${d}" is already used by program.runs[${c}]`}});return}n.set(d,i)}),t}s(Rp,"runSpecIssues");var sJ={capacity:null,isOpen:!1},aJ={capacity:null,isOpen:!0};function lJ(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(lJ,"isCapacity");function Ip(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)||!lJ(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(Ip,"capacitySpecIssues");function CC(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(Fr(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(f=>f.key===ni(r,c.key));if(u===void 0&&!a.has(c.key))throw new Error(`offer[admission]: run "${c.key}" does not exist and is not created by this apply`);for(let[f,m]of Object.entries(c.capacities)){let y=i.get(f);if(y===void 0&&!o.has(f))throw new Error(`offer[admission]: capacities of run "${c.key}" name stage "${f}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let k={capacity:m.capacity,isOpen:m.isOpen},g=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,v=g!==void 0?{capacity:g.capacity,isOpen:g.isOpen}:u===void 0?sJ:aJ;v.capacity===k.capacity&&v.isOpen===k.isOpen||d.push({run:c.key,stageKey:f,from:v,to:k})}}return d}s(CC,"planRunCapacities");function NC(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(NC,"describeCell");function Op(e){return`~cap ${e.run}\xD7${e.stageKey} ${NC(e.from)} \u2192 ${NC(e.to)}`}s(Op,"describeCapacityStep");function DC(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(DC,"assertBackendHasStageKeys");async function ab(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}));DC(i);let a=Tp(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 f=c.get(u.stageId);if(f===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:f.activeApplications,openLeads:f.openLeads}}})}s(ab,"planStages");async function Pp(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});DC(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Fr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return CC(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===ni(d,c)))})}s(Pp,"planCapacities");async function dJ(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===ni(a,d)&&c.status==="archived"));if(l.length>0)throw new Error(`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(dJ,"assertNoArchivedRunKey");var lb={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...Ep(o??[]),...Rp(n.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(g=>g.message.de).join("; ")}`);let l=Ip(n.program?.runs??[],o?.map(g=>g.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await dJ(e,i,t,n);let d=await Pp(e,i,t,n),c=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=cJ(n);if(!u)throw new Error("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let f=c.units.find(g=>g.key===u);if(!f)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(g=>g.key===null?[]:[g.key]).join(", ")||"(none)"}`);let m=[];if(r.dryRun||(await e.mutation(S.programAdmin.ensurePedagogyUnit,{client:i,unitId:f.unitId}),await e.mutation(S.programAdmin.createProgramForAngebot,{client:i,offerKey:t,unitId:f.unitId,...n.program?.key!==void 0?{programKey:n.program.key}:{}})),m.push(`unit=${u}`),o!==void 0)if(r.dryRun){let g=await ab(e,i,t,o);m.push(...g.map($p))}else{let g=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}:{}}))});m.push(...g.steps,...g.warnings.map(v=>`warning ${v}`))}let y=r.dryRun?c:await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t});for(let g of n.program?.runs??[]){let v=y.programKey===null?void 0:y.runs.find($=>$.key===ni(y.programKey,g.key));if(v!==void 0){as(v.name,g.name)||(r.dryRun||await e.mutation(S.programAdmin.updateProgramRun,{client:i,offerKey:t,runId:v.runId,name:g.name}),m.push(`~run ${g.key} ("${_e(v.name)}" \u2192 "${_e(g.name)}")`));continue}r.dryRun||await e.mutation(S.programAdmin.addProgramRun,{client:i,offerKey:t,key:g.key,name:g.name,isOpen:g.capacities!==void 0?!1:g.isOpen??!0,...g.startDate?{startDate:g.startDate}:{},...g.endDate?{endDate:g.endDate}:{}}),m.push(`+run ${g.key} (${_e(g.name)})`)}let k=r.dryRun?d:await Pp(e,i,t,n);if(!r.dryRun&&k.length>0){let g=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),v=g.programKey;if(v===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let $ of k){let R=g.runs.find(O=>O.key===ni(v,$.run))?.runId,A=g.stages.find(O=>Fr(v,O.key)===$.stageKey)?.stageId;if(R===void 0||A===void 0)throw new Error(`offer[admission]: cell ${$.run}\xD7${$.stageKey} vanished between plan and write`);await e.mutation(S.programAdmin.setRunStageCapacity,{client:i,offerKey:t,runId:R,stageId:A,capacity:$.to.capacity,isOpen:$.to.isOpen})}}return m.push(...k.map(Op)),m.join(", ")}};function cJ(e){let t=e.program?.unitKey,n=e.links?.unitKey;if(t!==void 0&&n!==void 0&&t!==n)throw new Error(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${t}" and links.unitKey "${n}"; keep one`);return t??n}s(cJ,"bundleUnitKey");var FC={role:"control",effect:"pure",cardinality:"N-to-1"};var _p=["add","remove","replace"];function LC(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(LC,"roleAssignLiteral");var MC={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=LC(e,"roleKey")?.trim()??"",o=LC(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"}),_p.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 ${_p.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${_p.join(" | ")}.`},severity:"error"}),r},"validate")};var uJ=["event","effect","outcomes"],db=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),qC={outcomes:[{id:dr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of uJ)i in r&&n.push(db(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${dr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${dr}" itself.`));return On(t.nodes).some(i=>i.target===e.id)&&n.push(db(`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?.[dr]===void 0&&n.push(db(`nodes.${e.id}.next.${dr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${dr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${dr}" nowhere.`)),n},"validate")};var fJ="submit",KC=[{id:fJ,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function jC(e){return e==="draft"}s(jC,"isWritableSmartFormState");var cb=["draft","committed"],WSe=cb.filter(e=>jC(e));async function BC(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&&N(`application ${t}: two form instances for node "${n}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(BC,"getSmartFormInstance");var UC="form:fill",ub="request:collectPayment";var pJ={key:UC,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},VC={key:"bearbeitung",label:ne("In Bearbeitung","In progress"),scope:"node"},GC={[F$]:{label:ne("In Bearbeitung","In progress"),tone:"neutral",phase:VC,external:Ze(ne("Entwurf","Draft"),"neutral",ne("Bewerbung fortsetzen","Continue application"),ne("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."),ne("Bewerbung fortsetzen","Continue application"),"continue-form")},[Du]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:VC,external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung ist eingereicht","Your application has been submitted"),ne("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."))}},zC={role:"user-action",effect:"side-effect",progressDefaults:GC,progressEvents:Pt(GC),actions:s(()=>KC,"actions"),workItemTemplates:s(()=>[pJ],"workItemTemplates"),states:cb,currentState:s(async(e,t)=>{let n=await BC(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=>kn(e)?[]:[{id:Fu,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 WC={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Tt.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Tt.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Tt.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:rI(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[];e.inputs?.[Tt.flagKey]?.kind==="literal"&&rf(e)===null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Tt.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?.[Tt.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Tt.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 mJ="true",hJ="false",fb=[{id:mJ,label:{de:"Ja",en:"Yes"}},{id:hJ,label:{de:"Nein",en:"No"}}];var YC={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:fb,validate:s((e,t,n)=>gJ(e,t,n),"validate")};function gJ(e,t,n){let r=s(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${d.de}`,en:`[if/condition] Node "${e.id}": ${d.en}`},severity:"error"}),"issue"),i=fb.filter(d=>e.next?.[d.id]===void 0).map(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${d.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${d.label.de}\u201C (${d.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${d.label.en}" (${d.id}) leads nowhere.`},severity:"error"}));if(typeof e.condition!="string"||e.condition.trim()==="")return[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})];let o=Q$(t),a=_f(e.condition,o).filter(d=>d.severity==="error").map(d=>r(d.message)),l=[...i,...a];if(a.length>0||n?.liveEnvKeys===void 0)return l;for(let d of Fy(e.condition,o)){let c=DO(d.path,n.liveEnvKeys);c===null&&N(`[if/condition] no live-key universe for '${d.path}' \u2014 extend liveKeyUniverse`),c.has(d.value)||l.push(r({de:`$env.${d.path} == '${d.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${d.path} == '${d.value}' names no key of this school.`}))}return l}s(gJ,"ifNodeIssues");var ld="decision",yJ=new Set(["decision","review"]),kAe=new Set([...yJ,"governedDocument"]);var JC=[{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"}],HC={released:{label:ne("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:ne("Freigabe","Release"),scope:"node"},external:Ze(ne("Freigegeben","Released"),"green",ne("Ihre Bewerbung wurde freigegeben","Your application has been released"),ne("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."))}},Li={role:"user-action",effect:"side-effect",outcomes:JC,progressDefaults:HC,progressEvents:Pt(HC),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,...vi(t.semantic)?{semantic:t.semantic}:{}})),...mP(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:ld,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===ld&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),validate:pb};function pb(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(f=>typeof f=="string"&&f.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 ${wn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${wn.join(", ")}.`},severity:"error"}):vi(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: ${wn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${wn.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(pb,"validateDecisionNode");var mb=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],QC=[{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 Jn="processFooter";var hb="promoted";var ZC="promote",XC="Nachr\xFCcken";var gb={key:"warteliste",label:ne("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},eD={waitlisted:{label:ne("Warteliste","Waitlisted"),tone:"amber",phase:gb,external:Ze(ne("Warteliste","Waiting list"),"amber",ne("Sie stehen auf der Warteliste","You are on the waiting list"),ne("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:ne("Nachger\xFCckt","Promoted"),tone:"green",phase:gb,external:Ze(ne("Nachger\xFCckt","Moved up"),"green",ne("Sie sind nachger\xFCckt","You have moved up"),ne("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:ne("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:gb,external:Ze(ne("Warteliste geschlossen","Waiting list closed"),"red",ne("Die Warteliste wurde geschlossen","The waiting list has been closed"),ne("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},tD={outcomes:mb,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Gn.map(e=>({value:e,label:lR[e]}))},{id:"autoPromoteOnVacancy",label:{de:"Bei freiem Platz automatisch nachr\xFCcken",en:"Promote automatically when a place frees up"},type:"boolean",required:!0,inspector:"literal-only"}],"inputs"),validate:s((e,t)=>{let n=Pg(e);if(n===null)return[];let r=t.nodes.filter(o=>o.type==="waitlist"&&o.id!==e.id),i=t.nodes.indexOf(e);for(let o of r){if(t.nodes.indexOf(o)>i)continue;let a=Pg(o);if(a!==null&&!(a.waitlistOrder===n.waitlistOrder&&a.autoPromoteOnVacancy===n.autoPromoteOnVacancy))return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${o.id}" und "${e.id}" nennen verschiedene Regeln (Reihenfolge, automatisches Nachr\xFCcken) \u2014 eine Kohorte hat EINE Warteliste.`,en:`[waitlist/policyConflict] Waiting lists "${o.id}" and "${e.id}" state different rules (order, automatic promotion) \u2014 a cohort has ONE waiting list.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:eD,progressEvents:Pt(eD),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:mb).some(n=>n.id===hb)?[{id:ZC,kind:"advance",outcome:hb,semantic:"other",label:{de:XC,en:"Promote from waitlist"},surface:Jn,superUserOnly:!0}]:[],"actions")};var wJ="complete",Np="acceptedIncomplete",Cp="rejected",kJ="absage",nD="closeWithoutDocuments",rD="rejectAtCompleteness",iD="Ohne Nachreichung abschlie\xDFen",oD="Ablehnen",sD="awaitingDocuments",yb="documentsComplete",wb="closedWithoutDocuments",kb="rejected",bb="withdrawn",aD="requested",jAe={[wJ]:{event:yb,status:"complete",endsRole:!0},[Np]:{event:wb,status:"acceptedIncomplete",endsRole:!1},[Cp]:{event:kb,status:"rejected",endsRole:!0},[kJ]:{event:bb,status:"withdrawn",endsRole:!0}};var dd=s(()=>nl[0],"beneficiary"),vb=366;function bJ(e){let t=e.reads,n=rl(e).flatMap(({address:r})=>at(r)&&!nl.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(at):[],...n]}s(bJ,"printedFields");function vJ(e,t){let n=se(t);return e.nodes.filter(r=>r.type==="governedDocument"&&bJ(r).some(i=>se(i)===n))}s(vJ,"documentsPrinting");function xJ(e,t){if(!at(t)||t.path!==dd())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!kn(n)}s(xJ,"isCreatedFormBeneficiary");function Gt(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Gt,"issue");var xb={key:"unterlagen",label:ne("Unterlagen nachreichen","Outstanding documents"),scope:"node"},lD={[sD]:{label:ne("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:xb,external:Ze(ne("Unterlagen fehlen","Documents missing"),"amber",ne("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),ne("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."))},[yb]:{label:ne("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:xb,external:Ze(ne("Unterlagen vollst\xE4ndig","Documents complete"),"green",ne("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),ne("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[wb]:{label:ne("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:xb,external:Ze(ne("Abgeschlossen","Closed"),"neutral",ne("Die Nachreichung ist abgeschlossen","The document request is closed"),ne("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[kb]:{label:ne("Abgelehnt","Rejected"),tone:"red",phase:qI,external:Ze(ne("Abgelehnt","Rejected"),"red",ne("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),ne("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."))},[bb]:{label:ne("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:wf,external:Ze(ne("Zur\xFCckgezogen","Withdrawn"),"red",ne("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),ne("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},dD={outcomes:QC,progressDefaults:lD,progressEvents:Pt(lD),notificationEvents:s(()=>[{id:aD,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(Np)&&n.push({id:nD,kind:"advance",outcome:Np,semantic:"other",label:{de:iD,en:"Close without documents"},surface:Jn,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(Cp)&&n.push({id:rD,kind:"advance",outcome:Cp,semantic:"rejected",label:{de:oD,en:"Reject application"},surface:Jn,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($=>Be(t,$,"de"),"shown"),l=s($=>Be(t,$,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Gt(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 $=new Set;for(let R of d){if(!be(R))continue;let A=se(R);if($.has(A)){r.push(Gt(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(R)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(R)} appears twice in \`requires\`.`}));continue}if($.add(A),!at(R)){r.push(Gt(e,"requires",{de:`[completenessCheck/unknownField] ${a(R)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(R)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let O=Pr(n,R);if(O==null)continue;let F=Oi("requires",Ii(O));F==="computed"||F==="repeated"?r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(R)} ist ${O.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(R)} is ${O.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):F==="untranslated"&&r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(R)} (\u201E${Ri(O,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 der Brief \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l(R)} ("${Ri(O,"de")}") has no English name (field or person/section) \u2014 the letter "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},f="inDays"in u,m="until"in u;if(f===m)r.push(Gt(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(f){let $=u.inDays;(typeof $!="number"||!Number.isInteger($)||$<0||$>vb)&&r.push(Gt(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String($)}" ist keine ganze Zahl von 0 bis ${vb} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String($)}" is not a whole number from 0 to ${vb} days.`}))}else typeof u.until!="string"||xy(u.until)===null?r.push(Gt(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<rO(Date.now())&&r.push({...Gt(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 $=new Map(d.filter(at).map(R=>[se(R),R]));for(let R of $.values())for(let A of vJ(t,R))r.push(Gt(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(R)} flie\xDFt in das Dokument \u201E${A.label?.de??A.id}" (${A.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(R)} flows into the document "${A.label?.en||A.id}" (${A.id}) \u2014 once it is issued, the family can no longer submit it later. Remove the field from \`requires\` or from the document.`}))}let y=e.inputs?.guestRole,k=y?.kind==="literal"?y.value:void 0,g=e.inputs?.person,v=g?.kind==="binding"?g.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Gt(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(k)?r.push(Gt(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${k}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${k}" does not exist in this school's role catalog. Known roles: ${[...n.roleKeys].sort().join(", ")}.`})):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(k)&&r.push(Gt(e,"inputs.guestRole",{de:`[completenessCheck/nonLeafRole] Rolle "${k}" hat untergeordnete Rollen und ist nicht vergebbar.`,en:`[completenessCheck/nonLeafRole] Role "${k}" has sub-roles and cannot be assigned.`})),v===null&&r.push(Gt(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${tn}.${dd()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${tn}.${dd()}).`}))),be(v)&&!xJ(t,v)&&r.push(Gt(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>.${tn}.${dd()}).`,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>.${tn}.${dd()}).`})),v!==null&&k===void 0&&r.push(Gt(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 $ of["complete","rejected"])e.next?.[$]===void 0&&r.push(Gt(e,`next.${$}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${$}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${$}" nowhere.`}));return r},"validate")};var SJ=[{id:cR,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],cd=s(e=>e,"asDecision"),cD={[uR]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:ne("In Pr\xFCfung","In review"),scope:"node"},external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),ne("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."))}},uD={role:"user-action",effect:"side-effect",outcomes:SJ,progressDefaults:cD,progressEvents:Pt(cD),notificationEvents:s(e=>Li.notificationEvents(cd(e)),"notificationEvents"),actions:s(e=>[...Li.actions(cd(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:Cg,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Li.optionalActionKinds,workItemTemplates:s(e=>Li.workItemTemplates(cd(e)).map(t=>t.key===ld?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,Cg]}:t),"workItemTemplates"),taskDocuments:s((e,t)=>Li.taskDocuments(cd(e),t),"taskDocuments"),validate:s((e,t,n)=>{let r=pb(cd(e),t,n),i=Array.isArray(e.reads)?e.reads:[];for(let o of e.outcomes??[]){let a=o.semantic;typeof a!="string"||!Hu.includes(a)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/rejectingOutcome] Pr\xFCf-Knoten "${e.id}" deklariert das Outcome "${o.id}" mit der Bedeutung "${String(a)}" \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 "${o.id}" meaning "${String(a)}" \u2014 a review neither rejects nor waitlists; that is the decision of the approval or "Reject application".`},severity:"error"})}for(let o of i){if(!at(o))continue;let a=Pr(n,o);a==null||Oi("nodeReads",Ii(a),e.type)!=="computed"||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.reads`,reason:{de:`[review/readsNotTickable] Pr\xFCf-Knoten \u201E${e.label?.de??e.id}\u201C (${e.id}) soll das berechnete Feld ${se(o)} abhaken lassen \u2014 nur eingegebene Felder haben einen Wert, den jemand pr\xFCfen kann.`,en:`[review/readsNotTickable] Review node "${e.label?.en||e.id}" (${e.id}) is to tick off the computed field ${se(o)} \u2014 only entered fields have a value someone can check.`},severity:"error"})}return r},"validate")};var fD=["awaitingAnswer","answered"];async function pD(e,t){return(await gl(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(pD,"externalRequestState");var gD=[{id:As,label:{de:"Bezahlt",en:"Paid"}}],SEe=new Set(gD.map(e=>e.id));var AJ=As,mD=[{id:AJ,kind:"advance",outcome:As,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],EJ={id:dy,kind:"advance",outcome:As,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:Jn,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"}}},TJ={id:dy,kind:"advance",outcome:As,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:Jn,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 Sb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Sb,"literalOf");function Zs(e){let t=Sb(e,zn);return lf(t)?t:null}s(Zs,"settlementOrNull");function $J(e){let t=Sb(e,Ti);return typeof t=="string"&&t.length>0?t:null}s($J,"articleKeyOrNull");function RJ(e){let t=Sb(e,Wn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(RJ,"payeeKeyOrNull");var IJ={id:Ti,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},OJ={id:zn,label:{de:"Abrechnung",en:"Settlement"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"separate",label:{de:"Separat (Schule)",en:"Separately (school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},PJ={id:$i,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},_J={id:Wn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function NJ(e){return[IJ,OJ,...Zs(e)==="online"?[_J]:[],PJ]}s(NJ,"collectPaymentInputs");var CJ=["amount","currency","settlement"];function DJ(e,t){if(Zs(e)!=="online")return[];let n=RJ(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] Abrechnung \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 \u201Eseparat" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Settlement "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 "separate".`})]:[]}s(DJ,"payeeIssues");var hD={awaitingPayment:{label:ne("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:ne("Zahlung","Payment"),scope:"node"},external:Ze(ne("Zahlung offen","Payment due"),"amber",ne("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),ne("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},yD={outputs:s(()=>[{name:WR,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>NJ(e),"inputs"),outcomes:gD,progressDefaults:hD,progressEvents:Pt(hD),notificationEvents:s(e=>Zs(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=Zs(e);return t==="online"?[...mD,TJ]:t==="separate"?[EJ]:[]},"actions"),states:fD,currentState:s((e,t)=>pD(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:ub}),"currentState"),workItemTemplates:s(e=>{let t=e;return Zs(t)!=="online"?[]:[{key:ub,recipient:"external",title:t.label,unlocks:mD.map(n=>n.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 CJ)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"), die Abrechnung ist der Parameter \u201EAbrechnung" (inputs.settlement).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and settlement is the parameter "Settlement" (inputs.settlement).`});r.push(...DJ(e,n)),Zs(e)===null&&i(`inputs.${zn}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${Ss.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[zn])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${Ss.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[zn])}.`});let o=e.inputs?.[$i];if(o?.kind==="literal"){let d=af(o.value);d!==null&&i(`inputs.${$i}`,{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=$J(e);if(a===null)return i(`inputs.${Ti}`,{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.${Ti}`;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 ${cy.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${cy.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")};var Fn="traeger",wD={de:"Tr\xE4ger",en:"Provider"};function Dp(e){let t=e.inputs?.[Fn];return t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0?t.value:null}s(Dp,"traegerKeyOfNode");var Fp={name:"input.traeger.name",address:"input.traeger.anschrift"},TEe=Object.values(Fp);var kD="governedDocument",Io="prepareDocument",ud="prepareDocument:revision",Lr="releaseApproval",Oo="documentResponse",Mr="responseCheck",Lp="returnSigned";var bD="requestApproval";var vD="issueDocument",xD="correctInPlace",SD="rescindAndReissue",Mp="requestChange";var Xs="releaseArtifact",cn="signingRecovery",Po="resendESignature",_o="switchToPaper";var Ab=new Set([Io,ud]),AD=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],qp=["upload","resolver","template","none"],No=1,Co=366,ri="responseDueInDays";function Eb(e){let t=e.inputs?.[ri];return t?.kind==="literal"&&fd(t.value)?t.value:void 0}s(Eb,"responseDueInDaysForVocabulary");function fd(e){return typeof e=="number"&&Number.isInteger(e)&&e>=No&&e<=Co}s(fd,"isValidResponseDueInDays");var Kp=["generatedAt","responseDueInDays"],Do=["release","none"],jp=["confirm","signedUpload","signedUploadChecked","eSignature"];function ED(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(ED,"localeFieldMissingText");var Tb=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),TD=/^[a-z][a-z0-9_]*$/;function $D(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"||!TD.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(!Ei(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 (${xs.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 (${xs.join(", ")}).`}});continue}if(Tb.has(a.type)||n.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${t}" hat den Typ "${a.type}" \u2014 ein Brief druckt nur ${[...Tb].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a letter only prints ${[...Tb].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!TD.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!==void 0&&!Kp.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Kp.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Kp.join(", ")}.`}})}return n.push(...FJ(e,t)),n}s($D,"templateParameterIssues");function FJ(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:ED(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=>!ze.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${ze.join(", ")})`,en:`has options that are not a language (allowed: ${ze.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(FJ,"localeFieldIssues");function RD(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(RD,"applyTemplateStamp");var $b=50;async function Bp(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take($b+1);return n.length>$b&&N(`signing_returns: Vorgang ${t} has more than ${$b} returns`),n}s(Bp,"returnsOf");var Rb=50;async function Ib(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(Rb+1);return n.length>Rb&&N(`signing_returns: return ${t} has more than ${Rb} files`),n.length===0&&N(`[signing/noDocument] return ${t} carries no file`),n}s(Ib,"returnDocumentsOf");async function ID(e,t){let n=await Ib(e,t);return n.length!==1&&N(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(ID,"soleReturnDocumentOf");var Up=200,WEe=Up*20;async function LJ(e,t){let n=await e.db.get(t);return n===null&&N(`[process] application ${t} not found`),n.redactedAt!==void 0}s(LJ,"processRedacted");async function Ob(e,t){await LJ(e,t)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(Ob,"assertProcessReadable");function MJ(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(MJ,"rowOf");async function OD(e,t,n){await Ob(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(Up+1);return r.length>Up&&N(`[process] application ${t} has more than ${Up} results of ${n.scope}.${n.owner}.${n.key}`),r.map(MJ)}s(OD,"storeHistory");async function qJ(e,t,n){if(n.key===tn){await Ob(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 OD(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(qJ,"nodeResultAt");async function Vp(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return KJ(await qJ(e,t.applicationId,n),n,t.applicationId)}s(Vp,"readOwnResult");function KJ(e,t,n){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&N(`[process] ${se(t)} of application ${n} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(KJ,"refOf");var Pb={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},jJ=Object.keys(Pb),BJ=jJ.filter(e=>Pb[e]==="open"),nTe=BJ.filter(e=>e!=="pending");function PD(e){return Pb[e]==="terminal"}s(PD,"isTerminalSigningStatus");var Mi=["docusign","insign"];var pd={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var VJ=PD;function ND(e){return!VJ(e.status)&&e.voidRequestedAt===void 0}s(ND,"holdsContract");async function CD(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(CD,"traegerLegalEntityOfParty");async function GJ(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(GJ,"isOrganizationParty");async function DD(e,t){return await CD(e,t)!==null?"traeger":await GJ(e,t)?"organization":"person"}s(DD,"signerKindOf");async function FD(e,t){t.length===0&&N("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await zJ(e,n.partyId)==="family")return"family";return"traeger"}s(FD,"signingSideOf");async function zJ(e,t){return await DD(e,t)==="traeger"?"traeger":"family"}s(zJ,"sideOfParty");var DTe=16*1024;var FTe=15*6e4;var LTe=10*6e4;var _b={contractSnapshotId:Ut.restrict(w.id("contract_snapshots")),storageId:Ut.restrict(w.id("_storage")),sha256:w.string(),filename:w.string(),uploadedAt:w.number(),signers:w.array(w.object({partyId:Ut.history(w.id("parties")),role:w.string()}))},e$e=Vr({tenantId:Ut.tenant(w.id("tenants")),signingRequestDocumentId:Ut.belongsTo(w.id("signing_request_documents")),..._b}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var o$e=w.object(_b);var Nb=200;async function YJ(e,t,n,r){t.length>Nb&&N(`${r} is carried by more than ${Nb} 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&&N(`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(YJ,"requestsOfMembers");async function LD(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(Nb+1);return await YJ(e,r,n,`revision ${t}`)}s(LD,"requestsOfSnapshot");var MD=100;async function HJ(e,t){let n=await LD(e,t);n.length>MD&&N(`requestsBySideOf: revision ${t} has more than ${MD} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await FD(e,i.signers)].push(i);return r}s(HJ,"requestsBySideOf");async function Cb(e,t){return(await HJ(e,t)).family}s(Cb,"familyRequestsOf");var Db=100;async function JJ(e,t){let n=await e;return n.length>Db&&N(`contractChain: more than ${Db} ${t}`),n}s(JJ,"bounded");async function QJ(e,t,n){let r=await Vp(e,{applicationId:t,nodeId:n,key:ws});return r.state==="pending"?null:(r.ref.kind!=="contract"&&N(`contractChain: $node.${n}.${ws} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(QJ,"nodeContractRef");async function qD(e,t){return await JJ(e.db.query("contract_snapshots").withIndex("by_contractId_and_revisionNumber",n=>n.eq("contractId",t)).take(Db+1),`revisions on contract ${t}`)}s(qD,"snapshotsAsc");async function Fb(e,t){let n=(await Cb(e,t)).filter(ND);return n.length>1&&N(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s(Fb,"openFamilyRequest");async function ZJ(e,t){for(let n of await qD(e,t))if((await Cb(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(ZJ,"familyRoute");async function KD(e,t){for(let n of t)if(await ZJ(e,n)==="paper")return"paper";return"provider"}s(KD,"familyRouteOf");async function XJ(e,t){let n=await ID(e,t._id),r=await e.db.system.get("_storage",n.storageId);return r===null&&N(`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(XJ,"toReturn");function Gp(e){async function t(a,l){return await QJ(a,l,e.id)}s(t,"contractOrNull");async function n(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),f=u===null?null:await a.db.get(u),m=await t(a,l);return(f===null||m===null||f.contractId!==m)&&N(`${c}: ${d} is no revision of node "${e.id}"'s contract ${m??"(none yet)"} \u2014 corrupt arc`),f}s(n,"snapshotOf");async function r(a,l){let d=await t(a,l);return d===null?null:(await qD(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;N(`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 Fb(a,c._id);if(u===null)return null;let f=(await Bp(a,u._id)).filter(m=>m.review.status==="pending"&&m._id!==d.rejected);return f.length>1&&N(`returned(${d.where}): Vorgang ${u._id} has ${f.length} returns pending \u2014 one is checked at a time`),f[0]===void 0?null:await XJ(a,f[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(Gp,"contractNodeReads");function zp(e){return e.addedParts??[]}s(zp,"addedPartsOf");var Lb=50;async function e6(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(Lb+1);return n.length>Lb&&N(`groupRunsOf: generation group ${t} has more than ${Lb} runs`),n.length===0&&N(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(e6,"groupRunsOf");async function jD(e,t){let n=await e6(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)&&N(`groupRunsInOrder: package group ${t} has inconsistent members`);let i=await e.db.get(r);i===null&&N(`groupRunsInOrder: package run ${t} is missing`);let o=await e.db.query("contract_package_parts").withIndex("by_packageRevisionId_and_position",l=>l.eq("packageRevisionId",i.packageRevisionId)).take(51),a=[...o.map(l=>l.partKey),...zp(i).map(l=>l.partKey)];return(o.length>50||n.some(l=>!a.includes(l.partKey)))&&N(`groupRunsInOrder: package group ${t} names an unknown part`),n.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}N(`Package run ${t} has no package reference.`)}s(jD,"groupRunsInOrder");function BD(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(BD,"isCompleteGroup");var Mb=200;function t6(e){let t=e.generatorStamp?.parts;return t===void 0&&N(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),t.map(n=>n.partKey)}s(t6,"groupPartKeys");async function n6(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(Mb+1);return r.length>Mb&&N(`groupChain: more than ${Mb} generation runs on node ${n}`),r}s(n6,"nodeRuns");async function r6(e,t,n){let r=t6(n),i=new Set;for(let a of await n6(e,t,n.id))a.packageRunId===void 0&&N(`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 jD(e,a);if(!BD(l))continue;let d=await e.db.get(a);d===null&&N(`groupChain: generation group ${a} has no package run`);let c=new Set(zp(d).map(f=>f.partKey)),u=[];for(let f of l){!r.includes(f.partKey)&&!c.has(f.partKey)&&N(`groupChain: run ${f._id} renders part "${f.partKey}", which node "${n.id}"'s pin does not declare and nobody added`);let m=await e.db.get(f.contractSnapshotId);m===null&&N(`groupChain: run ${f._id} names revision ${f.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:f,snapshot:m})}o.push({packageRunId:a,startedAt:Math.min(...l.map(f=>f._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(r6,"groupRevisionRows");async function qb(e,t,n){let r=await Vp(e,{applicationId:t,nodeId:n,key:ks});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&N(`groupChain: $node.${n}.${ks} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(qb,"nodeGroupContracts");async function i6(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await Fb(e,r._id);i!==null&&n.set(i._id,i)}return n.size>1&&N(`groupChain: generation group ${t.packageRunId} is held by ${n.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...n.values()][0]??null}s(i6,"openGroupRequest");async function o6(e,t){let n=[];for(let i of await Ib(e,t._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&N(`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(o6,"toGroupReturn");function UD(e){async function t(i,o,a,l){let d=(await r6(i,o,e)).find(c=>c.members[0]?.snapshot._id===a);return d===void 0&&N(`${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;N(`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 i6(i,l);if(d===null)return null;let c=(await Bp(i,d._id)).filter(u=>u.review.status==="pending"&&u._id!==a.rejected);return c.length>1&&N(`returned(${a.where}): Vorgang ${d._id} has ${c.length} returns pending \u2014 one is checked at a time`),c[0]===void 0?null:await o6(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await qb(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(UD,"groupNodeReads");var s6={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},VD={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},GD={...VD,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},a6={...GD,kind:"eSignature",issuesBy:"provider"},ii={confirm:s6,signedUpload:VD,signedUploadChecked:GD,eSignature:a6};function qi(e){let t=e.responseStrategy;if(typeof t=="string"&&t in ii)return ii[t];N(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(t)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(qi,"responseStrategyOf");function zD(e){if(e.type!==kD||e.production!=="resolver")return!1;let t=e.responseStrategy;return typeof t=="string"&&t in ii?ii[t].acceptEvent==="contractEvent":!1}s(zD,"isFamilySignedContractNode");function md(e){return e.label}s(md,"governedDocTitle");function Kb(e){return e.approval==="release"?bD:vD}s(Kb,"submitActionId");function WD(e,t,n){return{key:t,recipient:"internal",title:n,unlocks:[Kb(e)],gatesNode:!0,advancesNode:!0}}s(WD,"producerTemplate");function l6(e){return e.titles?.respond??e.label}s(l6,"responseTitle");var ea={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function jb(e){let t=qi(e),n=[];if(e.production!=="none"&&n.push(WD(e,Io,e.titles?.prepare??ea),WD(e,ud,e.titles?.revise??ea)),e.approval==="release"&&n.push({key:Lr,recipient:"internal",title:e.titles?.approve??ea,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),n.push({key:Oo,recipient:"external",title:l6(e),unlocks:t.producesResponseArtifact?[t.checksReturn?Lp:t.acceptOutcomeId,t.declineOutcomeId,Mp]:[t.acceptOutcomeId,t.declineOutcomeId],advancesNode:!0,...Eb(e)!==void 0?{dueInDays:Eb(e)}:{}}),t.checksReturn&&n.push({key:Mr,recipient:"internal",title:e.titles?.check??ea,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),t.issuesBy==="provider"){let r=md(e);n.push({key:cn,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Po,_o],gatesNode:!1,advancesNode:!1})}return n}s(jb,"governedDocIntrinsicTemplates");function d6(e){e.production==="none"&&N(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let t=e.artifacts??[];t.length!==1&&N(`governedDocSlot: node "${e.id}" declares ${t.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let n=t[0];return(typeof n.key!="string"||n.key.length===0)&&N(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),n}s(d6,"governedDocSlot");function Wp(e){return d6(e).key}s(Wp,"governedDocSlotKey");function c6(e){let t=e.lifecycle.kind==="draft"?void 0:e.lifecycle.kind;return{_id:e._id,_creationTime:e._creationTime,versionNumber:e.versionNumber,...t!==void 0?{status:t}:{},origin:e.origin.kind,storageId:e.storageId,mimeType:e.mimeType,...e.filename!==void 0?{filename:e.filename}:{}}}s(c6,"toRevision");function u6(e){let t=c6(e);return{_id:t._id,_creationTime:t._creationTime,storageId:t.storageId,...t.filename!==void 0?{filename:t.filename}:{},...t.mimeType!==void 0?{mimeType:t.mimeType}:{},round:t.versionNumber}}s(u6,"toReturn");function YD(e){let t=Wp(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;ae("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(f=>f._id===l.rejected);if(u===void 0&&N(`returned(${l.where}): the handed-back scan ${l.rejected} is no version of slot "${t}"`),c.versionNumber<=u.versionNumber)return null}return u6(c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(YD,"artifactNodeReads");function Yp(e){return e.production==="none"&&N(`documentChainKind: node "${e.id}" has production 'none' \u2014 it keeps no document`),e.production!=="resolver"?"artifact":e.generatorStamp?.parts!==void 0?"group":"contract"}s(Yp,"documentChainKind");function HD(e){switch(Yp(e)){case"contract":return Gp(e).reads;case"group":return UD(e).reads;case"artifact":return YD(e).reads}}s(HD,"documentReadsFor");var f6={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function hd(e){let t=e.responseStrategy;return typeof t=="string"&&t in ii?ii[t].producesResponseArtifact:!1}s(hd,"returnsSignedCopy");function p6(e){return hd(e)&&e.confirmContractTerms!==!1}s(p6,"asksContractTerms");function JD(e){return p6(e)?{title:e.contractTermsQuestionText??f6,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(JD,"contractTermsConfirm");async function m6(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:Cy(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Mr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&N(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${Mr} row`),a}s(m6,"rejectedReturnOfAsk");async function QD(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await m6(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(QD,"returnedCopyOfAsk");var Bb=new Set([...Ab,Lr,Oo,Mr,cn]),tF={id:Ft,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},nF={id:lo,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function h6(e){let t=[],n=[{slot:tF,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:nF,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(Re(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(Re(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=il(a.value,{type:r.type});d!==null&&t.push(Re(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return t}s(h6,"referenceInputIssues");var g6={id:ri,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},y6={id:Fn,type:"legalEntity",label:wD,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function w6(e,t){let n=`inputs.${Fn}`,r=e.inputs?.[Fn];if(r!==void 0&&r.kind==="binding")return[Re(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=Dp(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(Re(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(Re(e,n,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Fp.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 (${Fp.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(w6,"traegerIssues");function Jp(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}}:(ki(r)||N(`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(Jp,"generatorFields");function k6(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(k6,"deferredToCockpit");function b6(e){return Ei(e.type)?e.type:void 0}s(b6,"resolverSlotType");function v6(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=md(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(v6,"issueConfirmation");function Re(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Re,"issue");function Hp(e){return qp.includes(e.production)&&Do.includes(e.approval)&&jp.includes(e.responseStrategy)}s(Hp,"hasValidModes");async function Ub(e,t){let n=await gl(e,{applicationId:t.applicationId,nodeId:t.node.id});if(n.length===0)return"pending";let r=n.filter(l=>l.isOpen&&l.kind==="admission"),i=r.filter(l=>l.templateKey!==void 0&&Ab.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";let o=r.find(l=>l.templateKey===Lr);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===cn))return"signatureStalled";let a=r.find(l=>l.templateKey===Oo);if(a!==void 0){if(qi(t.node).issuesBy==="provider"){let d=Yp(t.node)==="group"?(await qb(e,t.applicationId,t.node.id)).map(c=>c.contractId):[await Gp(t.node).contractOrNull(e,t.applicationId)].flatMap(c=>c===null?[]:[c]);if(d.length===0&&N(`governedDocCurrentState: eSignature node "${t.node.id}" has an open ask but no contract`),await KD(e,d)==="provider")return"awaitingSignature"}return qi(t.node).producesResponseArtifact?await QD(e,{chain:HD(t.node),applicationId:t.applicationId,ask:a,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${t.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(l=>l.templateKey===Mr)?"responseInCheck":"done"}s(Ub,"governedDocCurrentState");function ZD(e){return e.production!=="none"&&Yp(e)!=="artifact"}s(ZD,"keepsDocumentInContractDomain");function x6(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!be(r)||r.scope!=="env"||!ar(r.key))return[];let i=ao(r.key);if(t.type!==i.type)return[Re(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" ist ${t.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${se(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${t.key}" is ${t.type}, the environment variable "${i.label.en}" (${se(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?[]:[Re(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(x6,"envCoverageIssues");function rF(e,t){let n=[];for(let r of Jp(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...x6(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${be(a.address)?se(a.address):JSON.stringify(a.address)}`,en:`a binding to ${be(a.address)?se(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:k6(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(rF,"fieldSourceIssues");function S6(e){let t=lr(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=$D(e.templateStamp,t).map(({path:r,reason:i})=>Re(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...rF(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(S6,"templateIssues");function A6(e,t){return(t?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(n=>{if(n.documentAnchors===null)return[Re(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?[]:[Re(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(A6,"eSignatureAnchorIssues");function E6(e,t){return t===void 0||t.sendable?[]:qi(e).issuesBy!=="provider"?[]:[Re(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(E6,"eSignatureProviderIssues");var XD={key:"dokument",label:ne("Dokument","Document"),scope:"node"},eF={producing:{label:ne("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:XD,external:Ze(ne("In Vorbereitung","In preparation"),"blue",ne("Ihr Dokument wird vorbereitet","Your document is being prepared"),ne("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:ne("Dokument bereitgestellt","Document issued"),tone:"blue",phase:XD,external:Ze(ne("Dokument bereit","Document ready"),"amber",ne("Ihr Dokument liegt bereit","Your document is ready"),ne("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."),ne("Dokument beantworten","Respond to the document"))}},iF={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>Io,"processHoldTemplate"),progressDefaults:eF,progressEvents:Pt(eF),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:"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(!Hp(e))return[];let t=qi(e),n=[],r=t.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=t.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=t.checksReturn?[...i,"responseInCheck"]:i;return e.production!=="none"&&(n.push({id:Kb(e),kind:"internal",surface:Xs,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...v6(e)??{}}),n.push({id:xD,kind:"internal",surface:Xs,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:SD,kind:"internal",surface:Xs,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:Lp,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:i,external:{emphasis:"decline",event:"userTaskResolved"}}),t.producesResponseArtifact&&n.push({id:Mp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:Po,kind:"internal",surface:Xs,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:_o,kind:"internal",surface:Xs,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:AD,currentState:Ub,workItemTemplates:s(e=>{let t=e;return Hp(t)?jb(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e;if(!Hp(n)||n.production==="none")return[];let r=jb(n).find(i=>i.key===t);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:Wp(n)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[tF,y6]:[],...e.production==="template"?[nF]:[],g6,...Jp(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=b6(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"&&xi(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:el,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===Oo||t===ud||t===Mr||t===cn){let n=t===Oo?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===Mr?{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===cn?{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: ${Io}${e.approval==="release"?`, ${Lr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${Io}${e.approval==="release"?`, ${Lr}`:""}.`}}return t===Lr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Lr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Lr}" 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(ZD(t.node))return!1;let n=await Ub(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&qi(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=JD(t.node);if(n===null||ZD(t.node))return null;let r=await Ub(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Hp(e))return r.push(Re(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${qp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Do.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${jp.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 {${qp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Do.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${jp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=ii[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Re(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(Re(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(Re(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 v of o)v.visibility!=="external"&&r.push(Re(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${v.key}" auf Knoten "${e.id}" hat visibility "${v.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${v.key}" on node "${e.id}" has visibility "${v.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(v=>v.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(v=>l.includes(v)))&&r.push(Re(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(v=>`"${v}"`).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(v=>`"${v}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(v=>{let $=c?.[v];return $===null||typeof $!="object"||!Object.values($??{}).some(R=>typeof R=="string"&&R.length>0)},"missingTitle"),f=[];e.production!=="none"&&f.push("prepare","revise"),e.approval==="release"&&f.push("approve"),i.checksReturn&&f.push("check");let m=f.filter(u);m.length>0&&r.push(Re(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${m.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 ${m.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let y=e.assign??{};if(e.production!=="none"){let v=y.prepareDocument;(typeof v!="string"||v.length===0)&&r.push(Re(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.`}))}if(e.approval==="none"&&(y.releaseApproval!==void 0&&r.push(Re(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(Re(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){let v=y.responseCheck;(typeof v!="string"||v.length===0)&&r.push(Re(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(Re(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(Re(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(Re(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[v,$]of[["assign.responseCheck",y.responseCheck!==void 0],["titles.check",c?.check!==void 0]])$&&r.push(Re(e,v,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${v} \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 ${v} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"){let v=y.signingRecovery;(typeof v!="string"||v.length===0)&&r.push(Re(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.`}))}else y.signingRecovery!==void 0&&r.push(Re(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'.`}));if(i.issuesBy==="provider"&&r.push(...A6(e,n),...E6(e,n?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Re(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(Re(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(Re(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.`})),hd(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Re(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[v,$]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])$&&r.push(Re(e,v,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${v} \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 ${v} \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[v,$]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",y.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])$&&r.push(Re(e,v,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${v} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${v} \u2014 without a production phase there is nothing to carry it.`}));for(let v of e.tasks??[])Bb.has(v.key)&&r.push(Re(e,`tasks.${v.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${v.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...Bb].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${v.key}" on node "${e.id}" collides with an intrinsic template (${[...Bb].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...w6(e,n)):e.inputs?.[Fn]!==void 0&&r.push(Re(e,`inputs.${Fn}`,{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(...h6(e)),e.production==="resolver"){let v=Yr(e);if(v!==null){let $=nR(v);for(let R of Jp(e)){if(!Ei(R.type)){r.push(Re(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/unknownFieldType] Generator "${$}" typisiert das Feld "${R.key}" als "${String(R.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${xs.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${$}" types the field "${R.key}" as "${String(R.type)}" \u2014 that is not part of the platform's value vocabulary (${xs.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(R.type==="personList"){r.push(Re(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${$}" deklariert das Feld "${R.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 "${$}" declares the field "${R.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}R.type==="party"&&(R.key.endsWith("PartyId")||r.push(Re(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${R.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 "${R.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...rF(e,{de:`"${$}"`,en:`"${$}"`}))}}else e.generatorStamp!==void 0&&r.push(Re(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(...S6(e)):e.templateStamp!==void 0&&r.push(Re(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 k=e.inputs?.[ri],g=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return g!==void 0&&!fd(g)&&r.push(Re(e,`inputs.${ri}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(g)} \u2014 erlaubt ist eine ganze Zahl von ${No} bis ${Co} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(g)} \u2014 a whole number from ${No} to ${Co} days is allowed.`})),g===void 0&&Jp(e).some(v=>v.processSource==="responseDueInDays")&&r.push(Re(e,`inputs.${ri}`,{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 Qp="countersign",Vb="countersign",oF="countersigned",sF="countersigning",aF="countersigned",lF={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},gd=["scan","eSignature"],Zp="service_provider:1",dF=["countersigning","awaitingSignature","signatureStalled","done"],cF={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function uF(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(uF,"traegerSignatoryMissingReason");function Qn(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Qn,"issue");function mF(e,t){return e.nodes.filter(n=>{let r=n.contract;return n.type==="countersign"&&be(r)&&r.scope==="node"&&r.owner===t})}s(mF,"countersignersOf");function yd(e){return e.signing==="eSignature"}s(yd,"isElectronic");function T6(e,t){if(t===void 0||t.sendable||!yd(e))return[];let n=e.label?.de??e.id,r=e.label?.en||e.id;return[Qn(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${n}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${t.reason.en}`})]}s(T6,"countersignProviderIssues");function $6(e,t,n){if(n.scope!=="node")return[];let r=e.nodes.find(o=>o.id===n.owner);if(r===void 0)return[];let i=[];return zD(r)||i.push("sourceNotCheckedContract"),mF(e,r.id).some(o=>o.id!==t)&&i.push("twice"),i}s($6,"countersignContractRefusals");function fF(e){let t=e.inputs?.dueInDays;return t?.kind==="literal"&&typeof t.value=="number"&&Number.isInteger(t.value)&&t.value>=1?t.value:void 0}s(fF,"validDueInDays");function R6(e,t,n){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!gd.includes(o))return[Qn(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[cn];if(!yd(e))return a===void 0?[]:[Qn(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(Qn(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...I6(e,t,n),...O6(e,t,n),...T6(e,n?.signingProvider)),l}s(R6,"signingIssues");function hF(e,t){let n=e.contract;if(!(!be(n)||n.scope!=="node"))return t.nodes.find(r=>r.id===n.owner)}s(hF,"contractNodeOf");function I6(e,t,n){let r=hF(e,t),i=r===void 0?null:Dp(r),o=i===null?void 0:n?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[Qn(e,"signing",uF(o.name))]}s(I6,"traegerSignatoryIssues");function O6(e,t,n){let r=hF(e,t);if(r===void 0)return[];let i=n?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(Qn(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(Zp)||l.push(Qn(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Zp}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${Zp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(O6,"traegerAnchorIssues");var Gb=100;async function P6(e,t){let n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",t.applicationId).eq("context.anchor.nodeId",t.node.id)).take(Gb+1);n.length>Gb&&N(`countersign node "${t.node.id}" of ${t.applicationId} holds more than ${Gb} rows`);let r=n.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===cn)?"signatureStalled":r.some(o=>i(o)===Qp)?"countersigning":yd(t.node)?"awaitingSignature":"done"}s(P6,"countersignCurrentState");var pF={[sF]:{label:ne("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:ne("Gegenzeichnung","Countersignature"),scope:"node"},external:Ze(ne("Vertrag unterschrieben","Contract signed"),"blue",ne("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),ne("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},gF={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:oF,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:pF,progressEvents:Pt(pF),notificationEvents:s(()=>[{id:aF,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:Vb,kind:"internal",label:lF,surface:Jn,availableIn:["countersigning"]},...yd(e)?[{id:Po,kind:"internal",surface:Jn,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:_o,kind:"internal",surface:Jn,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Qp,recipient:"internal",title:e.titles?.countersign??ea,unlocks:[Vb],advancesNode:!0,...fF(e)!==void 0?{dueInDays:fF(e)}:{}},...yd(e)?[{key:cn,recipient:"internal",title:cF,unlocks:[Po,_o],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:dF,currentState:P6,validate:s((e,t,n)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[Qp];(typeof a!="string"||a.length===0)&&r.push(Qn(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),ki(e.titles?.countersign)||r.push(Qn(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(Qn(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...R6(e,t,n));let d=e.contract;if(!be(d))return r;let c=$6(t,e.id,d);if(c.length===0)return r;let u=t.nodes.find(f=>d.scope==="node"&&f.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(Qn(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let f=mF(t,u.id).filter(m=>m.id!==e.id);r.push(Qn(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${f.map(m=>`"${m.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${f.map(m=>`"${m.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};var yF={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:{}}};function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ln,"isRecord");var zb=["field","join","literal","address","payment","contract"],_6=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),N6=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function Zn(e){return typeof e=="string"&&e.trim().length>0}s(Zn,"nonEmptyString");function Xp(e,t,n,r,i="value"){if(!Ln(e)||!Ln(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=zb.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${zb.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${zb.join(" | ")}).`}});return}let[l]=a;l==="field"&&!Zn(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(Zn))&&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)||Zn(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"&&!(be(o.address)&&o.address.scope==="env"&&ar(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&&!_6.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&&!(Zn(e.lookup)&&Ln(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"||Ln(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Ln(d)&&N6.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(Xp,"checkMapping");function Ki(e,t,n,r,i){if(!Ln(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=yF[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))Xp(l,`${t}.${a}`,r,i)}s(Ki,"checkBody");function wF(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(!Ln(o)||!Zn(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),Xp(o.value,`${l}.value`,n,r),o.unless!==void 0&&Xp(o.unless,`${l}.unless`,n,r,"condition")})}s(wF,"checkAif");function Wb(e){let t=[];if(!Ln(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=Ln(e.lookups)?e.lookups:{};Ln(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))(!Ln(i)||!Object.values(i).every(Zn))&&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(Zn(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Ki(e.pupil,"engage.pupil","addPupil",n,t),Ki(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&Ki(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&Ki(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&Ki(e.medical,"engage.medical","addMedical",n,t),wF(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(!Ln(i)||!Zn(i.key)||!Zn(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),Ki(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&Ki(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,f)=>Ki(u,`${a}.${l}[${f}]`,d,n,t))}}wF(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&Xp(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Ln(r)||!Zn(r.repeated)||!Zn(r.field)||!Zn(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(Wb,"engagePushConfigIssues");function*Yb(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(Yb,"mappingsOf");function kF(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of Yb(e))for(let i of C6(n.from))t.add(D6(i,r));return[...t]}s(kF,"configFieldKeys");function C6(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(C6,"formFieldsOf");function D6(e,t){return e.startsWith(".")?(t===void 0&&N(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(D6,"resolveFieldKey");function bF(e,t){for(let{mapping:n}of Yb(e))if(t in n.from)return!0;return!1}s(bF,"configReadsSource");function vF(e){let t=new Set;for(let{mapping:n}of Yb(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(vF,"configEnvLeaves");var xF="done",SF=["sandbox","production"];var em="engagePush",cIe=660*1e3;function ji(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(ji,"issue");function Hb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Hb,"literal");function AF(e){return Wb(e.engage).length===0?e.engage:null}s(AF,"validConfig");function F6(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(F6,"bypassingPath");var EF={role:"system-action",effect:"side-effect",outcomes:[{id:xF,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=AF(e);return t===null?[]:vF(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=Hb(e,"target");SF.includes(a)||o.push(ji(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=Hb(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(ji(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`}));let d=e.assign?.[em];(typeof d!="string"||d.length===0)&&o.push(ji(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${em}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${em}\` names the team.`}));for(let g of Wb(e.engage))o.push(ji(e,g.path,{de:`[engagePush/config] \u201E${r}": ${g.message.de}`,en:`[engagePush/config] "${i}": ${g.message.en}`}));let c=t.nodes.filter(g=>g.id!==e.id&&g.type==="engagePush"&&Hb(g,"target")===a);c.length>0&&o.push(ji(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${c.map(g=>`"${g.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${c.map(g=>`"${g.id}"`).join(", ")} already transfers to the same target.`})),F6(t,e.id)&&o.push(ji(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 u=AF(e),f=e;for(let[g,v,$,R]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!bF(u,g)||f[v]!==void 0||o.push(ji(e,v,{de:Ts("address/missing",{where:`\u201E${r}\u201C \u203A ${$}`},"de"),en:Ts("address/missing",{where:`"${i}" \u203A ${R}`},"en")}));let m=f.form,y=be(m)&&m.scope==="node"?m.owner:void 0,k=y===void 0?void 0:n?.readinessFormFieldsByFormNode?.get(y);if(u!==null&&k!==void 0){let g=new Set(k.keys()),v=kF(u).filter($=>!g.has($)&&!/\[\d+\]\./.test($));if(v.length>0){let $=t.nodes.find(R=>R.id===y);o.push(ji(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${$?.label?.de??y}" nicht \u2014 sie werden nicht \xFCbertragen: ${v.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${$?.label?.en||y}" does not know these fields \u2014 they are not transferred: ${v.join(", ")}.`},"warning"))}}return o},"validate")};var Fo={join:FC,end:jI,roleAssign:MC,eventTrigger:qC,waitlist:tD,completenessCheck:dD,form:zC,setFlag:WC,if:YC,decision:Li,review:uD,collectPayment:yD,governedDocument:iF,countersign:gF,engagePush:EF};BR(Fo);function TF(e,t){let n=e;if(n==null||!Array.isArray(n.nodes))throw new Error(`offer plan: the ${t} carries no workflow graph with nodes`);return e}s(TF,"graphOf");function $F(e){let t=new Map;for(let n of e.nodes)for(let r of Ir(e,n))t.set(se(r.address),r.nodeId);return t}s($F,"producedOf");function RF(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(ho(e,n).map(r=>se(r.address))));return t}s(RF,"readsOf");function IF(e,t){let n=TF(e,"bundle"),r=TF(t.graph,"live head"),i=$F(n),o=$F(r),a={added:[],removed:[],moved:[]};for(let[u,f]of i){let m=o.get(u);m===void 0?a.added.push({address:u,nodeId:f}):m!==f&&a.moved.push({address:u,from:m,to:f})}for(let[u,f]of o)i.has(u)||a.removed.push({address:u,nodeId:f});let l=RF(n),d=RF(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let f=l.get(u)??new Set,m=d.get(u)??new Set,y=[...f].filter(g=>!m.has(g)),k=[...m].filter(g=>!f.has(g));(y.length>0||k.length>0)&&c.push({nodeId:u,added:y,removed:k})}return{headRevision:t.revision,pinnedApplications:t.pinnedApplications,produced:a,reads:c}}s(IF,"planAddresses");function OF(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(OF,"addressPlanRows");function PF(e,t){return t==null?!0:Pe(e)!==Pe(t)}s(PF,"changed");async function _F(e,t,n){if(t.index.module!==lb.name)throw new Error(`offer: unknown module "${t.index.module}"`);return QP(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return lb.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(_F,"applyOffer");async function NF(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(NF,"exportOffer");async function Jb(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,k]of Object.entries(t.smartforms??{})){let g=i?await e.query(S.forms.getSmartFormBySlug,{client:n.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=g?.def?PF(k,{label:g.def.label,...g.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}),k=y?.publishedVersion??y?.draftVersion;l=PF(k&&{graph:us(t.workflow.graph),progressLayout:t.workflow.progressLayout??k.progressLayout,progressWiring:t.workflow.progressWiring??k.progressWiring},k&&{graph:us(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let y=await e.query(S.workflow.getOfferHeadPins,{client:n.tenant,offerKey:n.slugs.manifest});y!==null&&(d=IF(t.workflow.graph,y))}}let c=n.program?.stages,u=c===void 0?[]:i?await ab(e,n.tenant,n.slugs.manifest,c):Tp(null,[],c),f=await Pp(e,n.tenant,i?n.slugs.manifest:null,n),m=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:f,publishPending:m?.draftDiffersFromExternal??null,draftRevision:m?.draftRevision??null,externalHeadRevision:m?.externalHeadRevision??null}}s(Jb,"diffOffer");function tm(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(tm,"contractProductionModeOf");function CF(e){return tm(e)==="resolver"}s(CF,"isResolverCarrierNode");function nm(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=Yr(n);return!CF(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(nm,"authoredPins");var DF={type:"address",dataType:"composite"};var FF={type:"boolean",dataType:"boolean"};var LF={type:"date",dataType:"date"};var MF={type:"docRef",dataType:"file"};var qF={type:"email",dataType:"text"};var KF={type:"enum",dataType:"option"};var jF={type:"string",dataType:"text"};var BF={type:"tel",dataType:"text"};var L6={address:DF.dataType,boolean:FF.dataType,date:LF.dataType,docRef:MF.dataType,email:qF.dataType,enum:KF.dataType,string:jF.dataType,tel:BF.dataType};function Qb(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(Qb,"shapeOf");function UF(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,Qb(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,Qb(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}`,Qb(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(UF,"fieldMapScopes");function M6(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(M6,"computedKeysOf");function VF(e){let t=[],n=M6(e);for(let r of UF(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(VF,"validateFieldMapSources");function GF(e){let t=[],n=new Set;for(let o of UF(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(GF,"validateFieldPersistence");var q6="$";function K6(e){return typeof e=="string"&&e.startsWith(q6)}s(K6,"isRef");function rm(e){return e.slice(1)}s(rm,"stripRef");function*j6(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(j6,"refSlots");function B6(e){let t=new Set;for(let n of j6(e))K6(n)&&t.add(rm(n));return[...t]}s(B6,"collectRefs");function U6(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 B6(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=rm(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&rm(l.target)===a||l.kind==="shareValue"&&rm(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(U6,"buildAdjacency");function zF(e){let{refsOf:t}=U6(e),r=Cf(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(zF,"detectCycle");function WF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(WF,"escapeRegExp");function Bi(e){return new RegExp(`^${WF(e)}\\[(\\d+)\\]\\.(.+)$`)}s(Bi,"repeatedRowKeyPattern");function Zb(e,t){let n=Bi(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(Zb,"countRepeatedRows");function YF(e,t,n){let r=Bi(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(YF,"repeatedRowHasData");function HF(e){return e.endsWith(".count")?e.slice(0,-6):e}s(HF,"readKeyOf");function Xb(e){return{sections:e,fields:[]}}s(Xb,"hiddenSectionsOnly");function JF(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??[])JF(r,t,n)}s(JF,"collectKeys");function QF(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;JF(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(Bi)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(QF,"restrictedSectionsOf");function ZF(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(ZF,"matchesKey");function V6(e,t){return t.find(n=>ZF(e,n))??null}s(V6,"hiddenSectionOfKey");function G6(e,t){for(let n=e;;){if(ZF(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(G6,"fieldOwnsKey");function z6(e,t){return t.find(n=>G6(e,n))??null}s(z6,"restrictedFieldOfKey");function W6(e,t){let n=V6(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=z6(e,t.fields);return r===null?null:{kind:"field",field:r}}s(W6,"hiddenOwnerOfKey");function im(e,t){return W6(e,t)!==null}s(im,"isKeyHidden");function Y6(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(Y6,"visibleToListIssues");function XF(e,t,n){let r=[],i=s((c,u,f)=>{let m=c.visibleTo;m!==void 0&&r.push(...Y6(c.id,m,`${u}.visibleTo`,f,n));let y=f||m!==void 0;if(y){let k=[...c.fields,...(c.groups??[]).flatMap(g=>g.fields),...(c.repeated??[]).flatMap(g=>g.itemTemplate)];for(let g of k)g.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${g.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${g.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,g)=>i(k,`${u}.subsections[${g}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=QF(e);if(o.length===0)return r;let a=s((c,u,f)=>{if(c===void 0)return;let m=Xb(f);for(let y of kt(c)){let k=HF(y);(im(y,m)||im(k,m))&&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,f)=>{a(c.visibleIf,`${u}.visibleIf`,f),a(c.requiredIf,`${u}.requiredIf`,f),a(c.disabledIf,`${u}.disabledIf`,f),a(c.defaultValue,`${u}.defaultValue`,f),c.sameAs!==void 0&&im(c.sameAs.source,Xb(f))&&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,f)=>{let m=c.visibleTo!==void 0?c.id:f,y=o.filter(k=>k.sectionId!==m);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((k,g)=>l(k,`${u}.fields[${g}]`,y)),c.groups?.forEach((k,g)=>{a(k.visibleIf,`${u}.groups[${g}].visibleIf`,y),k.fields.forEach((v,$)=>l(v,`${u}.groups[${g}].fields[${$}]`,y))}),c.repeated?.forEach((k,g)=>{a(k.itemVisibleIf,`${u}.repeated[${g}].itemVisibleIf`,y),k.itemTemplate.forEach((v,$)=>l(v,`${u}.repeated[${g}].itemTemplate[${$}]`,y))}),c.computed?.forEach((k,g)=>a(k.expression,`${u}.computed[${g}]`,y)),c.subsections?.forEach((k,g)=>d(k,`${u}.subsections[${g}]`,m))},"visitCompiled");return t.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(XF,"sectionVisibilityIssues");var qr="#";var eL=s(e=>{let t=Aw.find(n=>n.systemColumn===e);return t===void 0&&N(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),mr={firstName:eL("persons.firstName"),lastName:eL("persons.lastName")};function tL(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===mr.firstName?n.firstName.push(o):a===mr.lastName&&n.lastName.push(o);return n}s(tL,"personNameKeys");function nL(e){return[...e.firstName,...e.lastName]}s(nL,"personNameKeyList");function rL(e){return e.firstName.length>0||e.lastName.length>0}s(rL,"hasPersonName");function ta(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 ta(i.subsections??[],a,i.id))r.push(l)}),r}s(ta,"walkSections");function H6(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(H6,"findFieldInSection");function iL(e,t){for(let n of ta(e.sections)){let r=H6(n.section,t);if(r)return{section:n.section,field:r}}return null}s(iL,"findField");var J6=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],Q6=["blue","rose","amber","violet","teal","emerald","slate"];function oL(e){return J6.includes(e)}s(oL,"isBucketIconName");function sL(e){return Q6.includes(e)}s(sL,"isBucketColorName");var Z6="__clear__";function aL(e){return e===""?"empty":e===Z6?"reserved":null}s(aL,"selectOptionValueDefect");var sPe=Object.freeze({});function X6(e,t){return Object.freeze(If(zr,e,t))}s(X6,"formContextEntries");function lL(e){return e.env??[]}s(lL,"declaredContextKeys");function dL(e,t){return lL(e).every(n=>cL(n,t?.[n]))}s(dL,"scenarioContextComplete");function cL(e,t){return bO(zr,e,t)}s(cL,"contextValueComplete");function uL(e,t){return X6(t??{},lL(e))}s(uL,"scenarioContextEntries");function tv(e){return kl(e)}s(tv,"isContextIdentifier");function e4(e,t,n){let r=Rf(zr,e);if(r!==null)return{severity:"error",path:n,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return t.has(i)?null:{severity:"error",path:n,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(e4,"contextIdentifierIssue");var ev=ju("stage.key");function t4(e){let t=[],n=s(i=>i.kind==="ident"&&i.path===ev,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(n(i.left)&&i.right.kind==="str"&&t.push(i.right.value),n(i.right)&&i.left.kind==="str"&&t.push(i.left.value)),i.op==="in"&&n(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&t.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),t}s(t4,"stageKeyLiterals");function fL(e,t,n){return t===void 0?[]:t4(e).filter(r=>!t.has(r)).map(r=>mL(r,t,n))}s(fL,"stageKeyAstIssues");function pL(e,t){if(t===void 0)return[];let n=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!t.has(i.key)&&n.push(mL(i.key,t,`scenario:${r.id}/env`))}return n}s(pL,"scenarioStageKeyIssues");function mL(e,t,n){let r=[...t].sort();return{severity:"error",path:n,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${ev}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${ev}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(mL,"unknownStageKeyIssue");function hL(e,t,n){let r=[];for(let i of kt(e)){if(!tv(i))continue;let o=e4(i,t,n);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Ly(e,qu))r.push({severity:"error",path:n,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(hL,"contextAstIssues");function gL(e,t){let n=[...n4(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!cs(i)){n.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${ds.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${ds.join(", ")}).`}});continue}t!==void 0&&!t.has(i)&&n.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>cs(a)&&!cL(a,i.env?.[a]));o.length>0&&n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))cs(a)?r.has(a)||n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return n}s(gL,"formContextIssues");function n4(e){let t=[];Object.hasOwn(e,"context")&&t.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let n=e.testScenarios;for(let r of Array.isArray(n)?n:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&t.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return t}s(n4,"retiredContextFields");var nv=J_.docRef.allowedMime;function vL(e,t={}){let n=qs(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 f(P,I){if(i.has(P))return;i.add(P);let B=o.get(P.id);B&&B!==P?r.push({severity:"error",path:`sections[${I.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${P.id}' ist mehrfach deklariert.`,en:`Section id '${P.id}' is declared more than once.`}}):o.set(P.id,P);let D=`sections[${I.join(".")}]`;P.fields.forEach((X,ce)=>{na(a,X.key,`${D}.fields[${ce}]`,"duplicate.field-key",r),l.add(X.key),u.set(X.key,X),c.set(X.key,iv(X)),X.externalFlag&&(X.type!=="boolean"&&r.push({severity:"error",path:`${D}.fields[${ce}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${X.key}' muss den Typ 'boolean' haben (ist '${X.type}').`,en:`External flag '${X.key}' must be type 'boolean' (got '${X.type}').`}}),X.notice!==void 0&&r.push({severity:"error",path:`${D}.fields[${ce}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${X.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${X.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),X.defaultValue==null&&r.push({severity:"error",path:`${D}.fields[${ce}]`,code:"flag.missing-default",message:{de:`Externes Flag '${X.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${X.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...yL(X,`${D}.fields[${ce}]`))}),P.groups?.forEach((X,ce)=>{X.fields.forEach((fe,xe)=>{na(a,fe.key,`${D}.groups[${ce}].fields[${xe}]`,"duplicate.field-key",r),l.add(fe.key),u.set(fe.key,fe),c.set(fe.key,iv(fe)),fe.externalFlag&&r.push({severity:"error",path:`${D}.groups[${ce}].fields[${xe}]`,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(...yL(fe,`${D}.groups[${ce}].fields[${xe}]`))})}),P.repeated?.forEach((X,ce)=>{X.itemTemplate.forEach((fe,xe)=>{na(a,fe.key,`${D}.repeated[${ce}].itemTemplate[${xe}]`,"duplicate.field-key",r),c.set(fe.key,iv(fe)),fe.externalFlag&&r.push({severity:"error",path:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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.notice!==void 0&&r.push({severity:"error",path:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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:`${D}.repeated[${ce}].itemTemplate[${xe}]`,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.`}})})}),P.computed?.forEach(X=>{d.add(X.key),na(a,X.key,`${D}.computed[${X.key}]`,"duplicate.field-key",r),X.export===!0&&X.exportType===void 0&&r.push({severity:"error",path:`${D}.computed[${X.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${X.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${X.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),P.subsections?.forEach((X,ce)=>f(X,[...I,ce]))}s(f,"visitRawSection"),e.sections.forEach((P,I)=>f(P,[I]));let m=new Set;n.effects.forEach((P,I)=>{na(m,P.id,`effects[${I}]`,"duplicate.effect-id",r)});let y=new Set;n.outcomes.forEach((P,I)=>{na(y,P.id,`outcomes[${I}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((P,I)=>{P.output.effectRefs?.forEach((B,D)=>{m.has(B.effect)||r.push({severity:"error",path:`outcomes[${I}].output.effectRefs[${D}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${P.id}' verweist auf den unbekannten Effekt '${B.effect}'.`,en:`Outcome '${P.id}' references unknown effect '${B.effect}'.`}})})}),n.outcomes.forEach((P,I)=>{P.output.fields?.forEach((B,D)=>{iL(n,B.path)||r.push({severity:"error",path:`outcomes[${I}].output.fields[${D}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${P.id}' verweist auf das unbekannte Feld '${B.path}'.`,en:`Outcome '${P.id}' references unknown field '${B.path}'.`}})})});let k=new Set;for(let P of ta(n.sections))for(let I of P.section.repeated??[])k.add(`${I.key}.count`);for(let P of k)(a.has(P)||d.has(P))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${P}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${P}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let g={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...gL(e)),r.push(...XF(e,n,t.visibleToKeys)),r.push(...pL(e,t.stageKeys));for(let P of ta(n.sections)){let I=P.section,B=`sections[${P.path.join(".")}]`;I.visibleIf&&(hr(I.visibleIf,`${B}.visibleIf`,g,!1,r),ra(I.visibleIf,`${B}.visibleIf`,c,r)),I.fields.forEach((D,X)=>rv(D,`${B}.fields[${X}]`,g,!1,c,r)),I.groups?.forEach((D,X)=>{D.visibleIf&&(hr(D.visibleIf,`${B}.groups[${X}].visibleIf`,g,!1,r),ra(D.visibleIf,`${B}.groups[${X}].visibleIf`,c,r)),D.fields.forEach((ce,fe)=>rv(ce,`${B}.groups[${X}].fields[${fe}]`,g,!1,c,r))}),I.repeated?.forEach((D,X)=>{D.itemVisibleIf&&(hr(D.itemVisibleIf,`${B}.repeated[${X}].itemVisibleIf`,g,!0,r),ra(D.itemVisibleIf,`${B}.repeated[${X}].itemVisibleIf`,c,r)),D.itemTemplate.forEach((ce,fe)=>rv(ce,`${B}.repeated[${X}].itemTemplate[${fe}]`,g,!0,c,r)),D.effects?.forEach((ce,fe)=>{ce.when&&hr(ce.when,`${B}.repeated[${X}].effects[${fe}].when`,g,!0,r)})}),I.computed?.forEach((D,X)=>hr(D.expression,`${B}.computed[${X}].expression`,g,!1,r))}n.effects.forEach((P,I)=>{P.when&&hr(P.when,`effects[${I}].when`,g,!1,r)}),n.outcomes.forEach((P,I)=>{hr(P.when,`outcomes[${I}].when`,g,!1,r)});let v=new Set(n.outcomes.map(P=>P.id));function $(P,I){P.requiredFor&&P.requiredFor.forEach((B,D)=>{v.has(B)||r.push({severity:"error",path:`${I}.requiredFor[${D}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${P.key}": requiredFor verweist auf das unbekannte Ergebnis "${B}"`,en:`field "${P.key}": requiredFor references unknown outcome "${B}"`}})})}s($,"checkRequiredFor");for(let P of ta(n.sections)){let I=P.section,B=`sections[${P.path.join(".")}]`;I.fields.forEach((D,X)=>$(D,`${B}.fields[${X}]`)),I.groups?.forEach((D,X)=>{D.fields.forEach((ce,fe)=>$(ce,`${B}.groups[${X}].fields[${fe}]`))}),I.repeated?.forEach((D,X)=>{D.itemTemplate.forEach((ce,fe)=>$(ce,`${B}.repeated[${X}].itemTemplate[${fe}]`))})}function R(P,I){let B=s((D,X)=>{let ce=(D.type==="docRef"?D.docRefConstraints?.mimeType??[]:[]).filter(xe=>!nv.includes(xe));ce.length>0&&r.push({severity:"error",path:X,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${D.key}' erlaubt ${ce.map(xe=>`'${xe}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${nv.join(", ")}).`,en:`Field '${D.key}' allows ${ce.map(xe=>`'${xe}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${nv.join(", ")}).`}}),D.multiple===!0&&D.type!=="enum"&&r.push({severity:"error",path:X,code:"config.multiple-non-enum",message:{de:`Feld '${D.key}' setzt multiple: true, hat aber den Typ '${D.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(D.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${D.key}' sets multiple: true but is type '${D.type}' \u2014 only 'enum' supports multi-select.`+(D.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),D.presentation==="yesNo"&&D.type!=="boolean"&&r.push({severity:"error",path:X,code:"config.yesno-non-boolean",message:{de:`Feld '${D.key}' setzt presentation: 'yesNo', hat aber den Typ '${D.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${D.key}' sets presentation: 'yesNo' but is type '${D.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),D.presentation==="yesNo"&&D.defaultValue!=null&&r.push({severity:"error",path:X,code:"config.yesno-default",message:{de:`Feld '${D.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 '${D.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),typeof D.minSelections=="number"&&typeof D.maxSelections=="number"&&D.minSelections>D.maxSelections&&r.push({severity:"error",path:X,code:"config.min-gt-max-selections",message:{de:`Feld '${D.key}' hat minSelections (${D.minSelections}) > maxSelections (${D.maxSelections}).`,en:`Field '${D.key}' has minSelections (${D.minSelections}) > maxSelections (${D.maxSelections}).`}});let fe=D.enumRef;fe!==void 0&&r.push({severity:"error",path:`${X}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${D.key}' nennt den entfernten Options-Katalog (enumRef '${String(fe)}'). Die Optionen im Formular angeben (enumOptions + enumOptionLabels) oder eine Liste des Mandanten binden (enumListKey).`,en:`Field '${D.key}' names the removed option catalog (enumRef '${String(fe)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(D.enumOptions??[]).forEach((xe,Ge)=>{let ft=aL(xe);ft!==null&&r.push({severity:"error",path:`${X}.enumOptions[${Ge}]`,code:"config.enum-option-value",message:{de:ft==="empty"?`Feld '${D.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 '${D.key}' hat den Enum-Optionswert '${xe}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:ft==="empty"?`Field '${D.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 '${D.key}' has the enum option value '${xe}', which the single select reserves for its clear row. Rename the option.`}})}),(D.attachments??[]).forEach((xe,Ge)=>{if("storageId"in xe){r.push({severity:"error",path:`${X}.attachments[${Ge}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${D.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 '${D.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 ft=xe.fileKey!==void 0&&xe.fileKey!=="",ot=xe.url!==void 0&&xe.url!=="";ft===ot&&r.push({severity:"error",path:`${X}.attachments[${Ge}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${D.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${ft&&ot?"beide":"keines"}).`,en:`Field '${D.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${ft&&ot?"both":"neither"}).`}}),xe.renderAs==="inlineLink"&&xe.label===void 0&&r.push({severity:"error",path:`${X}.attachments[${Ge}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${D.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${D.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");P.fields.forEach((D,X)=>B(D,`${I}.fields[${X}]`)),P.groups?.forEach((D,X)=>{D.fields.forEach((ce,fe)=>B(ce,`${I}.groups[${X}].fields[${fe}]`))}),P.repeated?.forEach((D,X)=>{D.itemTemplate.forEach((ce,fe)=>B(ce,`${I}.repeated[${X}].itemTemplate[${fe}]`))}),P.subsections?.forEach((D,X)=>R(D,`${I}.subsections[${X}]`))}s(R,"visitFieldConfig"),e.sections.forEach((P,I)=>R(P,`sections[${I}]`)),e.effects.forEach((P,I)=>{if(P.kind==="person"){r.push(...bL(P,e.effects,`effects[${I}]`,B=>l.has(B)));return}P.kind==="organization"&&P.nameFrom?.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nameFrom[${D}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${P.id}': nameFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${P.id}' nameFrom references unknown field '${B}'.`}})})});let A=s((P,I)=>{if(P.kind!=="person"&&P.kind!=="organization")return;let B=P.display;if(!B){r.push({severity:"error",path:`${I}.display`,code:"display.missing",message:{de:`Effekt '${P.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${P.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}oL(B.icon)||r.push({severity:"error",path:`${I}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${P.id}': display.icon '${B.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${P.id}' display.icon '${B.icon}' is not a known bucket icon.`}}),sL(B.color)||r.push({severity:"error",path:`${I}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${P.id}': display.color '${B.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${P.id}' display.color '${B.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((P,I)=>A(P,`effects[${I}]`));let O=new Set,F=s(P=>{P.kind==="person"?O.add(P.bucket):P.kind==="organization"&&O.add(P.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(F);let b=new Set,E=s(P=>{for(let I of P)I.repeated?.forEach(B=>B.effects?.forEach(D=>F(D))),E(I.subsections??[])},"collectRepeatedBuckets");E(e.sections);let q=s((P,I)=>{O.size!==0&&P.forEach((B,D)=>{B.bucket===void 0||O.has(B.bucket)||r.push({severity:"error",path:`${I}[${D}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${B.key}' geh\xF6rt zum Bucket '${B.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${B.key}' belongs to bucket '${B.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),_=s((P,I)=>{if(b.has(P))return;b.add(P);let B=`sections[${I.join(".")}]`;q(P.fields,`${B}.fields`),P.groups?.forEach((D,X)=>q(D.fields,`${B}.groups[${X}].fields`)),P.repeated?.forEach((D,X)=>q(D.itemTemplate,`${B}.repeated[${X}].itemTemplate`)),P.subsections?.forEach((D,X)=>_(D,[...I,X]))},"visitBucketSection");e.sections.forEach((P,I)=>_(P,[I]));let H=e.effects.flatMap((P,I)=>P.kind==="person"&&P.subject===!0?[{e:P,i:I}]:[]);H.length>1&&H.slice(1).forEach(({e:P,i:I})=>{r.push({severity:"error",path:`effects[${I}].subject`,code:"subject.duplicate",message:{de:`Effekt '${P.id}' deklariert subject:true, aber '${H[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${P.id}' declares subject:true, but '${H[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((P,I)=>{if(!(P.kind!=="person"||P.nationalityFrom===void 0)){if(P.subject!==!0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${P.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 '${P.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(P.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${P.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${P.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}P.nationalityFrom.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nationalityFrom[${D}]`,code:"nationality.unknown-field",message:{de:`Effekt '${P.id}': nationalityFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${P.id}' nationalityFrom references unknown field '${B}'.`}})})}});let W=e.effects.flatMap((P,I)=>P.kind==="person"&&P.contractParty!==void 0?[{e:P,i:I,decl:P.contractParty}]:[]);if(W.length>0){let P=W.filter(({decl:I})=>I.role==="beneficiary");P.slice(1).forEach(({e:I,i:B})=>{r.push({severity:"error",path:`effects[${B}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${I.id}' deklariert contractParty.role 'beneficiary', aber '${P[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${I.id}' declares contractParty.role 'beneficiary', but '${P[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),P.forEach(({e:I,i:B})=>{I.subject!==!0&&r.push({severity:"error",path:`effects[${B}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${I.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 '${I.id}' setzen.`,en:`Effect '${I.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 '${I.id}'.`}})}),H.forEach(({e:I,i:B})=>{let D=I.contractParty?.role;D!==void 0&&D!=="beneficiary"&&r.push({severity:"error",path:`effects[${B}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${I.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${D}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${I.id}' is the application subject but declares contractParty.role '${D}'. The application subject is the contract beneficiary.`}})}),W.some(({decl:I})=>I.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((P,I)=>{P.kind==="fieldMap"&&P.mappings.forEach((B,D)=>{a.has(B.from)||r.push({severity:"error",path:`effects[${I}].mappings[${D}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${P.id}': fieldMap from '${B.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${P.id}' fieldMap from '${B.from}' references unknown field.`}})})});for(let[P,I]of u){if(!I.sameAs)continue;let B=`fields[${P}].sameAs`,D=u.get(I.sameAs.source);D===void 0||I.sameAs.source===P?r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:I.sameAs.source===P?`Feld '${P}': sameAs.source verweist auf sich selbst.`:`Feld '${P}': sameAs.source verweist auf das unbekannte Feld '${I.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:I.sameAs.source===P?`Field '${P}' sameAs.source references itself.`:`Field '${P}' sameAs.source references unknown field '${I.sameAs.source}' (must be a top-level or group field).`}}):D.type!==I.type?r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}' (${I.type}): sameAs.source '${I.sameAs.source}' hat einen anderen Typ (${D.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${P}' (${I.type}) sameAs.source '${I.sameAs.source}' has a different type (${D.type}) \u2014 the mirror must be shape-identical.`}}):D.sameAs&&r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}': sameAs.source '${I.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${P}' sameAs.source '${I.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let X=u.get(I.sameAs.toggle);(X===void 0||X.type!=="boolean")&&r.push({severity:"error",path:`${B}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:X===void 0?`Feld '${P}': sameAs.toggle verweist auf das unbekannte Feld '${I.sameAs.toggle}'.`:`Feld '${P}': sameAs.toggle '${I.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${X.type}').`,en:X===void 0?`Field '${P}' sameAs.toggle references unknown field '${I.sameAs.toggle}'.`:`Field '${P}' sameAs.toggle '${I.sameAs.toggle}' must be type 'boolean' (got '${X.type}').`}}),I.required===!0&&r.push({severity:"error",path:`fields[${P}].required`,code:"config.sameas-static-required",message:{de:`Feld '${P}' 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: "${I.sameAs.toggle} != true" verwenden.`,en:`Field '${P}' 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: "${I.sameAs.toggle} != true".`}})}{let P=new Map;e.effects.forEach(I=>P.set(I.id,I.kind)),e.effects.forEach((I,B)=>{if(I.kind!=="shareValue")return;[["from",I.from],["to",I.to]].forEach(([ce,fe])=>{let xe=P.get(fe.slice(1));xe!==void 0&&xe!=="person"&&xe!=="organization"&&r.push({severity:"error",path:`effects[${B}].${ce}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${I.id}': shareValue ${ce} '${fe}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${xe}').`,en:`Effect '${I.id}' shareValue ${ce} '${fe}' must reference a person/organization effect (got '${xe}').`}})});let D=I.from.slice(1);e.effects.some(ce=>ce.kind==="fieldMap"&&ce.target.slice(1)===D&&ce.mappings.some(fe=>fe.to===I.field)||ce.kind==="shareValue"&&ce.id!==I.id&&ce.to.slice(1)===D&&ce.field===I.field)||r.push({severity:"error",path:`effects[${B}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${I.id}' teilt das Feld '${I.field}' aus '${I.from}', aber kein fieldMap mit Ziel '${I.from}' bildet auf '${I.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${I.id}' shares field '${I.field}' from '${I.from}', but no fieldMap targeting '${I.from}' maps to '${I.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((P,I)=>{P.kind==="person"&&P.bucket.includes(qr)&&r.push({severity:"error",path:`effects[${I}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': bucket '${P.bucket}' darf '${qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' bucket '${P.bucket}' must not contain '${qr}' (reserved for the per-row namespace).`}}),P.kind==="organization"&&P.orgKind.includes(qr)&&r.push({severity:"error",path:`effects[${I}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': orgKind '${P.orgKind}' darf '${qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' orgKind '${P.orgKind}' must not contain '${qr}' (reserved for the per-row namespace).`}})});let de=new Set;function J(P,I){P.repeated?.forEach((B,D)=>{let X=B.effects??[];if(X.length>0){let ce=`${I}.repeated[${D}]`,fe=new Set(X.map(ie=>ie.id)),xe=new Set(B.itemTemplate.map(ie=>ie.key)),Ge=(B.uniqueBy?.length??0)>0,ft=s(ie=>ie.startsWith("$item.")?xe.has(ie.slice(6)):l.has(ie),"resolvesName"),ot=s(ie=>ie.startsWith("$item.")?xe.has(ie.slice(6)):a.has(ie),"resolvesFrom"),Ht=s(ie=>{let Nt=ie.slice(1);return fe.has(Nt)||m.has(Nt)},"resolvesRef");X.forEach((ie,Nt)=>{let pt=`${ce}.effects[${Nt}]`;if(m.has(ie.id)||de.has(ie.id)?r.push({severity:"error",path:pt,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${ie.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${ie.id}' is declared more than once.`}}):de.add(ie.id),ie.kind==="person"||ie.kind==="organization"){A(ie,pt),ie.kind==="person"&&ie.subject===!0&&r.push({severity:"error",path:`${pt}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${ie.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 '${ie.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.`}}),ie.kind==="person"&&ie.nationalityFrom!==void 0&&r.push({severity:"error",path:`${pt}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${ie.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${ie.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),ie.kind==="person"&&ie.contractParty!==void 0&&r.push({severity:"error",path:`${pt}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${ie.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 '${ie.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ge||r.push({severity:"error",path:ce,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${B.key}' hat einen Parteien erzeugenden Effekt '${ie.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${B.key}' has a party-creating effect '${ie.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Ne=ie.kind==="person"?ie.bucket:ie.orgKind;Ne.includes(qr)&&r.push({severity:"error",path:`${pt}.${ie.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${ie.id}' der Wiederholung: ${ie.kind==="person"?"bucket":"orgKind"} '${Ne}' darf '${qr}' nicht enthalten.`,en:`Repeated effect '${ie.id}' ${ie.kind==="person"?"bucket":"orgKind"} '${Ne}' must not contain '${qr}'.`}}),ie.kind==="person"&&r.push(...bL(ie,X,pt,ft)),ie.kind==="organization"&&ie.nameFrom?.forEach((Ue,Rn)=>{ft(Ue)||r.push({severity:"error",path:`${pt}.nameFrom[${Rn}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${ie.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Ue}'.`,en:`Repeated effect '${ie.id}' nameFrom references unknown field '${Ue}'.`}})}),ie.identity?.strategy==="keyed"&&ie.identity.keyFrom.forEach((Ue,Rn)=>{ot(Ue)||r.push({severity:"error",path:`${pt}.identity.keyFrom[${Rn}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${ie.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Ue}'.`,en:`Repeated effect '${ie.id}' identity.keyFrom references unknown field '${Ue}'.`}})})}else if(ie.kind==="relationship"){if([["from",ie.from],["to",ie.to]].forEach(([Ne,Ue])=>{Ht(Ue)||r.push({severity:"error",path:`${pt}.${Ne}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: ${Ne} verweist auf den unbekannten Effekt '${Ue}'.`,en:`Repeated relationship '${ie.id}' ${Ne} references unknown effect '${Ue}'.`}})}),ie.meta)for(let[Ne,Ue]of Object.entries(ie.meta))typeof Ue=="string"&&Ue.startsWith("$")&&!Ht(Ue)&&r.push({severity:"error",path:`${pt}.meta.${Ne}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: meta.${Ne} verweist auf den unbekannten Effekt '${Ue}'.`,en:`Repeated relationship '${ie.id}' meta.${Ne} references unknown effect '${Ue}'.`}})}else ie.kind==="fieldMap"?(Ht(ie.target)||r.push({severity:"error",path:`${pt}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${ie.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${ie.target}'.`,en:`Repeated fieldMap '${ie.id}' target references unknown effect '${ie.target}'.`}}),ie.mappings.forEach((Ne,Ue)=>{ot(Ne.from)||r.push({severity:"error",path:`${pt}.mappings[${Ue}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${ie.id}' der Wiederholung: from '${Ne.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${ie.id}' from '${Ne.from}' references unknown field.`}})})):ie.kind==="shareValue"&&r.push({severity:"error",path:pt,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${ie.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${ie.id}': shareValue is not supported inside repeated row effects.`}})})}}),P.subsections?.forEach((B,D)=>J(B,`${I}.subsections[${D}]`))}s(J,"visitRepeatedEffects"),e.sections.forEach((P,I)=>J(P,`sections[${I}]`));let oe=zF(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(...r4(e)),r}s(vL,"validateForm");function r4(e){let t={...e,effects:e.effects.map(xL),sections:e.sections.map(SL),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return Lf(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:Gy(n)}))}s(r4,"missingTranslationIssues");function xL(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(xL,"withoutSubjectFlag");function SL(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(xL)})),subsections:e.subsections?.map(SL)}}s(SL,"withoutRowSubjectFlags");function yL(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(yL,"exportGateIssues");function na(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${wL(r,"de")} '${t}'`,en:`Duplicate ${wL(r,"en")}: '${t}'`}}):e.add(t)}s(na,"reportIfDup");function wL(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(wL,"labelForCode");function rv(e,t,n,r,i,o){e.visibleIf&&(hr(e.visibleIf,`${t}.visibleIf`,n,r,o),ra(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(hr(e.requiredIf,`${t}.requiredIf`,n,r,o),ra(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(hr(e.disabledIf,`${t}.disabledIf`,n,r,o),ra(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&hr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(rv,"checkFieldAsts");function iv(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo"}}s(iv,"gatingMeta");function ra(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(kL(o.left,o.right,o.op,t,n,r),kL(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(ra,"checkGatingExpr");function kL(e,t,n,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);a&&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(kL,"inspectEqualityOperand");function hr(e,t,n,r,i){i.push(...hL(e,n.declaredContext,t)),i.push(...fL(e,n.stageKeys,t));for(let o of kt(e))n.known.has(o)||tv(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(hr,"checkAst");function bL(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 ${mr.firstName} / ${mr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${mr.firstName} / ${mr.lastName}. Remove nameFrom.`}});let o=tL(e.id,t);rL(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${mr.firstName} oder ${mr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${mr.firstName} or ${mr.lastName} \u2014 the person would get no name.`}});for(let a of nL(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(bL,"personNameIssues");var i4="blocked";function AL(e,t){let n={values:t};for(let r of e.outcomes){let i;try{i=gt(r.when,n)}catch(o){N(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(o4(i))return r.id===i4?null:r.id}return null}s(AL,"resolveActiveOutcome");function o4(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(o4,"truthy");function EL(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(EL,"isScalar");function s4(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(EL(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))EL(a)&&(t[`${r}.${o}`]=a)}a4(e,t,n)}s(s4,"mergeRecord");function a4(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);Bi(a).test(i)&&r.add(a)}for(let i of r){let o=Zb(e,i),a=0;for(let l=0;l<o;l++)YF(e,i,l)&&a++;t[`${i}.count`]=a}}s(a4,"mergeRepeatedCounts");function TL(e,t,n){let r={...n};return s4(e,r,t),r}s(TL,"flattenValues");function ov(e,t,n){return{code:e,fieldKey:t,text:n}}s(ov,"submitIssue");function $L(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s($L,"truthyEval");function RL(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(RL,"isEmptyValue");function l4(e,t,n){let r=!!e.required;if(!r&&e.requiredIf)try{r=$L(gt(e.requiredIf,{values:t}))}catch{r=!1}return r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(l4,"fieldIsLiveRequired");function d4(e,t,n){return IL(e,t,n).evalCtx}s(d4,"buildSubmitEvalContext");function IL(e,t,n){let r=c4(e),i=Object.keys(t).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[y,k]of Object.entries(t))(r(y)===null||o.has(y))&&(l[y]=k);let d=OL(e,l,n),c=new Set,u=new Set;_L(e,d,y=>c.add(y.key),y=>u.add(y.key));let f=new Set(i.filter(y=>{let k=r(y);return k.kind==="field"?c.has(y):u.has(k.repeatedKey)}));if(f.size===o.size&&[...f].every(y=>o.has(y))){let y={};for(let k of i)o.has(k)||(y[k]=t[k]);return{visible:l,hidden:y,evalCtx:d}}let m=[...f].sort().join("\0");if(a.has(m)){let y=i.filter(k=>f.has(k)!==o.has(k));N(`[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(m),o=f}}s(IL,"splitWithContext");function c4(e){let t=new Map,n=[];for(let r of sm(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:Bi(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(c4,"fieldOwnership");function OL(e,t,n){let r=[];for(let o of sm(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=TL(t,r,n);for(let o of sm(e.sections))for(let a of o.computed??[])try{i[a.key]=gt(a.expression,{values:i})}catch{}return i}s(OL,"rawEvalContext");function PL(e,t,n){let{values:r,defaulted:i}=u4(e,t,n),o=IL(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(PL,"splitDraftValues");function u4(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of sm(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??=OL(e,t,n);let c;try{c=gt(d.defaultValue,{values:a})}catch(u){N(`[smartForm] defaultValue of '${d.key}' does not evaluate: ${u instanceof Error?u.message:String(u)}`)}c!=null&&(i[d.key]=c,o.add(d.key))}return{values:i,defaulted:o}}s(u4,"applyFieldDefaults");function sm(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(sm,"walkSectionsDeep");function f4(e,t,n,r=!1){if(RL(t))return null;let i=n.fields[e.type];i||N(`[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(f4,"fieldFormatIssue");function om(e,t){if(!e)return!0;try{return $L(gt(e,{values:t}))}catch{return!1}}s(om,"isVisibleUnder");function _L(e,t,n,r){let i=s(o=>{if(om(o.visibleIf,t)){for(let a of o.fields)om(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(om(a.visibleIf,t))for(let l of a.fields)om(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(_L,"forEachVisibleField");function NL(e,t,n,r={}){let i=d4(e,t,n),o=[],a=AL(e,i);a===null&&r.requireOutcome!==!1&&o.push(ov("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 _L(e,i,d=>{let c=t[d.key];if(RL(c)){!l.has(d.type)&&l4(d,i,a)&&o.push(ov("required",d.key,Va([d.label],([f],m)=>m==="de"?`${f} ist ein Pflichtfeld.`:`${f} is a required field.`)));return}if(!r.registry)return;let u=f4(d,c,r.registry,r.testMode===!0);u!==null&&o.push(ov("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(NL,"checkSubmittable");function CL(e){let t=e.testScenarios??[];if(t.length===0)return[];let{compiled:n}=qs(e),r=[];for(let i of t){let o=i.prefill??{};if(!dL(e,i.env))continue;let a=uL(e,i.env),{visible:l}=PL(n,o,a),d=NL(n,l,a,{exemptFromRequired:["docRef"]});for(let c of d.issues){if(c.code==="no-outcome"){r.push({severity:"error",path:`scenario:${i.id}`,code:"scenario.no-outcome",message:{de:`Szenario "${i.label.de}" erreicht kein g\xFCltiges Outcome \u2013 der Testfall ist nicht absendbar.`,en:`Scenario "${i.label.en}" reaches no valid outcome \u2013 the test case cannot be submitted.`}});continue}if(c.code==="required"){r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.required-field-unfilled",message:{de:`Szenario "${i.label.de}" l\xE4sst das Pflichtfeld ${c.fieldKey} unbef\xFCllt \u2013 kein g\xFCltiges Outcome.`,en:`Scenario "${i.label.en}" leaves the required field ${c.fieldKey} empty \u2013 no valid outcome.`}});continue}r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.invalid-value",message:Va([i.label,c.text],([u,f],m)=>m==="de"?`Szenario "${u}": ${f}`:`Scenario "${u}": ${f}`)})}}return r}s(CL,"validateScenarios");function am(e){return e.filter(t=>(t.severity??"error")==="error")}s(am,"blockingIssues");function lm(e,t={}){return[...vL(e,t),...CL(e)]}s(lm,"runFormValidators");function dm(e){return am(e)}s(dm,"blockingFormErrors");function DL(e,t,n){return PP(e,t,n)}s(DL,"runWorkflowValidators");function FL(e){return am(e)}s(FL,"blockingWorkflowErrors");var p4=["artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],LL={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"]},review:{required:[],optional:["commentRequired","decisionAsTask","reads"]},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"]}},un={id:w.string(),label:Gs,artifacts:w.optional(w.any()),assign:w.optional(w.any()),inputs:w.optional(w.any()),library:w.optional(w.any()),next:w.optional(w.any()),notifications:w.optional(w.any()),optionalActions:w.optional(w.any()),outcomes:w.optional(w.any()),outputLabels:w.optional(w.any()),sublabel:w.optional(w.any()),tasks:w.optional(w.any())},m4=w.object({...un,type:w.literal("join")}),h4=w.object({...un,type:w.literal("end")}),g4=w.object({...un,type:w.literal("eventTrigger")}),y4=w.object({...un,type:w.literal("form"),adoptForm:w.optional(w.any()),formExports:w.optional(w.any())}),w4=w.object({...un,type:w.literal("roleAssign")}),k4=w.object({...un,type:w.literal("setFlag")}),b4=w.object({...un,type:w.literal("if"),condition:w.optional(w.any())}),v4=w.object({...un,type:w.literal("countersign"),contract:w.optional(w.any()),signing:w.optional(w.any()),titles:w.optional(w.any())}),x4=w.object({...un,type:w.literal("engagePush"),contract:w.optional(w.any()),engage:w.optional(w.any()),form:w.optional(w.any()),payment:w.optional(w.any())}),S4=w.object({...un,type:w.literal("decision"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any()),requiresOneOf:w.optional(w.any())}),A4=w.object({...un,type:w.literal("review"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any())}),E4=w.object({...un,type:w.literal("waitlist")}),T4=w.object({...un,type:w.literal("completenessCheck"),deadline:w.optional(w.any()),requires:w.optional(w.any())}),$4=w.object({...un,type:w.literal("collectPayment")}),R4=w.object({...un,type:w.literal("governedDocument"),approval:w.optional(w.any()),confirmBeforeIssue:w.optional(w.any()),confirmContractTerms:w.optional(w.any()),contractTermsQuestionText:w.optional(w.any()),form:w.optional(w.any()),generatorStamp:w.optional(w.any()),production:w.optional(w.any()),reads:w.optional(w.any()),responseLabels:w.optional(w.any()),responseStrategy:w.optional(w.any()),templateStamp:w.optional(w.any()),titles:w.optional(w.any())}),f_e=w.union(m4,h4,g4,y4,w4,k4,b4,v4,x4,S4,A4,E4,T4,$4,R4);function ML(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 LL)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=LL[a],d=new Set(["id","type","label",...p4,...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(ML,"workflowNodeEnvelopeIssues");function qL(e,t){return e.enumOptionLabels?.[t]??{de:t,en:t}}s(qL,"inlineEnumOptionLabel");var jL={string:"string",boolean:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function BL(e){return jL[e]!==void 0}s(BL,"isExportableFieldType");function I4(e){return e.exportType===void 0&&N(`formExports: computed '${e.key}' is exported without an exportType \u2014 the publish validator should have refused this form.`),{key:e.key,type:e.exportType,label:e.label??{de:e.key,en:e.key}}}s(I4,"leafForComputed");function KL(e){let t=jL[e.type];return t===void 0&&N(`formExports: field '${e.key}' has type '${e.type}', which is not exportable \u2014 the publish validator should have refused this form.`),{key:e.key,type:t,label:e.label,...e.enumOptions!==void 0?{enumOptions:e.enumOptions.map(n=>({value:n,label:qL(e,n)}))}:{}}}s(KL,"leafFor");function sv(e){let t=[],n=s(r=>{for(let i of r.fields)i.export===!0&&t.push(KL(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&t.push(KL(o));for(let i of r.computed??[])i.export===!0&&t.push(I4(i));for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(sv,"exportedFormLeaves");var UL=s(e=>e,"asEffectId"),Ui=s(e=>e,"asOutcomeId"),ia=s(e=>e,"asSectionId"),nn=s(e=>e,"asFieldKey");var oi=["string","boolean","date","enum","email","tel","address","docRef"],wd=["person","organization","relationship","fieldMap"],Vi=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],oa=["fresh","keyed","manual"];function Lo(e,t,n,r){if(e===void 0||e===""){if(t!==void 0&&t!=="")throw new Error(`${n}: ${r}-en needs ${r} too`);return}return ct(e,t,n,r)}s(Lo,"optionalLocalizedText");function zt(e,t){if(!(e===void 0||e===""))try{qt(e)}catch(n){throw new Error(`offer form: ${t} is not a valid expression: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}s(zt,"assertExpression");function kd(e){return Object.keys(e.smartforms??{})}s(kd,"carriedFormSlugs");function av(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(av,"boundFormSlugs");function cm(e,t){let n=kd(e);if(t){if(!n.includes(t))throw new Error(`offer form: no smartform "${t}" in this bundle (have: ${n.join(", ")||"none"})`);return t}if(n.length===0)throw new Error("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(n.length>1)throw new Error(`offer form: bundle carries ${n.length} smartforms \u2014 pass --form <key> (one of: ${n.join(", ")})`);return n[0]}s(cm,"resolveFormSlug");function um(e,t){let n=e.smartforms?.[t];if(!n)throw new Error(`offer form: smartform "${t}" not found in bundle`);return n}s(um,"getForm");function Mn(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(Mn,"walkSections");function Xn(e,t){return Mn(e).find(n=>n.id===t)}s(Xn,"findSection");function Mo(e,t){for(let n of Mn(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Mo,"findField");function qo(e){let t=new Set;for(let n of Mn(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(qo,"allFieldKeys");function O4(e){let t=ct(e.label,e.labelEn,"offer form add"),n={id:ia("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Ui("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(O4,"buildSkeletonSmartForm");function fm(e,t){let{key:n,label:r}=t;if(kd(e).includes(n))throw new Error(`offer form add: smartform "${n}" already exists in this bundle`);let i=O4({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(fm,"addForm");function VL(e,t){if(!kd(e).includes(t))throw new Error(`offer form rm: smartform "${t}" not found in bundle`);if(av(e).includes(t))throw new Error(`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(VL,"removeForm");function GL(e,t){let n=um(e,t.slug);if(t.label===void 0&&t.labelEn===void 0)throw new Error("offer form set: nothing to change \u2014 pass --label/--label-en");if(t.label==="")throw new Error("offer form set: --label cannot be empty");yt(n,"label",{de:t.label,en:t.labelEn},"offer form set")}s(GL,"setForm");function zL(e,t){let n=e.workflow?.graph?.nodes;if(!Array.isArray(n))throw new Error(`${t}: the bundle carries no workflow graph (workflow.json)`);return n}s(zL,"nodesOf");function WL(e,t,n){let r=zL(e,n),i=r.find(o=>o.id===t);if(i===void 0)throw new Error(`${n}: no node "${t}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(WL,"nodeOf");function YL(e){return e.flatMap(t=>{if(t.type!=="form"||kn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(YL,"creatingFormNodes");function HL(e){return dm(lm(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(HL,"formErrors");function pm(e){let t="offer workflow restamp-exports",n=zL(e,t),r=[];for(let{node:i,slug:o}of YL(n)){let a=e.smartforms?.[o];if(a===void 0)throw new Error(`${t}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=HL(l);if(d.length>0)throw new Error(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
10345
10345
  ${d.join(`
10346
10346
  `)}`);let c=sv(l),u=Array.isArray(i.formExports)?i.formExports.map(m=>m.key):null,f=i.formExports===void 0||Pe(i.formExports)!==Pe(c);i.formExports=c,r.push({node:i.id,form:o,before:u,after:c.map(m=>m.key),changed:f})}for(let i of n)if(i.type==="form"&&kn(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(pm,"restampFormExports");function JL(e){let t=e.workflow?.graph?.nodes??[];return YL(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 HL(o).length>0?[]:Pe(n.formExports)===Pe(sv(o))?[]:[{node:n.id,form:r}]})}s(JL,"staleFormExports");var lv=["string","number","boolean","date"];function QL(e,t){let n="offer form field export";for(let r of Mn(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 Error(`${n}: --type is for a computed field; "${t.key}" is an entered ${i.type} field and exports as its own type`);if(t.on&&!BL(i.type))throw new Error(`${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 Error(`${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 Error(`${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 Error(`${n}: "${t.key}" is a computed field \u2014 name its type with --type (${lv.join("|")}); an expression has none to infer`);if(!lv.includes(d))throw new Error(`${n}: --type "${d}" is no computed export type (${lv.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 Error(`${n}: "${t.key}" sits in a repeated block \u2014 a row value is no per-application leaf (export.in-repeated)`)}throw new Error(`${n}: the form has no field "${t.key}"`)}s(QL,"setFieldExport");function ZL(e,t,n){let r="offer workflow node set-generator",i=WL(e,t,r);if(tm(i)!=="resolver")throw new Error(`${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 Error(`${r}: the ${n.kind} key is empty`);let l=Yr(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??{},[Ft]:{kind:"literal",value:{kind:n.kind,key:a}}};let u=d?[]:Object.keys(i.inputs).filter(f=>f!==Ft&&f!==Fn);return{before:l,after:{key:a,kind:n.kind},droppedStamp:c,keptParameterCells:u}}s(ZL,"setGeneratorPin");function XL(e,t,n){let r="offer workflow node set-cockpit-fields",i=WL(e,t,r),o=tm(i);if(o!=="resolver"&&o!=="template")throw new Error(`${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"?Yr(i)!==null:lr(i)!==null))throw new Error(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 u of n){if(l.has(u))throw new Error(`${r}: --fields names "${u}" twice`);l.add(u)}let d={...i.inputs??{}},c=Object.keys(d).filter(u=>d[u]?.kind==="cockpit");for(let u of n){let f=d[u]?.kind;if(f!==void 0&&f!=="cockpit"&&f!=="unset")throw new Error(`${r}: "${u}" holds a ${String(f)} \u2014 a parameter has one source; remove it first (offer workflow node set-input --clear)`)}for(let u of c)l.has(u)||delete d[u];for(let u of n)d[u]={kind:"cockpit"};return i.inputs=d,{pin:o,before:c,after:[...n]}}s(XL,"setCockpitFields");var P4=new Set(["graph","progressLayout","progressWiring"]);function e0(e){let{label:t,...n}=e;return n}s(e0,"definitionOf");function _4(e){let t=[];for(let o of Object.keys(e))P4.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(oR.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(...ML(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(_4,"workflowShapeIssues");function t0(e){let t=e.nodes??[],n=new Map;for(let r of t){let i=QR(r);i!==void 0&&n.set(r.id,i)}return n}s(t0,"formNodeSlugById");function N4(e,t){let n=e.smartforms??{},r=new Map;for(let[i,o]of t0(t)){let a=n[o];if(a===void 0)return;r.set(i,e0(a))}return tP(r)}s(N4,"readinessContext");function C4(e){return[...t0(e).values()]}s(C4,"formNodeSlugs");function mm(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(mm,"describe");function $n(e){let t=[];for(let l of Vu(e.manifest))t.push({severity:"error",area:"manifest",message:l});let n=Et(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 Ep(e.index.program?.stages??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of Rp(e.index.program?.runs??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of Ip(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 v of _4(e.workflow))t.push({severity:"error",area:"workflow",message:v});let l=e.workflow.graph,d=e.workflow.progressLayout,c=e.workflow.progressWiring;if(d!==void 0)for(let v of iR(d))t.push({severity:"error",area:"workflow",message:v});let u=[];for(let{node:v,key:$,kind:R}of nm(e))v.generatorStamp?.schemaDigest===void 0&&(u.push(v.id),t.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped] Knoten "${v.id}" pinnt ${R}:${$} 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 v of l.nodes)v.type!=="governedDocument"||v.production!=="template"||v.templateStamp!==void 0||t.push({severity:"warning",area:"workflow",message:`[template/notStamped] Knoten "${v.id}" f\xFCllt die Vorlage ${lr(v)??"\u2014"} ohne ihre Parameter \u2014 welche Felder sie hat, pr\xFCft erst \`offer plan\` (stempelt sie vom Vorlagen-Datensatz der Umgebung).`});for(let{node:v,form:$}of JL(e))t.push({severity:"warning",area:"workflow",message:`[formExports/stale] Knoten "${v}": der Stempel formExports passt nicht mehr zum Formular "${$}" \u2014 die Adresspr\xFCfung liest den alten Stand; \`offer workflow restamp-exports\` stempelt ihn neu (publish tut es ohnehin).`});let f=N4(e,l),m=s(v=>{let $=DL(v,{layout:d,wiring:c},f),R=new Set(FL($));return{issues:$,isError:s(A=>R.has(A)||(A.severity??"error")==="error","isError")}},"blockingOf"),{issues:y,isError:k}=m(l),g=new Set;if(u.length>0){let v=structuredClone(l);for(let O of v.nodes)u.includes(O.id)&&(O.generatorStamp={...O.generatorStamp??{},parts:[{partKey:"?"}]});let $=m(v),R=new Set($.issues.filter($.isError).map(mm)),A=s(O=>u.some(F=>O.includes(`$node.${F}.contract`)),"namesOutput");for(let O of y){let F=mm(O);k(O)&&!R.has(F)&&A(F)&&g.add(F)}}for(let v of y){let $=mm(v);if(g.has($)){t.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped \u2192 offer plan] ${$}`});continue}t.push({severity:k(v)?"error":"warning",area:"workflow",message:$})}}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=Et(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=e0(d);for(let k of sR(u,`smartforms/${l}.json`))t.push({severity:"error",area:"smartform",message:k.de});let f=u,m=lm(f,{stageKeys:a}),y=new Set(dm(m));for(let k of m)t.push({severity:y.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${mm(k)}`});for(let k of[...GF(f),...VF(f)])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(C4(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($n,"validateBundle");async function dv(e,t,n){let r=nm(n);if(r.length===0)return{rows:[],issues:[]};let i=[...new Map(r.map(({key:c,kind:u,revision:f})=>[`${u}:${c}:${f??"current"}`,{key:c,kind:u,...f===void 0?{}:{revision:f}}])).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")?new Error(`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).`,{cause:c}):c}),a=new Map(o.map(c=>[`${c.kind}:${c.key}:${c.revision??"current"}`,c])),l=[],d=[];for(let{node:c,key:u,kind:f,revision:m}of r){let y=a.get(`${f}:${u}:${m??"current"}`);if(y===void 0)throw new Error(`offer: the environment answered no stamp for ${f}:${u}`);if(y.stamp===null){if(y.refusal===null)throw new Error(`offer: the environment answered neither a stamp nor a refusal for ${f}:${u}`);d.push({severity:"error",area:"workflow",message:`[resolver/pinRefused] Knoten "${c.id}": ${y.refusal.de}`});continue}rR(c,structuredClone(y.stamp),{freezeRevision:!0}),l.push({target:`stamp:${c.id}`,detail:y.stamp.parts===void 0?`${f}:${u} Dokument`:`${f}:${u} kombiniert (${y.stamp.parts.map(k=>k.partKey).join(", ")})`})}return{rows:l,issues:d}}s(dv,"stampResolverPins");async function cv(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=lr(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=lr(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(RD(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(cv,"stampTemplatePins");async function n0(e,t,n){let r=Ke(n),i=await dv(e,t,r),o=await cv(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 Error("offer workflow restamp-pins: the bundle pins no contract generator or package (offer workflow node set-generator) and fills no Word template");An(r);let d=a.map(f=>f.target.slice(6)),c=s(f=>d.some(m=>f.includes(`nodes.${m}.`)||f.includes(`node.${m}.`)||f.includes(`"${m}"`)),"onStamped"),u=$n(r).filter(f=>f.severity==="error"&&c(f.message));return{rows:a,refused:[],open:u}}s(n0,"restampPinsOnDisk");var D4=G.join("contract","resolver-setup.json"),si="resolver setup",sa=s((e,t)=>Rt(e,t,si),"record"),Gi=s((e,t)=>Ve(e,t,si),"text");function F4(e,t){let n=sa(e,"Datei"),r=sa(n.contractTemplate,"contractTemplate"),i=sa(n.resolver,"resolver");return{dir:t,contractTemplate:{key:Gi(r.key,"contractTemplate.key"),name:dn(r.name,"contractTemplate.name",si,"Vorlagennamen"),file:Gi(r.file,"contractTemplate.file"),role:Gi(r.role,"contractTemplate.role")},revenueAccounts:Wf(n.revenueAccounts,si),billingItems:Yf(n.billingItems,si),resolver:{key:Gi(i.key,"resolver.key"),name:dn(i.name,"resolver.name",si,"Generatornamen"),description:i.description===void 0?null:dn(i.description,"resolver.description",si,"Beschreibungen"),legalText:i.legalText??{},source:Gi(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:_n(i.feeGroups,"resolver.feeGroups",si)).map((o,a)=>{let l=sa(o,`resolver.feeGroups[${a}]`);return{key:Gi(l.key,"feeGroup.key"),name:dn(l.name,"feeGroup.name",si,"Geb\xFChrengruppen"),billingItemKeys:uv(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:uv(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:uv(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:L4(i.scenarios??[]),config:sa(i.config,"resolver.config")}}}s(F4,"parseResolverSetup");function uv(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||n.trim()==="")||new Set(e).size!==e.length)throw new Error(`generator setup: ${t} must be a list of unique keys.`);return e}s(uv,"stringList");function L4(e){if(!Array.isArray(e)||e.length>20)throw new Error("generator setup: scenarios must be a list of at most 20 reviewed examples.");return e.map(t=>{let n=sa(t,"scenario");if(!("input"in n)||!("expected"in n))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:Gi(n.key,"scenario.key"),input:n.input,expected:n.expected}})}s(L4,"parseScenarios");function hm(e){let t=G.resolve(e);return F4(JSON.parse(ye(t,"utf8")),G.dirname(t))}s(hm,"readResolverSetup");function M4(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!(r in n))throw new Error(`resolver setup: resolver.config.${t} existiert nicht.`);n=n[r]}return n}s(M4,"configValue");function r0(e){let t=s(()=>Gi(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),n=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...fv(e.resolver.config),...e.resolver.billingItemKeys])].filter(r=>!n.has(r)),billingItems:e.billingItems.map(r=>{if(r.programs!==void 0)throw new Error(`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 Error(`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"?M4(e.resolver.config,i.$config):i;if(typeof o!="number"||!Number.isFinite(o))throw new Error(`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(r0,"billingSetupPayload");function i0(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 Error(`resolver setup: $billingItem ${JSON.stringify(n)} ist kein Schl\xFCssel.`);return n}s(i0,"billingItemRef");function fv(e){if(Array.isArray(e))return e.flatMap(fv);if(typeof e!="object"||e===null)return[];let t=i0(e);return t!==void 0?[t]:Object.values(e).flatMap(fv)}s(fv,"billingItemRefs");function pv(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 Error(`generator setup: grant template ${String(l)} is not declared.`);return n[l]}let a=i0(i);if(a!==void 0){if(!(a in t))throw new Error(`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(pv,"renderResolverConfig");function q4(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 Error("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(q4,"assertPlaceholderParity");function K4(e,t){let n=[...e].filter(r=>r.status==="sealed").sort((r,i)=>i.revisionNumber-r.revisionNumber)[0];if(n!==void 0)return n.source===t.source&&n.pinnedDocumentTemplateId===t.documentTemplateId&&Pe(n.config)===Pe(t.config)&&Pe(n.legalText)===Pe(t.legalText)&&Pe([...n.billingItemDefinitionIds].sort())===Pe([...t.billingItemDefinitionIds].sort())&&Pe([...n.grantTemplateIds].sort())===Pe([...t.grantTemplateIds].sort())&&Pe(n.feeGroups)===Pe(t.feeGroups)?n:void 0}s(K4,"matchingSealedRevision");async function bd(e,t,n){if(n.resolver.source===null)throw new Error("generator setup requires a self-contained source file.");let r=ye(G.join(n.dir,n.resolver.source),"utf8"),i=await El(G.join(n.dir,n.contractTemplate.file));q4(n.resolver.config,i);let o=await e.query(S.contractSetup.planBillingSetup,{client:t,...r0(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 R of n.resolver.grantTemplateKeys){let A=d.grantTemplates.find(O=>O.configKey===R);if(A===void 0)throw new Error(`Unknown grant template ${R}`);c[R]=A.id}let u=pv(n.resolver.config,o.billingItemIds,c),m=(await e.query(S.contractGeneratorRevisions.model,{client:t})).find(R=>R.definition.key===n.resolver.key),y=m?.currentRevisionId?await e.query(S.contractGeneratorRevisions.detail,{client:t,id:m.currentRevisionId}):null,k=m?.revisions.find(R=>R.status==="draft"),g=k?await e.query(S.contractGeneratorRevisions.detail,{client:t,id:k.id}):null,v=l||y===null?void 0:K4([y],{source:r,config:u,legalText:n.resolver.legalText,documentTemplateId:a.id,billingItemDefinitionIds:n.resolver.billingItemKeys.map(R=>o.billingItemIds[R]??`not-created:${R}`),grantTemplateIds:Object.values(c),feeGroups:n.resolver.feeGroups.map(R=>({key:R.key,name:R.name,billingItemDefinitionIds:R.billingItemKeys.map(A=>o.billingItemIds[A]??`not-created:${A}`)}))}),$=o.rows.map(R=>({step:R.kind,target:R.key,action:R.action,detail:R.detail}));return $.push({step:"wordTemplate",target:n.contractTemplate.key,action:l?"create":"same",detail:G.basename(i.file)}),$.push({step:"generatorRevision",target:n.resolver.key,action:v?"same":"create",detail:v?`Current sealed revision ${v.revisionNumber}`:"Save source, review scenarios and seal a new revision"}),{rows:$,docx:i,source:r,renderedConfig:u,billingItemIds:o.billingItemIds,grantTemplateIds:c,head:m,current:y,draft:g,match:v,template:{documentTemplateId:a?.id??null,upload:l}}}s(bd,"planResolverSetup");async function o0(e,t,n){let r=await bd(e,t,n);if(r.rows.every(f=>f.action==="same"))return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}};if(!r.match&&n.resolver.scenarios.length===0)throw new Error("A new generator revision requires reviewed scenarios.");let i=await e.mutation(S.contractSetup.applyBillingSetup,{client:t,...r0(n)});if(r.match)return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}};let o=r.template.upload?await zf(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.contractGeneratorRevisions.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.contractGeneratorRevisions.cloneDraft,{client:t,id:r.current._id})}let l=await e.query(S.contractGeneratorRevisions.detail,{client:t,id:a}),d=await e.mutation(S.contractGeneratorRevisions.save,{client:t,id:a,expectedSourceRevision:l.sourceRevision,config:pv(n.resolver.config,i.billingItemIds,r.grantTemplateIds),legalText:n.resolver.legalText,documentTemplateId:o}),c=await e.action(S.contractGeneratorRevisionActions.saveSource,{client:t,id:a,expectedSourceRevision:d,source:r.source,billingItemDefinitionIds:n.resolver.billingItemKeys.map(f=>i.billingItemIds[f]),grantTemplateIds:Object.values(r.grantTemplateIds),feeGroups:n.resolver.feeGroups.map(f=>({key:f.key,name:f.name,billingItemDefinitionIds:f.billingItemKeys.map(m=>i.billingItemIds[m])}))});if(c.diagnostics.length||c.sourceRevision===null||c.artifactHash===null)throw new Error(c.diagnostics.join(`
10347
10347
  `));if(d=c.sourceRevision,await e.mutation(S.contractGeneratorRevisions.approveScenarios,{client:t,id:a,expectedSourceRevision:d,artifactHash:c.artifactHash,scenarios:pv({scenarios:n.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await e.mutation(S.contractGeneratorRevisions.seal,{client:t,id:a,expectedSourceRevision:d}),(await bd(e,t,n)).match===void 0)throw new Error("The sealed revision does not match the declarative setup.");return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}}}s(o0,"applyResolverSetup");async function mv(e,t,n){let r=G.join(n.dir,D4);if(!Ae(r)||n.workflow===void 0)return[];let i=hm(r);if((await bd(e,t,i)).match===void 0)throw new Error("Apply the generator setup before publishing the offer.");return[]}s(mv,"pinSetupRevisions");function j4(e){if(e.label===void 0)return;let t=e.label;if(typeof t!="object"||t===null||typeof t.de!="string"||typeof t.en!="string")throw new Error(`node "${e.id}": label ${JSON.stringify(e.label)} is not a { de, en } text`);return{de:t.de,en:t.en}}s(j4,"nodeText");function vd(e,t){let n=[],r=[],i=[],o={},a=t.progressEvents??[],l=j4(e);for(let d of a){let c=`${e.id}.${d}`,u=t.progressDefaults?.[d];if(u===void 0)throw new Error(`node "${e.id}" (${e.type}) emits progress-event "${d}", but its node spec declares no progress default for it`);let f=e.type==="decision"&&d==="released"&&l!==void 0,m=f?l:u.label,y=u.tone,k={id:c,label:m,tone:y,external:u.external};u.terminal&&(k.terminal=!0),n.push(k),r.push({match:{nodeId:e.id},event:d,bus:"process",state:c});let g=u.phase,v=B4(g,e.id),$=i.find(R=>R.id===v);if($)$.states=[...$.states,c];else{let R={id:v,label:f?m:g.label,tone:y,states:[c]};g.track&&(R.track=g.track),g.defaultCollapsed&&(R.defaultCollapsed=!0),g.waitlist&&(R.waitlist=!0),i.push(R)}u.terminal&&(o[c]=u.terminal)}return{states:n,mappings:r,columns:i,terminalSemantics:o}}s(vd,"deriveProgressEntriesForNode");function gm(e){return Object.entries(e).filter(([,t])=>t.outcome==="approved").map(([t])=>t)}s(gm,"seatedTerminalStates");function B4(e,t){return e.scope==="global"?`col.${e.key}`:`${t}.${e.key}`}s(B4,"columnIdFor");function s0(e,t){let n=s(i=>(i.states??[]).some(o=>t.terminalStateIds.has(o)),"isTerminal"),r=s(i=>{let o=t.columnNodeId(i);return(o!==void 0?t.nodeOrder.get(o):void 0)??Number.POSITIVE_INFINITY},"topoOf");return e.map((i,o)=>({c:i,idx:o,term:n(i)?1:0,topo:r(i)})).sort((i,o)=>i.term-o.term||i.topo-o.topo||i.idx-o.idx).map(i=>i.c)}s(s0,"orderProcessColumns");var er=s((e,t)=>({de:e,en:t}),"lt"),gv=ls("start",[]),ym=ls("form",[gv]),hv=ls("end",[gv,ym]);function U4(e){let t=[vd({id:ym,type:"form",label:er("Formular","Form")},Fo.form),vd({id:hv,type:"end",label:er("Ende","End")},Fo.end)],n=[],r=[],i=[],o={};for(let c of t){n.push(...c.states),i.push(...c.mappings),o={...o,...c.terminalSemantics};for(let u of c.columns){let f=r.find(m=>m.id===u.id);f?f.states=[...new Set([...f.states,...u.states])]:r.push(u)}}let a=gm(o);return{layout:{id:`layout.${e}.starter`,buses:[{key:"process",states:n,terminalSemantics:o,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:er("Prozess","Process"),audience:"both",columns:r}]}]},wiring:{mappings:i}}}s(U4,"buildStarterProgress");function a0(e){let{slug:t,title:n,tenant:r,unit:i,responsible:o}=e,a=t,l=`${t}-form`,d=`${t}-flow`,c=[{id:gv,type:"eventTrigger",label:er("Start","Start"),sublabel:er("Eingang externer Bewerber-Aktion","Incoming external applicant action"),next:{bewerbungOffen:{to:ym}}},{id:ym,type:"form",label:n,sublabel:er("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:er("Standard","Standard")}],next:{standard:{to:hv}},notifications:{submitted:{templateId:"applicant.applicationSubmitted"}}},{id:hv,type:"end",label:er("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"}}}],u={nodes:c,assignmentRules:KO(BO([{slot:"responsible",rules:[{when:Ci,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:o}}]}],Nf({nodes:c})))},{layout:f,wiring:m}=U4(d),y={id:ia("section.applicant"),label:er("Antragsteller","Applicant"),fields:[{key:nn("applicant.vorname"),label:er("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:nn("applicant.nachname"),label:er("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},k=[{id:Ui("standard"),label:er("Standard","Standard"),when:"true",output:{fields:[{path:nn("applicant.vorname")},{path:nn("applicant.nachname")}],includeForm:!0}}],g={sections:[y],effects:[],outcomes:k},v={};return{index:{module:"admission",tenant:r,label:n,slugs:{manifest:a,workflow:a},smartforms:{[l]:{}},...i?{links:{unitKey:i}}:{}},manifest:v,smartforms:{[l]:{label:n,...g}},workflow:{graph:u,progressLayout:f,progressWiring:m}}}s(a0,"buildSkeletonBundle");var Ko={same:"\xB7",create:"+",change:"~",absent:"\u2205"};async function It(e,t,n){let i=(await e.query(S.workflow.listManifests,{client:t})).find(o=>o.offerKey===n);if(!i)throw new Error(`offer: no offer "${n}" in tenant "${t}"`);return i}s(It,"findOfferHandle");function rn(e,t,n){return e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0})}s(rn,"loadConfig");function yv(e,t){let n=e.units.find(r=>r.key===t);if(!n)throw new Error(`offer: unit "${t}" not found. Available keys: ${e.units.map(r=>r.key??"(no key)").join(", ")||"(none)"}`);return n.unitId}s(yv,"resolveUnitId");function aa(e,t){let n=l0(e),r=e.runs.find(i=>i.key===ni(n,t));if(!r)throw new Error(`offer: run "${t}" not found. Available keys: ${e.runs.map(i=>_C(n,i.key)).join(", ")||"(none)"}`);return r.runId}s(aa,"resolveRunId");function la(e,t){let n=l0(e),r=e.stages.find(i=>i.key===sb(n,t));if(!r)throw new Error(`offer: level "${t}" not found. Available keys: ${e.stages.map(i=>Fr(n,i.key)).join(", ")||"(none)"}`);return r.stageId}s(la,"resolveStageId");function l0(e){if(e.programKey===null)throw new Error("offer: the offer has no program yet \u2014 link a unit first");return e.programKey}s(l0,"requireProgramKey");async function wv(e,t,n,r){await e.mutation(S.programAdmin.ensurePedagogyUnit,{client:t,unitId:r}),await e.mutation(S.programAdmin.createProgramForAngebot,{client:t,offerKey:n,unitId:r})}s(wv,"linkUnit");function jo(e,t){if(t===void 0)return;let n=Number(t);if(!Number.isInteger(n)||n<0)throw new Error(`offer: --${e} must be a non-negative integer`);return n}s(jo,"parsePositiveInt");var da=s((e="Offer slug (required)")=>p.String("--offer",{description:e}),"offerOption"),kv=s(()=>p.String("--slug",{hidden:!0}),"retiredSlugOption");function bv(e){if(e.retiredSlug!==void 0){if(e.offer!==void 0&&e.offer!==e.retiredSlug)throw new wt(`--offer "${e.offer}" and --slug "${e.retiredSlug}" name different offers \u2014 pass only --offer.`);return it(e.context.stderr,"--slug","--offer"),e.retiredSlug}if(e.offer===void 0)throw new wt("Missing --offer <slug>.");return e.offer}s(bv,"requireOffer");var Xe=class extends C{static{s(this,"OfferCommand")}offer=da();retiredSlug=kv();#e;get offerSlug(){return this.#e??=bv(this),this.#e}};var xd=class extends Xe{static{s(this,"OfferExportCommand")}static paths=[["offer","export"]];static usage=T.Usage({category:"Offer",description:"Pull an offer's published generation (manifest + smartforms + workflow + program) into a bundle; --draft pulls the draft"});offer=da("Manifest slug to export (required)");out=p.String("--out",{required:!0,description:"Output bundle directory (refused when not empty, unless --force)"});force=En();draft=p.Boolean("--draft",!1,{description:"Export the editable draft instead of the published generation (the live head, else the staged candidate)"});async execute(){let t=cw(this.out,this.force),n=await this.caller(),r=this.requireTenant(n),{bundle:i,generation:o,revision:a}=await NF(n,r,this.offerSlug,this.draft?"draft":"published");return An({...i,dir:t}),this.print({exported:`${r}/${this.offerSlug}`,generation:o,revision:a,dir:t},l=>[{key:"exported",value:l.exported},{key:"generation",value:`${l.generation} (revision ${l.revision})`},{key:"dir",value:l.dir}]),0}},Sd=class extends Se{static{s(this,"OfferInitCommand")}static paths=[["offer","init"]];static usage=T.Usage({category:"Offer",description:"Scaffold a complete, publishable, minimal linear offer bundle on disk"});offer=da("New offer slug (identity key) (required)");retiredSlug=kv();title=p.String("--title",{required:!0,description:"Bare offer title in German (= program/form label), e.g. 'Grundschule'. Do NOT include the run/year or levels \u2014 those are separate entities (program_runs.name / program_stages) shown alongside the offer, never composed into the label."});titleEn=p.String("--title-en",{required:!0,description:"The same title in English, e.g. 'Primary School' (every name a reader sees has both)"});tenant=p.String("--tenant",{required:!0,description:"Tenant slug (stamped on bundle.yaml)"});unit=p.String("--unit",{description:"Pedagogic unit (school) the portal resolves the offer through \u2014 its config key"});responsible=p.String("--responsible",{required:!0,description:"configKey of the staff member a self-service application goes to (the process slot\u2019s \u201Esonst\u201C row); a staff start goes to its creator"});template=p.String("--template","basic",{description:"Scaffold template (only 'basic')"});out=p.String("--out",{description:"Output directory (default: offers/<tenant>/<slug>; refused when not empty, unless --force)"});force=En();async execute(){let t=bv(this);if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let n=cw(this.out??G.join("offers",this.tenant,t),this.force),r=a0({slug:t,title:Vt({de:this.title,en:this.titleEn},"offer init",{de:"--title",en:"--title-en"}),tenant:this.tenant,responsible:this.responsible,template:"basic",...this.unit?{unit:this.unit}:{}});return An({...r,dir:n}),this.print({created:`${this.tenant}/${t}`,dir:n},i=>[{key:"created",value:i.created},{key:"dir",value:i.dir},{key:"next",value:`plexus offer validate --dir ${i.dir}`}]),0}},Ad=class extends Se{static{s(this,"OfferValidateCommand")}static paths=[["offer","validate"]];static usage=T.Usage({category:"Offer",description:"Run the publish-gate validators locally against a bundle (no deployment)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let t=Ke(this.dir),n=$n(t);return this.print(n,r=>r.length===0?[{severity:"ok",area:"-",message:"local validation clean"}]:r.map(i=>({severity:i.severity,area:i.area,message:i.message}))),n.some(r=>r.severity==="error")?1:0}},Ed=class extends C{static{s(this,"OfferPlanCommand")}static paths=[["offer","plan"]];static usage=T.Usage({category:"Offer",description:"Read-only: local validation (resolver pins stamped from the environment, as publish would) + remote\u2194local diff (create/change/same)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let t=Ke(this.dir),n=await this.caller(),{pins:r,stamps:i,issues:o}=await d0(n,t),a=await Jb(n,t);return this.print({validation:o,resolverPins:r,resolverStamps:i.rows,diff:a},()=>[...o.map(l=>({kind:`local:${l.severity}`,target:l.area,detail:l.message})),...r.map(l=>({kind:"=",target:l.target,detail:l.detail})),...i.rows.map(l=>({kind:"=",target:l.target,detail:l.detail})),{kind:Ko[a.manifest],target:"manifest",detail:a.manifest},...Object.entries(a.smartforms).map(([l,d])=>({kind:Ko[d],target:`smartform:${l}`,detail:d})),{kind:Ko[a.workflow],target:"workflow",detail:a.workflow},...c0(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...u0(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...f0(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...p0(a).map(l=>({kind:l.icon,target:l.target,detail:l.status}))]),o.some(l=>l.severity==="error")?1:0}},Td=class extends C{static{s(this,"OfferDiffCommand")}static paths=[["offer","diff"]];static usage=T.Usage({category:"Offer",description:"Read-only remote\u2194local drift (no local validation)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let t=Ke(this.dir),n=await this.caller(),r=await mv(n,t.index.tenant,t),i=await Jb(n,t);return this.print(i,()=>[...r.map(o=>({icon:"=",target:o.target,status:o.detail})),{icon:Ko[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([o,a])=>({icon:Ko[a],target:`smartform:${o}`,status:a})),{icon:Ko[i.workflow],target:"workflow",status:i.workflow},...c0(i),...u0(i),...f0(i),...p0(i)]),0}};async function d0(e,t){let n=await mv(e,t.index.tenant,t),r=await dv(e,t.index.tenant,t),i=await cv(e,t.index.tenant,t);return{pins:n,stamps:{...r,rows:[...r.rows,...i.rows]},issues:[...r.issues,...i.issues,...$n(t)]}}s(d0,"validateOnEnvironment");function c0(e){return e.addresses===null?[]:OF(e.addresses)}s(c0,"addressRows");function u0(e){let t={insert:"+",update:"~",archive:"-"};return e.stages.map(n=>({icon:t[n.op],target:`stage:${n.key}`,status:$p(n)}))}s(u0,"stageRows");function f0(e){return e.capacities.map(t=>({icon:"~",target:`cap:${t.run}\xD7${t.stageKey}`,status:Op(t)}))}s(f0,"capacityRows");function p0(e){if(e.publishPending===null)return[];let t=e.externalHeadRevision===null?"none":`v${e.externalHeadRevision}`;return[{icon:e.publishPending?"!":"=",target:"publish",status:e.publishPending?`pending (draft v${e.draftRevision} ahead of live ${t})`:`up to date (live ${t})`}]}s(p0,"publishPendingRows");var $d=class extends C{static{s(this,"OfferApplyCommand")}static paths=[["offer","apply"]];static usage=T.Usage({category:"Offer",description:"Idempotent create/update; with --publish, release the draft when it differs from what is live"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});publish=p.Boolean("--publish",!1,{description:"Release the draft when it says something the live generation does not"});stage=p.String("--stage","external",{description:"Publish stage: 'external' (default, goes live) or 'internal' (stage as the testable candidate only)"});async execute(){if(this.stage!=="internal"&&this.stage!=="external")throw new Error(`offer: --stage must be 'internal' or 'external' (got "${this.stage}")`);let t=Ke(this.dir),n=await this.caller(),{pins:r,stamps:i,issues:o}=await d0(n,t);for(let d of[...r,...i.rows])this.context.stderr.write(` = ${d.target}: ${d.detail}
@@ -10475,6 +10475,6 @@ ${n.length} unusable ${o}:
10475
10475
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
10476
10476
  `),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>
10477
10477
  `)}else this.context.stdout.write(`No unusable identities.
10478
- `);return n.length>0?1:0}},BA=class extends nr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=p.String({required:!0});async execute(){let n=await(await this.caller()).mutation(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 vK(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(vK,"requireOnOff");var xK=[EA,TA,$A,RA,IA,OA,PA,_A,NA,CA,Lc,DA,FA,LA,MA,qA,KA,jA,BA];function SK(e){return e.de??e.en??Object.values(e)[0]??""}s(SK,"titleDe");function Y5(e){return{id:e._id,kind:e.kind,status:e.status,title:SK(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(Y5,"row");var H5=["id","kind","status","title","assignee","group","outcome"],GA=class extends C{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=p.Boolean("--mine",!1,{description:"Only items assigned to me."});application=p.String("--application",{description:"Filter by application id."});group=p.String("--group",{description:"Filter by team (permission-group) id."});assignee=p.String("--assignee",{description:"Filter by assignee users._id."});openOnly=p.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(Y5),H5),0}},zA=class extends C{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=p.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.get,{client:n,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:SK(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}},WA=class extends C{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=p.String("--title",{required:!0,description:"Task title."});description=p.String("--description",{description:"Task description."});application=p.String("--application",{description:"Link to an application id."});group=p.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=p.String("--assignee",{description:"Assignee users._id."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},YA=class extends C{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=p.String({required:!0,name:"workItemId"});outcome=p.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.complete,{client:n,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},HA=class extends C{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=p.String({required:!0,name:"workItemId"});user=p.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.assign,{client:n,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},AK=[GA,zA,WA,YA,HA];var Mc=[...I$,...b_,...N_,...UN,...BN,...hC,...xC,...vC,...kK,...xK,...wK,...xq,...o_,...uC,...lK,...$$,...X$,...n_,...EC,...AC,...RC,...IC,...dC,...HN,...AK,...x0,...aM,...bq,...lM,...Jq,...iK,...Sq,..._q,...Dq,...aK,...fK,...G$];for(let e of Mc){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:JE(e.usage.category,t.join(" "))})}var EK="0.1.41";function TK(){return Mc.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=zE[eo(n)];return{path:n,effect:to(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(TK,"plexusCommandCatalog");import Vo from"node:path";function J5(e){let t=st()?.workspaceRoot??process.cwd(),n=Vo.resolve(t,e),r=Vo.relative(t,n);if(Vo.isAbsolute(e)||r===".."||r.startsWith(`..${Vo.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(J5,"workspacePath");function Q5(e){let{absolute:t,relative:n}=J5(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of vr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Vo.join(o,a.name);if(a.isDirectory()?i(l):r.push(Vo.relative(t,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=ye(t);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return lt(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return Ot(Vo.dirname(t),{recursive:!0}),lt(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Yo(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(Q5,"plexusWorkspace");function $K(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=Ua[n];if(!o||!Object.hasOwn(Ua,n))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(hg,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:hg[i.path],skillHash:Nu}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return Q5(i)},"executePlexusAgentTool")}s($K,"createPlexusAgentToolExecutor");var eh=$K({inspectCommand:IK,executeCommand:OK});function th(){let e=new Zo({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:EK});e.register(Ta.HelpCommand),e.register(Ta.VersionCommand);for(let n of Mc)e.register(n);async function t(n,r){let i;try{i=e.process(n,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return eQ(i,r.stderr??process.stderr),e.run(i,r)}return s(t,"run"),{process(n,r){return e.process(n,r)},run:t,async runExit(n,r){process.exitCode=await t(n,r)}}}s(th,"createPlexusCli");function eQ(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&Pa[n]===r&&it(t,n,r),n in Pa&&to(n)==="confirm"&&!_a(e)&&t.write(`plexus-cli: \`${Pa[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
10478
+ `);return n.length>0?1:0}},BA=class extends nr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=p.String({required:!0});async execute(){let n=await(await this.caller()).mutation(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 vK(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(vK,"requireOnOff");var xK=[EA,TA,$A,RA,IA,OA,PA,_A,NA,CA,Lc,DA,FA,LA,MA,qA,KA,jA,BA];function SK(e){return e.de??e.en??Object.values(e)[0]??""}s(SK,"titleDe");function Y5(e){return{id:e._id,kind:e.kind,status:e.status,title:SK(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(Y5,"row");var H5=["id","kind","status","title","assignee","group","outcome"],GA=class extends C{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=p.Boolean("--mine",!1,{description:"Only items assigned to me."});application=p.String("--application",{description:"Filter by application id."});group=p.String("--group",{description:"Filter by team (permission-group) id."});assignee=p.String("--assignee",{description:"Filter by assignee users._id."});openOnly=p.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(Y5),H5),0}},zA=class extends C{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=p.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(S.workItems.get,{client:n,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:SK(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}},WA=class extends C{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=p.String("--title",{required:!0,description:"Task title."});description=p.String("--description",{description:"Task description."});application=p.String("--application",{description:"Link to an application id."});group=p.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=p.String("--assignee",{description:"Assignee users._id."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},YA=class extends C{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=p.String({required:!0,name:"workItemId"});outcome=p.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.complete,{client:n,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},HA=class extends C{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=p.String({required:!0,name:"workItemId"});user=p.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(S.workItems.assign,{client:n,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},AK=[GA,zA,WA,YA,HA];var Mc=[...I$,...b_,...N_,...UN,...BN,...hC,...xC,...vC,...kK,...xK,...wK,...xq,...o_,...uC,...lK,...$$,...X$,...n_,...EC,...AC,...RC,...IC,...dC,...HN,...AK,...x0,...aM,...bq,...lM,...Jq,...iK,...Sq,..._q,...Dq,...aK,...fK,...G$];for(let e of Mc){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:JE(e.usage.category,t.join(" "))})}var EK="0.1.43";function TK(){return Mc.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=zE[eo(n)];return{path:n,effect:to(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(TK,"plexusCommandCatalog");import Vo from"node:path";function J5(e){let t=st()?.workspaceRoot??process.cwd(),n=Vo.resolve(t,e),r=Vo.relative(t,n);if(Vo.isAbsolute(e)||r===".."||r.startsWith(`..${Vo.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(J5,"workspacePath");function Q5(e){let{absolute:t,relative:n}=J5(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of vr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Vo.join(o,a.name);if(a.isDirectory()?i(l):r.push(Vo.relative(t,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=ye(t);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return lt(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return Ot(Vo.dirname(t),{recursive:!0}),lt(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Yo(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(Q5,"plexusWorkspace");function $K(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=Ua[n];if(!o||!Object.hasOwn(Ua,n))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(hg,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:hg[i.path],skillHash:Nu}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return Q5(i)},"executePlexusAgentTool")}s($K,"createPlexusAgentToolExecutor");var eh=$K({inspectCommand:IK,executeCommand:OK});function th(){let e=new Zo({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:EK});e.register(Ta.HelpCommand),e.register(Ta.VersionCommand);for(let n of Mc)e.register(n);async function t(n,r){let i;try{i=e.process(n,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return eQ(i,r.stderr??process.stderr),e.run(i,r)}return s(t,"run"),{process(n,r){return e.process(n,r)},run:t,async runExit(n,r){process.exitCode=await t(n,r)}}}s(th,"createPlexusCli");function eQ(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&Pa[n]===r&&it(t,n,r),n in Pa&&to(n)==="confirm"&&!_a(e)&&t.write(`plexus-cli: \`${Pa[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
10479
10479
  `)}s(eQ,"noteRetiredPath");function IK(e){let t=th().process(ya(e),{executePlexusAgentTool:eh}),n=t.path.join(" ");if(n.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=TK().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"?wp(Js(Qs),i.fn??"",i.kind):void 0,a=bu(n,{confirm:_a(t),callKind:o});return{...r,writes:a}}s(IK,"inspectPlexusCommand");async function OK(e,t){if(t)return ZA(t,()=>OK(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=th();if(st()){let l=IK(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(ya(e.argv),{executePlexusAgentTool:eh,stdin:X5.from(e.stdin===void 0?[]:[e.stdin]),stdout:new RK({write(l,d,c){n+=String(l),c()}}),stderr:new RK({write(l,d,c){r+=String(l),c()}})}),stdout:n,stderr:r}}s(OK,"executePlexusCommand");rE({source:tQ.join(import.meta.dirname,"skill")});th().runExit(ya(process.argv.slice(2)),{executePlexusAgentTool:eh});
10480
10480
  //# sourceMappingURL=cli.mjs.map