@smartkomm/plexus-cli 0.1.29 → 0.1.31

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
@@ -9758,7 +9758,7 @@ ${i.map(d=>` ${nd(d)}
9758
9758
  `),0}},iC=[Ik,Ok,Pk];var _k=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}},oC=[_k];function jk(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(jk,"ts");function aC(e){return e==null?"":`${Math.round((Date.now()-e)/6e4)}m`}s(aC,"ago");var sC=["queued","running","succeeded","failed","canceled"];function cY(e){let t=sC.find(n=>n===e);if(t===void 0)throw new Error(`jobs list: --status must be one of ${sC.join(" | ")}, got "${e}".`);return t}s(cY,"jobStatus");var Nk=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:xu(this.limit,100),r=await this.paginate(t,S.jobs.listPage,this.status?{status:cY(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:aC(a.updatedAt)})),["id","kind","status","tenant","phase","progress","tries","worker","updated"]),0}},Ck=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}},Dk=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:jk(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},Fk=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}},Lk=class extends C{static{s(this,"WorkersLogsCommand")}static paths=[["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:jk(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},Mk=class extends C{static{s(this,"WorkersReaperStatusCommand")}static paths=[["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:jk(n.ranAt)}),0)}},qk=class extends C{static{s(this,"WorkersReapCommand")}static paths=[["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}},Kk=class extends C{static{s(this,"ImportsCleanupOrphansCommand")}static paths=[["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:aC(o.updatedAt),action:i.confirmed?"failed":"would-fail"})),["id","tenant","importRunId","phase","updated","action"]),0}},lC=[Nk,Ck,Dk,Fk,Lk,Mk,qk,Kk];var uY=/^(\d+)([mhd])$/,fY={m:6e4,h:36e5,d:864e5};function wp(e,t=Date.now()){let n=e.trim(),r=uY.exec(n);if(r!==null)return t-Number(r[1])*fY[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(wp,"parseSince");function kp(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(kp,"ts");function Xk(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(!Jf(e))throw new Error(`notifications: --locale "${e}" is not a supported locale (${ze.join("|")})`);return e}s(Xk,"parseLocale");function pY(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(pY,"parseSlots");var Bk=class extends C{static{s(this,"NotificationsListCommand")}static paths=[["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:xu(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:wp(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:kp(o.createdAt),settled:kp(o.settledAt),smtp:o.lastSmtpResponse??""})),["id","template","status","tenant","to","files","tries","error","mode","dup","created","settled","smtp"]),0}};function mY(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(mY,"showView");var Uk=class extends C{static{s(this,"NotificationsShowCommand")}static paths=[["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(mY(n)),0}},Vk=class extends C{static{s(this,"NotificationsRetryCommand")}static paths=[["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}},Gk=class extends C{static{s(this,"NotificationsSweeperStatusCommand")}static paths=[["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:kp(n.ranAt),lastDeadAt:kp(n.lastDeadAt)}),0)}},zk=class extends C{static{s(this,"NotificationsSelfTestCommand")}static paths=[["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}},Wk=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}},Hk=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:Xk(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}
9759
9759
  Platzhalter: ${i||"\u2014"}
9760
9760
 
9761
- `)}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}},Yk=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=pY(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:Xk(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}},Jk=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:Xk(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}},od=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function bp(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":od(t[r],""),...n===null?{}:{platform:od(n[r],"")}}))}s(bp,"chromeTextRows");var Qk=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=>[...bp("greeting",r.greeting,r.defaults.greeting),...bp("closing",r.closing,r.defaults.closing),{field:"senderName",school:od(r.senderName,"\u2014 (platform)"),platform:od(r.defaults.senderName,"")}],["field","school","platform"]),0}},Zk=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=>[...bp("greeting",l.greeting,null),...bp("closing",l.closing,null),{field:"senderName",school:od(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},dC=[Bk,Uk,Vk,Gk,zk,Wk,Hk,Yk,Jk,Qk,Zk];var hY="-stufe-",gY=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function eb(e){return`${e}${hY}`}s(eb,"stageKeyPrefix");function tb(e,t){return`${eb(e)}${t}`}s(tb,"stageStorageKey");function uC(e,t){let n=eb(e);return t.startsWith(n)&&t.length>n.length}s(uC,"isUnderProgram");function Cr(e,t){let n=eb(e);return uC(e,t)||ce("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(Cr,"bareStageKey");function vp(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"||!gY.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(vp,"stageSpecIssues");function cC(e){return{de:e.de.trim(),en:e.en.trim()}}s(cC,"trimmedText");function yY(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(yY,"describeNameChange");function xp(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:cC(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:cC(a)},u=tb(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={};is(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:uC(e,a.key)?Cr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(xp,"planStageReconcile");function Sp(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(yY(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(Sp,"describeStageStep");var wY=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ei(e,t){return`${e}-${t}`}s(ei,"runStorageKey");function fC(e,t){typeof t!="string"&&ce("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)&&ce("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(fC,"bareRunKey");function Ap(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"||!wY.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(Ap,"runSpecIssues");var kY={capacity:null,isOpen:!1},bY={capacity:null,isOpen:!0};function vY(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(vY,"isCapacity");function Ep(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)||!vY(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(Ep,"capacitySpecIssues");function mC(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(Cr(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===ei(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?kY:bY;v.capacity===k.capacity&&v.isOpen===k.isOpen||d.push({run:c.key,stageKey:f,from:v,to:k})}}return d}s(mC,"planRunCapacities");function pC(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(pC,"describeCell");function Tp(e){return`~cap ${e.run}\xD7${e.stageKey} ${pC(e.from)} \u2192 ${pC(e.to)}`}s(Tp,"describeCapacityStep");function hC(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(hC,"assertBackendHasStageKeys");async function nb(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}));hC(i);let a=xp(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(nb,"planStages");async function $p(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});hC(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Cr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return mC(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===ei(d,c)))})}s($p,"planCapacities");async function xY(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===ei(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(xY,"assertNoArchivedRunKey");var rb={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...vp(o??[]),...Ap(n.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(g=>g.message.de).join("; ")}`);let l=Ep(n.program?.runs??[],o?.map(g=>g.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await xY(e,i,t,n);let d=await $p(e,i,t,n),c=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=SY(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})),m.push(`unit=${u}`),o!==void 0)if(r.dryRun){let g=await nb(e,i,t,o);m.push(...g.map(Sp))}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===ei(y.programKey,g.key));if(v!==void 0){is(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 $p(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(P=>P.key===ei(v,$.run))?.runId,A=g.stages.find(P=>Cr(v,P.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(Tp)),m.join(", ")}};function SY(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(SY,"bundleUnitKey");var gC={role:"control",effect:"pure",cardinality:"N-to-1"};var Rp=["add","remove","replace"];function yC(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(yC,"roleAssignLiteral");var wC={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=yC(e,"roleKey")?.trim()??"",o=yC(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"}),Rp.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 ${Rp.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${Rp.join(" | ")}.`},severity:"error"}),r},"validate")};var AY=["event","effect","outcomes"],ib=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),kC={outcomes:[{id:lr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of AY)i in r&&n.push(ib(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${lr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${lr}" itself.`));return Pn(t.nodes).some(i=>i.target===e.id)&&n.push(ib(`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?.[lr]===void 0&&n.push(ib(`nodes.${e.id}.next.${lr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${lr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${lr}" nowhere.`)),n},"validate")};var EY="submit",bC=[{id:EY,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function vC(e){return e==="draft"}s(vC,"isWritableSmartFormState");var ob=["draft","committed"],$xe=ob.filter(e=>vC(e));async function xC(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(xC,"getSmartFormInstance");var SC="form:fill",sb="request:collectPayment";var TY={key:SC,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},AC={key:"bearbeitung",label:ne("In Bearbeitung","In progress"),scope:"node"},EC={[$$]:{label:ne("In Bearbeitung","In progress"),tone:"neutral",phase:AC,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")},[Nu]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:AC,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."))}},TC={role:"user-action",effect:"side-effect",progressDefaults:EC,progressEvents:Pt(EC),actions:s(()=>bC,"actions"),workItemTemplates:s(()=>[TY],"workItemTemplates"),states:ob,currentState:s(async(e,t)=>{let n=await xC(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=>wn(e)?[]:[{id:Cu,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 $C={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:HR(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"&&tf(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 $Y="true",RY="false",ab=[{id:$Y,label:{de:"Ja",en:"Yes"}},{id:RY,label:{de:"Nein",en:"No"}}];var RC={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:ab,validate:s((e,t,n)=>IY(e,t,n),"validate")};function IY(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=ab.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=B$(t),a=Of(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 _y(e.condition,o)){let c=RO(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(IY,"ifNodeIssues");var sd="decision",OY=new Set(["decision","review"]),Xxe=new Set([...OY,"governedDocument"]);var OC=[{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 IC={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."))}},Fi={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:OC,progressDefaults:IC,progressEvents:Pt(IC),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,...bi(t.semantic)?{semantic:t.semantic}:{}})),...aP(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:sd,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===sd&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),validate:lb};function lb(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 ${yn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${d.id}" of "${e.id}" does not say what it means \u2014 one of ${yn.join(", ")}.`},severity:"error"}):bi(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: ${yn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${d.id}" of "${e.id}" has the meaning "${String(f)}" \u2014 allowed: ${yn.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(lb,"validateDecisionNode");var db=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],PC=[{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 Qn="processFooter";var cb="promoted";var _C="promote",NC="Nachr\xFCcken";var ub={key:"warteliste",label:ne("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},CC={waitlisted:{label:ne("Warteliste","Waitlisted"),tone:"amber",phase:ub,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:ub,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:ub,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."))}},DC={outcomes:db,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:zn.map(e=>({value:e,label:X$[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=Ig(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=Ig(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:CC,progressEvents:Pt(CC),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:db).some(n=>n.id===cb)?[{id:_C,kind:"advance",outcome:cb,semantic:"other",label:{de:NC,en:"Promote from waitlist"},surface:Qn,superUserOnly:!0}]:[],"actions")};var PY="complete",Ip="acceptedIncomplete",Op="rejected",_Y="absage",FC="closeWithoutDocuments",LC="rejectAtCompleteness",MC="Ohne Nachreichung abschlie\xDFen",qC="Ablehnen",KC="awaitingDocuments",fb="documentsComplete",pb="closedWithoutDocuments",mb="rejected",hb="withdrawn",jC="requested",xSe={[PY]:{event:fb,status:"complete",endsRole:!0},[Ip]:{event:pb,status:"acceptedIncomplete",endsRole:!1},[Op]:{event:mb,status:"rejected",endsRole:!0},[_Y]:{event:hb,status:"withdrawn",endsRole:!0}};var ad=s(()=>el[0],"beneficiary"),gb=366;function NY(e){let t=e.reads,n=tl(e).flatMap(({address:r})=>st(r)&&!el.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(st):[],...n]}s(NY,"printedFields");function CY(e,t){let n=se(t);return e.nodes.filter(r=>r.type==="governedDocument"&&NY(r).some(i=>se(i)===n))}s(CY,"documentsPrinting");function DY(e,t){if(!st(t)||t.path!==ad())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!wn(n)}s(DY,"isCreatedFormBeneficiary");function Gt(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Gt,"issue");var yb={key:"unterlagen",label:ne("Unterlagen nachreichen","Outstanding documents"),scope:"node"},BC={[KC]:{label:ne("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:yb,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."))},[fb]:{label:ne("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:yb,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."))},[pb]:{label:ne("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:yb,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."))},[mb]:{label:ne("Abgelehnt","Rejected"),tone:"red",phase:PI,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."))},[hb]:{label:ne("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:gf,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."))}},UC={outcomes:PC,progressDefaults:BC,progressEvents:Pt(BC),notificationEvents:s(()=>[{id:jC,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(Ip)&&n.push({id:FC,kind:"advance",outcome:Ip,semantic:"other",label:{de:MC,en:"Close without documents"},surface:Qn,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(Op)&&n.push({id:LC,kind:"advance",outcome:Op,semantic:"rejected",label:{de:qC,en:"Reject application"},surface:Qn,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),!st(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 P=Ir(n,R);if(P==null)continue;let L=Ii("requires",Ri(P));L==="computed"||L==="repeated"?r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(R)} ist ${P.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(R)} is ${P.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(R)} (\u201E${$i(P,"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)} ("${$i(P,"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||$>gb)&&r.push(Gt(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String($)}" ist keine ganze Zahl von 0 bis ${gb} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String($)}" is not a whole number from 0 to ${gb} days.`}))}else typeof u.until!="string"||wy(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<JI(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(st).map(R=>[se(R),R]));for(let R of $.values())for(let A of CY(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>.${en}.${ad()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${en}.${ad()}).`}))),be(v)&&!DY(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>.${en}.${ad()}).`,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>.${en}.${ad()}).`})),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 FY=[{id:tR,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],ld=s(e=>e,"asDecision"),VC={[nR]:{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."))}},GC={role:"user-action",effect:"side-effect",outcomes:FY,progressDefaults:VC,progressEvents:Pt(VC),notificationEvents:s(e=>Fi.notificationEvents(ld(e)),"notificationEvents"),actions:s(e=>[...Fi.actions(ld(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:_g,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Fi.optionalActionKinds,workItemTemplates:s(e=>Fi.workItemTemplates(ld(e)).map(t=>t.key===sd?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,_g]}:t),"workItemTemplates"),taskDocuments:s((e,t)=>Fi.taskDocuments(ld(e),t),"taskDocuments"),validate:s((e,t,n)=>{let r=lb(ld(e),t,n),i=Array.isArray(e.reads)?e.reads:[];for(let o of e.outcomes??[]){let a=o.semantic;typeof a!="string"||!Wu.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(!st(o))continue;let a=Ir(n,o);a==null||Ii("nodeReads",Ri(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 zC=["awaitingAnswer","answered"];async function WC(e,t){return(await hl(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(WC,"externalRequestState");var JC=[{id:vs,label:{de:"Bezahlt",en:"Paid"}}],iAe=new Set(JC.map(e=>e.id));var LY=vs,HC=[{id:LY,kind:"advance",outcome:vs,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],MY={id:ay,kind:"advance",outcome:vs,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:Qn,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"}}},qY={id:ay,kind:"advance",outcome:vs,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:Qn,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 wb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(wb,"literalOf");function Ys(e){let t=wb(e,Wn);return sf(t)?t:null}s(Ys,"settlementOrNull");function KY(e){let t=wb(e,Ei);return typeof t=="string"&&t.length>0?t:null}s(KY,"articleKeyOrNull");function jY(e){let t=wb(e,Hn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(jY,"payeeKeyOrNull");var BY={id:Ei,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},UY={id:Wn,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)"}}]},VY={id:Ti,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},GY={id:Hn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function zY(e){return[BY,UY,...Ys(e)==="online"?[GY]:[],VY]}s(zY,"collectPaymentInputs");var WY=["amount","currency","settlement"];function HY(e,t){if(Ys(e)!=="online")return[];let n=jY(e);if(n===null)return[];let r=`nodes.${e.id}.inputs.${Hn}`,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(HY,"payeeIssues");var YC={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."))}},QC={outputs:s(()=>[{name:MR,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>zY(e),"inputs"),outcomes:JC,progressDefaults:YC,progressEvents:Pt(YC),notificationEvents:s(e=>Ys(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=Ys(e);return t==="online"?[...HC,qY]:t==="separate"?[MY]:[]},"actions"),states:zC,currentState:s((e,t)=>WC(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:sb}),"currentState"),workItemTemplates:s(e=>{let t=e;return Ys(t)!=="online"?[]:[{key:sb,recipient:"external",title:t.label,unlocks:HC.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 WY)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(...HY(e,n)),Ys(e)===null&&i(`inputs.${Wn}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${bs.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[Wn])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${bs.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[Wn])}.`});let o=e.inputs?.[Ti];if(o?.kind==="literal"){let d=of(o.value);d!==null&&i(`inputs.${Ti}`,{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=KY(e);if(a===null)return i(`inputs.${Ei}`,{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.${Ei}`;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 ${ly.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${ly.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 Ln="traeger",ZC={de:"Tr\xE4ger",en:"Provider"};function Pp(e){let t=e.inputs?.[Ln];return t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0?t.value:null}s(Pp,"traegerKeyOfNode");var _p={name:"input.traeger.name",address:"input.traeger.anschrift"},aAe=Object.values(_p);var XC="governedDocument",To="prepareDocument",dd="prepareDocument:revision",Dr="releaseApproval",$o="documentResponse",Fr="responseCheck",Np="returnSigned";var eD="requestApproval";var tD="issueDocument",nD="correctInPlace",rD="rescindAndReissue",Cp="requestChange";var Js="releaseArtifact",dn="signingRecovery",Ro="resendESignature",Io="switchToPaper";var kb=new Set([To,dd]),iD=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],Dp=["upload","resolver","template","none"],Oo=1,Po=366,ti="responseDueInDays";function bb(e){let t=e.inputs?.[ti];return t?.kind==="literal"&&cd(t.value)?t.value:void 0}s(bb,"responseDueInDaysForVocabulary");function cd(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Oo&&e<=Po}s(cd,"isValidResponseDueInDays");var Fp=["generatedAt","responseDueInDays"],_o=["release","none"],Lp=["confirm","signedUpload","signedUploadChecked","eSignature"];function oD(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(oD,"localeFieldMissingText");var vb=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),sD=/^[a-z][a-z0-9_]*$/;function aD(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"||!sD.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(!Ai(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 (${ks.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 (${ks.join(", ")}).`}});continue}if(vb.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 ${[...vb].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a letter only prints ${[...vb].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!sD.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&&!Fp.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Fp.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Fp.join(", ")}.`}})}return n.push(...YY(e,t)),n}s(aD,"templateParameterIssues");function YY(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:oD(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(YY,"localeFieldIssues");function lD(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(lD,"applyTemplateStamp");var xb=50;async function Mp(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take(xb+1);return n.length>xb&&N(`signing_returns: Vorgang ${t} has more than ${xb} returns`),n}s(Mp,"returnsOf");var Sb=50;async function Ab(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(Sb+1);return n.length>Sb&&N(`signing_returns: return ${t} has more than ${Sb} files`),n.length===0&&N(`[signing/noDocument] return ${t} carries no file`),n}s(Ab,"returnDocumentsOf");async function dD(e,t){let n=await Ab(e,t);return n.length!==1&&N(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(dD,"soleReturnDocumentOf");var qp=200,RAe=qp*20;async function JY(e,t){let n=await e.db.get(t);return n===null&&N(`[process] application ${t} not found`),n.redactedAt!==void 0}s(JY,"processRedacted");async function Eb(e,t){await JY(e,t)&&ce("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(Eb,"assertProcessReadable");function QY(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(QY,"rowOf");async function cD(e,t,n){await Eb(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(qp+1);return r.length>qp&&N(`[process] application ${t} has more than ${qp} results of ${n.scope}.${n.owner}.${n.key}`),r.map(QY)}s(cD,"storeHistory");async function ZY(e,t,n){if(n.key===en){await Eb(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 cD(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(ZY,"nodeResultAt");async function Kp(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return XY(await ZY(e,t.applicationId,n),n,t.applicationId)}s(Kp,"readOwnResult");function XY(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(XY,"refOf");var Tb={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},eJ=Object.keys(Tb),tJ=eJ.filter(e=>Tb[e]==="open"),LAe=tJ.filter(e=>e!=="pending");function uD(e){return Tb[e]==="terminal"}s(uD,"isTerminalSigningStatus");var Li=["docusign","insign"];var ud={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var rJ=uD;function pD(e){return!rJ(e.status)&&e.voidRequestedAt===void 0}s(pD,"holdsContract");async function mD(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(mD,"traegerLegalEntityOfParty");async function iJ(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(iJ,"isOrganizationParty");async function hD(e,t){return await mD(e,t)!==null?"traeger":await iJ(e,t)?"organization":"person"}s(hD,"signerKindOf");async function gD(e,t){t.length===0&&N("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await oJ(e,n.partyId)==="family")return"family";return"traeger"}s(gD,"signingSideOf");async function oJ(e,t){return await hD(e,t)==="traeger"?"traeger":"family"}s(oJ,"sideOfParty");var gEe=16*1024;var yEe=15*6e4;var wEe=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()}))},DEe=Br({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 KEe=w.object($b);var Rb=200;async function aJ(e,t,n,r){t.length>Rb&&N(`${r} is carried by more than ${Rb} 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(aJ,"requestsOfMembers");async function yD(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(Rb+1);return await aJ(e,r,n,`revision ${t}`)}s(yD,"requestsOfSnapshot");var wD=100;async function lJ(e,t){let n=await yD(e,t);n.length>wD&&N(`requestsBySideOf: revision ${t} has more than ${wD} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await gD(e,i.signers)].push(i);return r}s(lJ,"requestsBySideOf");async function Ib(e,t){return(await lJ(e,t)).family}s(Ib,"familyRequestsOf");var Ob=100;async function dJ(e,t){let n=await e;return n.length>Ob&&N(`contractChain: more than ${Ob} ${t}`),n}s(dJ,"bounded");async function cJ(e,t,n){let r=await Kp(e,{applicationId:t,nodeId:n,key:hs});return r.state==="pending"?null:(r.ref.kind!=="contract"&&N(`contractChain: $node.${n}.${hs} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(cJ,"nodeContractRef");async function kD(e,t){return await dJ(e.db.query("contract_snapshots").withIndex("by_contractId_and_revisionNumber",n=>n.eq("contractId",t)).take(Ob+1),`revisions on contract ${t}`)}s(kD,"snapshotsAsc");async function Pb(e,t){let n=(await Ib(e,t)).filter(pD);return n.length>1&&N(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s(Pb,"openFamilyRequest");async function uJ(e,t){for(let n of await kD(e,t))if((await Ib(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(uJ,"familyRoute");async function bD(e,t){for(let n of t)if(await uJ(e,n)==="paper")return"paper";return"provider"}s(bD,"familyRouteOf");async function fJ(e,t){let n=await dD(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(fJ,"toReturn");function jp(e){async function t(a,l){return await cJ(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 kD(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 Pb(a,c._id);if(u===null)return null;let f=(await Mp(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 fJ(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(jp,"contractNodeReads");function Bp(e){return e.addedParts??[]}s(Bp,"addedPartsOf");var _b=50;async function pJ(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(_b+1);return n.length>_b&&N(`groupRunsOf: generation group ${t} has more than ${_b} runs`),n.length===0&&N(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(pJ,"groupRunsOf");async function vD(e,t){let n=await pJ(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),...Bp(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(vD,"groupRunsInOrder");function xD(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(xD,"isCompleteGroup");var Nb=200;function mJ(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(mJ,"groupPartKeys");async function hJ(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(Nb+1);return r.length>Nb&&N(`groupChain: more than ${Nb} generation runs on node ${n}`),r}s(hJ,"nodeRuns");async function gJ(e,t,n){let r=mJ(n),i=new Set;for(let a of await hJ(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 vD(e,a);if(!xD(l))continue;let d=await e.db.get(a);d===null&&N(`groupChain: generation group ${a} has no package run`);let c=new Set(Bp(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(gJ,"groupRevisionRows");async function Cb(e,t,n){let r=await Kp(e,{applicationId:t,nodeId:n,key:gs});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&N(`groupChain: $node.${n}.${gs} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(Cb,"nodeGroupContracts");async function yJ(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await Pb(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(yJ,"openGroupRequest");async function wJ(e,t){let n=[];for(let i of await Ab(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(wJ,"toGroupReturn");function SD(e){async function t(i,o,a,l){let d=(await gJ(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 yJ(i,l);if(d===null)return null;let c=(await Mp(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 wJ(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await Cb(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(SD,"groupNodeReads");var kJ={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"}}},AD={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"}}},ED={...AD,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},bJ={...ED,kind:"eSignature",issuesBy:"provider"},ni={confirm:kJ,signedUpload:AD,signedUploadChecked:ED,eSignature:bJ};function Mi(e){let t=e.responseStrategy;if(typeof t=="string"&&t in ni)return ni[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(Mi,"responseStrategyOf");function TD(e){if(e.type!==XC||e.production!=="resolver")return!1;let t=e.responseStrategy;return typeof t=="string"&&t in ni?ni[t].acceptEvent==="contractEvent":!1}s(TD,"isFamilySignedContractNode");function fd(e){return e.label}s(fd,"governedDocTitle");function Db(e){return e.approval==="release"?eD:tD}s(Db,"submitActionId");function $D(e,t,n){return{key:t,recipient:"internal",title:n,unlocks:[Db(e)],gatesNode:!0,advancesNode:!0}}s($D,"producerTemplate");function vJ(e){return e.titles?.respond??e.label}s(vJ,"responseTitle");var Qs={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Fb(e){let t=Mi(e),n=[];if(e.production!=="none"&&n.push($D(e,To,e.titles?.prepare??Qs),$D(e,dd,e.titles?.revise??Qs)),e.approval==="release"&&n.push({key:Dr,recipient:"internal",title:e.titles?.approve??Qs,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),n.push({key:$o,recipient:"external",title:vJ(e),unlocks:t.producesResponseArtifact?[t.checksReturn?Np:t.acceptOutcomeId,t.declineOutcomeId,Cp]:[t.acceptOutcomeId,t.declineOutcomeId],advancesNode:!0,...bb(e)!==void 0?{dueInDays:bb(e)}:{}}),t.checksReturn&&n.push({key:Fr,recipient:"internal",title:e.titles?.check??Qs,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),t.issuesBy==="provider"){let r=fd(e);n.push({key:dn,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Ro,Io],gatesNode:!1,advancesNode:!1})}return n}s(Fb,"governedDocIntrinsicTemplates");function xJ(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(xJ,"governedDocSlot");function Up(e){return xJ(e).key}s(Up,"governedDocSlotKey");function SJ(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(SJ,"toRevision");function AJ(e){let t=SJ(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(AJ,"toReturn");function RD(e){let t=Up(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;ce("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 AJ(c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(RD,"artifactNodeReads");function Vp(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(Vp,"documentChainKind");function ID(e){switch(Vp(e)){case"contract":return jp(e).reads;case"group":return SD(e).reads;case"artifact":return RD(e).reads}}s(ID,"documentReadsFor");var EJ={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function pd(e){let t=e.responseStrategy;return typeof t=="string"&&t in ni?ni[t].producesResponseArtifact:!1}s(pd,"returnsSignedCopy");function TJ(e){return pd(e)&&e.confirmContractTerms!==!1}s(TJ,"asksContractTerms");function OD(e){return TJ(e)?{title:e.contractTermsQuestionText??EJ,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(OD,"contractTermsConfirm");async function $J(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:Oy(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Fr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&N(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${Fr} row`),a}s($J,"rejectedReturnOfAsk");async function PD(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await $J(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(PD,"returnedCopyOfAsk");var Lb=new Set([...kb,Dr,$o,Fr,dn]),DD={id:Ft,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},FD={id:so,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function RJ(e){let t=[],n=[{slot:DD,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:FD,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=nl(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(RJ,"referenceInputIssues");var IJ={id:ti,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},OJ={id:Ln,type:"legalEntity",label:ZC,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function PJ(e,t){let n=`inputs.${Ln}`,r=e.inputs?.[Ln];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=Pp(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 (${_p.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 (${_p.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(PJ,"traegerIssues");function zp(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}}:(wi(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(zp,"generatorFields");function _J(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(_J,"deferredToCockpit");function NJ(e){return Ai(e.type)?e.type:void 0}s(NJ,"resolverSlotType");function CJ(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=fd(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(CJ,"issueConfirmation");function Re(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Re,"issue");function Gp(e){return Dp.includes(e.production)&&_o.includes(e.approval)&&Lp.includes(e.responseStrategy)}s(Gp,"hasValidModes");async function Mb(e,t){let n=await hl(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&&kb.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";let o=r.find(l=>l.templateKey===Dr);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===dn))return"signatureStalled";let a=r.find(l=>l.templateKey===$o);if(a!==void 0){if(Mi(t.node).issuesBy==="provider"){let d=Vp(t.node)==="group"?(await Cb(e,t.applicationId,t.node.id)).map(c=>c.contractId):[await jp(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 bD(e,d)==="provider")return"awaitingSignature"}return Mi(t.node).producesResponseArtifact?await PD(e,{chain:ID(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===Fr)?"responseInCheck":"done"}s(Mb,"governedDocCurrentState");function _D(e){return e.production!=="none"&&Vp(e)!=="artifact"}s(_D,"keepsDocumentInContractDomain");function DJ(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!be(r)||r.scope!=="env"||!sr(r.key))return[];let i=oo(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(DJ,"envCoverageIssues");function LD(e,t){let n=[];for(let r of zp(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...DJ(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"}:_J(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(LD,"fieldSourceIssues");function FJ(e){let t=ar(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=aD(e.templateStamp,t).map(({path:r,reason:i})=>Re(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...LD(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(FJ,"templateIssues");function LJ(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(LJ,"eSignatureAnchorIssues");function MJ(e,t){return t===void 0||t.sendable?[]:Mi(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(MJ,"eSignatureProviderIssues");var ND={key:"dokument",label:ne("Dokument","Document"),scope:"node"},CD={producing:{label:ne("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:ND,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:ND,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"))}},MD={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>To,"processHoldTemplate"),progressDefaults:CD,progressEvents:Pt(CD),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(!Gp(e))return[];let t=Mi(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:Db(e),kind:"internal",surface:Js,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...CJ(e)??{}}),n.push({id:nD,kind:"internal",surface:Js,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:rD,kind:"internal",surface:Js,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:Np,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:Cp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:Ro,kind:"internal",surface:Js,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Io,kind:"internal",surface:Js,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:iD,currentState:Mb,workItemTemplates:s(e=>{let t=e;return Gp(t)?Fb(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e;if(!Gp(n)||n.production==="none")return[];let r=Fb(n).find(i=>i.key===t);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:Up(n)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[DD,OJ]:[],...e.production==="template"?[FD]:[],IJ,...zp(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=NJ(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"&&vi(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:Za,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===$o||t===dd||t===Fr||t===dn){let n=t===$o?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===Fr?{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===dn?{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: ${To}${e.approval==="release"?`, ${Dr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${To}${e.approval==="release"?`, ${Dr}`:""}.`}}return t===Dr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Dr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Dr}" 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(_D(t.node))return!1;let n=await Mb(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&Mi(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=OD(t.node);if(n===null||_D(t.node))return null;let r=await Mb(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Gp(e))return r.push(Re(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${Dp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${_o.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Lp.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 {${Dp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${_o.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Lp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=ni[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(...LJ(e,n),...MJ(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.`})),pd(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??[])Lb.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 (${[...Lb].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${v.key}" on node "${e.id}" collides with an intrinsic template (${[...Lb].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...PJ(e,n)):e.inputs?.[Ln]!==void 0&&r.push(Re(e,`inputs.${Ln}`,{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(...RJ(e)),e.production==="resolver"){let v=zr(e);if(v!==null){let $=W$(v);for(let R of zp(e)){if(!Ai(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 (${ks.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 (${ks.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(...LD(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(...FJ(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?.[ti],g=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return g!==void 0&&!cd(g)&&r.push(Re(e,`inputs.${ti}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(g)} \u2014 erlaubt ist eine ganze Zahl von ${Oo} bis ${Po} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(g)} \u2014 a whole number from ${Oo} to ${Po} days is allowed.`})),g===void 0&&zp(e).some(v=>v.processSource==="responseDueInDays")&&r.push(Re(e,`inputs.${ti}`,{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 Wp="countersign",qb="countersign",qD="countersigned",KD="countersigning",jD="countersigned",BD={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},md=["scan","eSignature"],Hp="service_provider:1",UD=["countersigning","awaitingSignature","signatureStalled","done"],VD={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function GD(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(GD,"traegerSignatoryMissingReason");function Zn(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Zn,"issue");function HD(e,t){return e.nodes.filter(n=>{let r=n.contract;return n.type==="countersign"&&be(r)&&r.scope==="node"&&r.owner===t})}s(HD,"countersignersOf");function hd(e){return e.signing==="eSignature"}s(hd,"isElectronic");function qJ(e,t){if(t===void 0||t.sendable||!hd(e))return[];let n=e.label?.de??e.id,r=e.label?.en||e.id;return[Zn(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(qJ,"countersignProviderIssues");function KJ(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 TD(r)||i.push("sourceNotCheckedContract"),HD(e,r.id).some(o=>o.id!==t)&&i.push("twice"),i}s(KJ,"countersignContractRefusals");function zD(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(zD,"validDueInDays");function jJ(e,t,n){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!md.includes(o))return[Zn(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?.[dn];if(!hd(e))return a===void 0?[]:[Zn(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(Zn(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(...BJ(e,t,n),...UJ(e,t,n),...qJ(e,n?.signingProvider)),l}s(jJ,"signingIssues");function YD(e,t){let n=e.contract;if(!(!be(n)||n.scope!=="node"))return t.nodes.find(r=>r.id===n.owner)}s(YD,"contractNodeOf");function BJ(e,t,n){let r=YD(e,t),i=r===void 0?null:Pp(r),o=i===null?void 0:n?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[Zn(e,"signing",GD(o.name))]}s(BJ,"traegerSignatoryIssues");function UJ(e,t,n){let r=YD(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(Zn(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(Hp)||l.push(Zn(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Hp}/ \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:${Hp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(UJ,"traegerAnchorIssues");var Kb=100;async function VJ(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(Kb+1);n.length>Kb&&N(`countersign node "${t.node.id}" of ${t.applicationId} holds more than ${Kb} 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)===dn)?"signatureStalled":r.some(o=>i(o)===Wp)?"countersigning":hd(t.node)?"awaitingSignature":"done"}s(VJ,"countersignCurrentState");var WD={[KD]:{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."))}},JD={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:qD,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:WD,progressEvents:Pt(WD),notificationEvents:s(()=>[{id:jD,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:qb,kind:"internal",label:BD,surface:Qn,availableIn:["countersigning"]},...hd(e)?[{id:Ro,kind:"internal",surface:Qn,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Io,kind:"internal",surface:Qn,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Wp,recipient:"internal",title:e.titles?.countersign??Qs,unlocks:[qb],advancesNode:!0,...zD(e)!==void 0?{dueInDays:zD(e)}:{}},...hd(e)?[{key:dn,recipient:"internal",title:VD,unlocks:[Ro,Io],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:UD,currentState:VJ,validate:s((e,t,n)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[Wp];(typeof a!="string"||a.length===0)&&r.push(Zn(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.`})),wi(e.titles?.countersign)||r.push(Zn(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(Zn(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(...jJ(e,t,n));let d=e.contract;if(!be(d))return r;let c=KJ(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(Zn(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=HD(t,u.id).filter(m=>m.id!==e.id);r.push(Zn(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 QD={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 Mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Mn,"isRecord");var jb=["field","join","literal","address","payment","contract"],GJ=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),zJ=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function Xn(e){return typeof e=="string"&&e.trim().length>0}s(Xn,"nonEmptyString");function Yp(e,t,n,r,i="value"){if(!Mn(e)||!Mn(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=jb.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${jb.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${jb.join(" | ")}).`}});return}let[l]=a;l==="field"&&!Xn(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(Xn))&&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)||Xn(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"&&sr(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&&!GJ.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&&!(Xn(e.lookup)&&Mn(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"||Mn(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Mn(d)&&zJ.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(Yp,"checkMapping");function qi(e,t,n,r,i){if(!Mn(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=QD[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))Yp(l,`${t}.${a}`,r,i)}s(qi,"checkBody");function ZD(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(!Mn(o)||!Xn(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),Yp(o.value,`${l}.value`,n,r),o.unless!==void 0&&Yp(o.unless,`${l}.unless`,n,r,"condition")})}s(ZD,"checkAif");function Bb(e){let t=[];if(!Mn(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=Mn(e.lookups)?e.lookups:{};Mn(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))(!Mn(i)||!Object.values(i).every(Xn))&&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(Xn(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),qi(e.pupil,"engage.pupil","addPupil",n,t),qi(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&qi(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&qi(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&qi(e.medical,"engage.medical","addMedical",n,t),ZD(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(!Mn(i)||!Xn(i.key)||!Xn(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),qi(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&qi(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)=>qi(u,`${a}.${l}[${f}]`,d,n,t))}}ZD(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&Yp(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Mn(r)||!Xn(r.repeated)||!Xn(r.field)||!Xn(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(Bb,"engagePushConfigIssues");function*Ub(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(Ub,"mappingsOf");function XD(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of Ub(e))for(let i of WJ(n.from))t.add(HJ(i,r));return[...t]}s(XD,"configFieldKeys");function WJ(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(WJ,"formFieldsOf");function HJ(e,t){return e.startsWith(".")?(t===void 0&&N(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(HJ,"resolveFieldKey");function eF(e,t){for(let{mapping:n}of Ub(e))if(t in n.from)return!0;return!1}s(eF,"configReadsSource");function tF(e){let t=new Set;for(let{mapping:n}of Ub(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(tF,"configEnvLeaves");var nF="done",rF=["sandbox","production"];var Jp="engagePush",G$e=660*1e3;function Ki(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(Ki,"issue");function Vb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Vb,"literal");function iF(e){return Bb(e.engage).length===0?e.engage:null}s(iF,"validConfig");function YJ(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(YJ,"bypassingPath");var oF={role:"system-action",effect:"side-effect",outcomes:[{id:nF,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=iF(e);return t===null?[]:tF(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=Vb(e,"target");rF.includes(a)||o.push(Ki(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=Vb(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(Ki(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?.[Jp];(typeof d!="string"||d.length===0)&&o.push(Ki(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${Jp}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${Jp}\` names the team.`}));for(let g of Bb(e.engage))o.push(Ki(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"&&Vb(g,"target")===a);c.length>0&&o.push(Ki(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.`})),YJ(t,e.id)&&o.push(Ki(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=iF(e),f=e;for(let[g,v,$,R]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!eF(u,g)||f[v]!==void 0||o.push(Ki(e,v,{de:Ss("address/missing",{where:`\u201E${r}\u201C \u203A ${$}`},"de"),en:Ss("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=XD(u).filter($=>!g.has($)&&!/\[\d+\]\./.test($));if(v.length>0){let $=t.nodes.find(R=>R.id===y);o.push(Ki(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 No={join:gC,end:NI,roleAssign:wC,eventTrigger:kC,waitlist:DC,completenessCheck:UC,form:TC,setFlag:$C,if:RC,decision:Fi,review:GC,collectPayment:QC,governedDocument:MD,countersign:JD,engagePush:oF};NR(No);function sF(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(sF,"graphOf");function aF(e){let t=new Map;for(let n of e.nodes)for(let r of $r(e,n))t.set(se(r.address),r.nodeId);return t}s(aF,"producedOf");function lF(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(po(e,n).map(r=>se(r.address))));return t}s(lF,"readsOf");function dF(e,t){let n=sF(e,"bundle"),r=sF(t.graph,"live head"),i=aF(n),o=aF(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=lF(n),d=lF(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(dF,"planAddresses");function cF(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(cF,"addressPlanRows");function uF(e,t){return t==null?!0:Pe(e)!==Pe(t)}s(uF,"changed");async function fF(e,t,n){if(t.index.module!==rb.name)throw new Error(`offer: unknown module "${t.index.module}"`);return VP(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return rb.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(fF,"applyOffer");async function pF(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(pF,"exportOffer");async function Gb(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?uF(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=uF(k&&{graph:ls(t.workflow.graph),progressLayout:t.workflow.progressLayout??k.progressLayout,progressWiring:t.workflow.progressWiring??k.progressWiring},k&&{graph:ls(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=dF(t.workflow.graph,y))}}let c=n.program?.stages,u=c===void 0?[]:i?await nb(e,n.tenant,n.slugs.manifest,c):xp(null,[],c),f=await $p(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(Gb,"diffOffer");function Qp(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(Qp,"contractProductionModeOf");function mF(e){return Qp(e)==="resolver"}s(mF,"isResolverCarrierNode");function Zp(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=zr(n);return!mF(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(Zp,"authoredPins");var hF={type:"address",dataType:"composite"};var gF={type:"boolean",dataType:"boolean"};var yF={type:"date",dataType:"date"};var wF={type:"docRef",dataType:"file"};var kF={type:"email",dataType:"text"};var bF={type:"enum",dataType:"option"};var vF={type:"string",dataType:"text"};var xF={type:"tel",dataType:"text"};var JJ={address:hF.dataType,boolean:gF.dataType,date:yF.dataType,docRef:wF.dataType,email:kF.dataType,enum:bF.dataType,string:vF.dataType,tel:xF.dataType};function zb(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(zb,"shapeOf");function SF(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,zb(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,zb(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}`,zb(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(SF,"fieldMapScopes");function QJ(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(QJ,"computedKeysOf");function AF(e){let t=[],n=QJ(e);for(let r of SF(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(AF,"validateFieldMapSources");function EF(e){let t=[],n=new Set;for(let o of SF(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(EF,"validateFieldPersistence");var ZJ="$";function XJ(e){return typeof e=="string"&&e.startsWith(ZJ)}s(XJ,"isRef");function Xp(e){return e.slice(1)}s(Xp,"stripRef");function*e4(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(e4,"refSlots");function t4(e){let t=new Set;for(let n of e4(e))XJ(n)&&t.add(Xp(n));return[...t]}s(t4,"collectRefs");function n4(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 t4(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=Xp(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&Xp(l.target)===a||l.kind==="shareValue"&&Xp(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(n4,"buildAdjacency");function TF(e){let{refsOf:t}=n4(e),r=_f(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(TF,"detectCycle");function $F(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s($F,"escapeRegExp");function ji(e){return new RegExp(`^${$F(e)}\\[(\\d+)\\]\\.(.+)$`)}s(ji,"repeatedRowKeyPattern");function Wb(e,t){let n=ji(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(Wb,"countRepeatedRows");function RF(e,t,n){let r=ji(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(RF,"repeatedRowHasData");function IF(e){return e.endsWith(".count")?e.slice(0,-6):e}s(IF,"readKeyOf");function Hb(e){return{sections:e,fields:[]}}s(Hb,"hiddenSectionsOnly");function OF(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??[])OF(r,t,n)}s(OF,"collectKeys");function PF(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;OF(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(ji)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(PF,"restrictedSectionsOf");function _F(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(_F,"matchesKey");function r4(e,t){return t.find(n=>_F(e,n))??null}s(r4,"hiddenSectionOfKey");function i4(e,t){for(let n=e;;){if(_F(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(i4,"fieldOwnsKey");function o4(e,t){return t.find(n=>i4(e,n))??null}s(o4,"restrictedFieldOfKey");function s4(e,t){let n=r4(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=o4(e,t.fields);return r===null?null:{kind:"field",field:r}}s(s4,"hiddenOwnerOfKey");function em(e,t){return s4(e,t)!==null}s(em,"isKeyHidden");function a4(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(a4,"visibleToListIssues");function NF(e,t,n){let r=[],i=s((c,u,f)=>{let m=c.visibleTo;m!==void 0&&r.push(...a4(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=PF(e);if(o.length===0)return r;let a=s((c,u,f)=>{if(c===void 0)return;let m=Hb(f);for(let y of kt(c)){let k=IF(y);(em(y,m)||em(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&&em(c.sameAs.source,Hb(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(NF,"sectionVisibilityIssues");var Lr="#";var CF=s(e=>{let t=kw.find(n=>n.systemColumn===e);return t===void 0&&N(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),fr={firstName:CF("persons.firstName"),lastName:CF("persons.lastName")};function DF(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===fr.firstName?n.firstName.push(o):a===fr.lastName&&n.lastName.push(o);return n}s(DF,"personNameKeys");function FF(e){return[...e.firstName,...e.lastName]}s(FF,"personNameKeyList");function LF(e){return e.firstName.length>0||e.lastName.length>0}s(LF,"hasPersonName");function Zs(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 Zs(i.subsections??[],a,i.id))r.push(l)}),r}s(Zs,"walkSections");function l4(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(l4,"findFieldInSection");function MF(e,t){for(let n of Zs(e.sections)){let r=l4(n.section,t);if(r)return{section:n.section,field:r}}return null}s(MF,"findField");var d4=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],c4=["blue","rose","amber","violet","teal","emerald","slate"];function qF(e){return d4.includes(e)}s(qF,"isBucketIconName");function KF(e){return c4.includes(e)}s(KF,"isBucketColorName");var u4="__clear__";function jF(e){return e===""?"empty":e===u4?"reserved":null}s(jF,"selectOptionValueDefect");var jIe=Object.freeze({});function f4(e,t){return Object.freeze($f(Vr,e,t))}s(f4,"formContextEntries");function BF(e){return e.env??[]}s(BF,"declaredContextKeys");function UF(e,t){return BF(e).every(n=>VF(n,t?.[n]))}s(UF,"scenarioContextComplete");function VF(e,t){return pO(Vr,e,t)}s(VF,"contextValueComplete");function GF(e,t){return f4(t??{},BF(e))}s(GF,"scenarioContextEntries");function Jb(e){return wl(e)}s(Jb,"isContextIdentifier");function p4(e,t,n){let r=Tf(Vr,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(p4,"contextIdentifierIssue");var Yb=qu("stage.key");function m4(e){let t=[],n=s(i=>i.kind==="ident"&&i.path===Yb,"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(m4,"stageKeyLiterals");function zF(e,t,n){return t===void 0?[]:m4(e).filter(r=>!t.has(r)).map(r=>HF(r,t,n))}s(zF,"stageKeyAstIssues");function WF(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(HF(i.key,t,`scenario:${r.id}/env`))}return n}s(WF,"scenarioStageKeyIssues");function HF(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.")+` \`${Yb}\` 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.")+` \`${Yb}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(HF,"unknownStageKeyIssue");function YF(e,t,n){let r=[];for(let i of kt(e)){if(!Jb(i))continue;let o=p4(i,t,n);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Ny(e,Lu))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(YF,"contextAstIssues");function JF(e,t){let n=[...h4(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!as(i)){n.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${ss.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${ss.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=>as(a)&&!VF(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??{}))as(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(JF,"formContextIssues");function h4(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(h4,"retiredContextFields");var Qb=N_.docRef.allowedMime;function tL(e,t={}){let n=Fs(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(O,I){if(i.has(O))return;i.add(O);let B=o.get(O.id);B&&B!==O?r.push({severity:"error",path:`sections[${I.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${O.id}' ist mehrfach deklariert.`,en:`Section id '${O.id}' is declared more than once.`}}):o.set(O.id,O);let D=`sections[${I.join(".")}]`;O.fields.forEach((Z,le)=>{Xs(a,Z.key,`${D}.fields[${le}]`,"duplicate.field-key",r),l.add(Z.key),u.set(Z.key,Z),c.set(Z.key,Xb(Z)),Z.externalFlag&&(Z.type!=="boolean"&&r.push({severity:"error",path:`${D}.fields[${le}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${Z.key}' muss den Typ 'boolean' haben (ist '${Z.type}').`,en:`External flag '${Z.key}' must be type 'boolean' (got '${Z.type}').`}}),Z.notice!==void 0&&r.push({severity:"error",path:`${D}.fields[${le}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${Z.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${Z.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),Z.defaultValue==null&&r.push({severity:"error",path:`${D}.fields[${le}]`,code:"flag.missing-default",message:{de:`Externes Flag '${Z.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${Z.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...QF(Z,`${D}.fields[${le}]`))}),O.groups?.forEach((Z,le)=>{Z.fields.forEach((ue,xe)=>{Xs(a,ue.key,`${D}.groups[${le}].fields[${xe}]`,"duplicate.field-key",r),l.add(ue.key),u.set(ue.key,ue),c.set(ue.key,Xb(ue)),ue.externalFlag&&r.push({severity:"error",path:`${D}.groups[${le}].fields[${xe}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ue.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${ue.key}' must be a direct section field, not a group field.`}}),r.push(...QF(ue,`${D}.groups[${le}].fields[${xe}]`))})}),O.repeated?.forEach((Z,le)=>{Z.itemTemplate.forEach((ue,xe)=>{Xs(a,ue.key,`${D}.repeated[${le}].itemTemplate[${xe}]`,"duplicate.field-key",r),c.set(ue.key,Xb(ue)),ue.externalFlag&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ue.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${ue.key}' must be a direct section field, not a repeated item field.`}}),ue.export&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"export.in-repeated",message:{de:`Feld '${ue.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${ue.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),ue.sameAs&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${ue.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${ue.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),ue.notice!==void 0&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"config.notice-in-repeated",message:{de:`Feld '${ue.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 '${ue.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),ue.type==="docRef"&&ue.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${ue.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${ue.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),O.computed?.forEach(Z=>{d.add(Z.key),Xs(a,Z.key,`${D}.computed[${Z.key}]`,"duplicate.field-key",r),Z.export===!0&&Z.exportType===void 0&&r.push({severity:"error",path:`${D}.computed[${Z.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${Z.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${Z.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),O.subsections?.forEach((Z,le)=>f(Z,[...I,le]))}s(f,"visitRawSection"),e.sections.forEach((O,I)=>f(O,[I]));let m=new Set;n.effects.forEach((O,I)=>{Xs(m,O.id,`effects[${I}]`,"duplicate.effect-id",r)});let y=new Set;n.outcomes.forEach((O,I)=>{Xs(y,O.id,`outcomes[${I}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((O,I)=>{O.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 '${O.id}' verweist auf den unbekannten Effekt '${B.effect}'.`,en:`Outcome '${O.id}' references unknown effect '${B.effect}'.`}})})}),n.outcomes.forEach((O,I)=>{O.output.fields?.forEach((B,D)=>{MF(n,B.path)||r.push({severity:"error",path:`outcomes[${I}].output.fields[${D}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${O.id}' verweist auf das unbekannte Feld '${B.path}'.`,en:`Outcome '${O.id}' references unknown field '${B.path}'.`}})})});let k=new Set;for(let O of Zs(n.sections))for(let I of O.section.repeated??[])k.add(`${I.key}.count`);for(let O of k)(a.has(O)||d.has(O))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${O}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${O}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let g={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...JF(e)),r.push(...NF(e,n,t.visibleToKeys)),r.push(...WF(e,t.stageKeys));for(let O of Zs(n.sections)){let I=O.section,B=`sections[${O.path.join(".")}]`;I.visibleIf&&(pr(I.visibleIf,`${B}.visibleIf`,g,!1,r),ea(I.visibleIf,`${B}.visibleIf`,c,r)),I.fields.forEach((D,Z)=>Zb(D,`${B}.fields[${Z}]`,g,!1,c,r)),I.groups?.forEach((D,Z)=>{D.visibleIf&&(pr(D.visibleIf,`${B}.groups[${Z}].visibleIf`,g,!1,r),ea(D.visibleIf,`${B}.groups[${Z}].visibleIf`,c,r)),D.fields.forEach((le,ue)=>Zb(le,`${B}.groups[${Z}].fields[${ue}]`,g,!1,c,r))}),I.repeated?.forEach((D,Z)=>{D.itemVisibleIf&&(pr(D.itemVisibleIf,`${B}.repeated[${Z}].itemVisibleIf`,g,!0,r),ea(D.itemVisibleIf,`${B}.repeated[${Z}].itemVisibleIf`,c,r)),D.itemTemplate.forEach((le,ue)=>Zb(le,`${B}.repeated[${Z}].itemTemplate[${ue}]`,g,!0,c,r)),D.effects?.forEach((le,ue)=>{le.when&&pr(le.when,`${B}.repeated[${Z}].effects[${ue}].when`,g,!0,r)})}),I.computed?.forEach((D,Z)=>pr(D.expression,`${B}.computed[${Z}].expression`,g,!1,r))}n.effects.forEach((O,I)=>{O.when&&pr(O.when,`effects[${I}].when`,g,!1,r)}),n.outcomes.forEach((O,I)=>{pr(O.when,`outcomes[${I}].when`,g,!1,r)});let v=new Set(n.outcomes.map(O=>O.id));function $(O,I){O.requiredFor&&O.requiredFor.forEach((B,D)=>{v.has(B)||r.push({severity:"error",path:`${I}.requiredFor[${D}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${O.key}": requiredFor verweist auf das unbekannte Ergebnis "${B}"`,en:`field "${O.key}": requiredFor references unknown outcome "${B}"`}})})}s($,"checkRequiredFor");for(let O of Zs(n.sections)){let I=O.section,B=`sections[${O.path.join(".")}]`;I.fields.forEach((D,Z)=>$(D,`${B}.fields[${Z}]`)),I.groups?.forEach((D,Z)=>{D.fields.forEach((le,ue)=>$(le,`${B}.groups[${Z}].fields[${ue}]`))}),I.repeated?.forEach((D,Z)=>{D.itemTemplate.forEach((le,ue)=>$(le,`${B}.repeated[${Z}].itemTemplate[${ue}]`))})}function R(O,I){let B=s((D,Z)=>{let le=(D.type==="docRef"?D.docRefConstraints?.mimeType??[]:[]).filter(xe=>!Qb.includes(xe));le.length>0&&r.push({severity:"error",path:Z,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${D.key}' erlaubt ${le.map(xe=>`'${xe}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${Qb.join(", ")}).`,en:`Field '${D.key}' allows ${le.map(xe=>`'${xe}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${Qb.join(", ")}).`}}),D.multiple===!0&&D.type!=="enum"&&r.push({severity:"error",path:Z,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:Z,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:Z,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:Z,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 ue=D.enumRef;ue!==void 0&&r.push({severity:"error",path:`${Z}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${D.key}' nennt den entfernten Options-Katalog (enumRef '${String(ue)}'). 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(ue)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(D.enumOptions??[]).forEach((xe,Ge)=>{let ft=jF(xe);ft!==null&&r.push({severity:"error",path:`${Z}.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:`${Z}.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!=="",it=xe.url!==void 0&&xe.url!=="";ft===it&&r.push({severity:"error",path:`${Z}.attachments[${Ge}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${D.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${ft&&it?"beide":"keines"}).`,en:`Field '${D.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${ft&&it?"both":"neither"}).`}}),xe.renderAs==="inlineLink"&&xe.label===void 0&&r.push({severity:"error",path:`${Z}.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");O.fields.forEach((D,Z)=>B(D,`${I}.fields[${Z}]`)),O.groups?.forEach((D,Z)=>{D.fields.forEach((le,ue)=>B(le,`${I}.groups[${Z}].fields[${ue}]`))}),O.repeated?.forEach((D,Z)=>{D.itemTemplate.forEach((le,ue)=>B(le,`${I}.repeated[${Z}].itemTemplate[${ue}]`))}),O.subsections?.forEach((D,Z)=>R(D,`${I}.subsections[${Z}]`))}s(R,"visitFieldConfig"),e.sections.forEach((O,I)=>R(O,`sections[${I}]`)),e.effects.forEach((O,I)=>{if(O.kind==="person"){r.push(...eL(O,e.effects,`effects[${I}]`,B=>l.has(B)));return}O.kind==="organization"&&O.nameFrom?.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nameFrom[${D}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${O.id}': nameFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${O.id}' nameFrom references unknown field '${B}'.`}})})});let A=s((O,I)=>{if(O.kind!=="person"&&O.kind!=="organization")return;let B=O.display;if(!B){r.push({severity:"error",path:`${I}.display`,code:"display.missing",message:{de:`Effekt '${O.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${O.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}qF(B.icon)||r.push({severity:"error",path:`${I}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${O.id}': display.icon '${B.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${O.id}' display.icon '${B.icon}' is not a known bucket icon.`}}),KF(B.color)||r.push({severity:"error",path:`${I}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${O.id}': display.color '${B.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${O.id}' display.color '${B.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((O,I)=>A(O,`effects[${I}]`));let P=new Set,L=s(O=>{O.kind==="person"?P.add(O.bucket):O.kind==="organization"&&P.add(O.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(L);let b=new Set,E=s(O=>{for(let I of O)I.repeated?.forEach(B=>B.effects?.forEach(D=>L(D))),E(I.subsections??[])},"collectRepeatedBuckets");E(e.sections);let q=s((O,I)=>{P.size!==0&&O.forEach((B,D)=>{B.bucket===void 0||P.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((O,I)=>{if(b.has(O))return;b.add(O);let B=`sections[${I.join(".")}]`;q(O.fields,`${B}.fields`),O.groups?.forEach((D,Z)=>q(D.fields,`${B}.groups[${Z}].fields`)),O.repeated?.forEach((D,Z)=>q(D.itemTemplate,`${B}.repeated[${Z}].itemTemplate`)),O.subsections?.forEach((D,Z)=>_(D,[...I,Z]))},"visitBucketSection");e.sections.forEach((O,I)=>_(O,[I]));let Y=e.effects.flatMap((O,I)=>O.kind==="person"&&O.subject===!0?[{e:O,i:I}]:[]);Y.length>1&&Y.slice(1).forEach(({e:O,i:I})=>{r.push({severity:"error",path:`effects[${I}].subject`,code:"subject.duplicate",message:{de:`Effekt '${O.id}' deklariert subject:true, aber '${Y[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${O.id}' declares subject:true, but '${Y[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((O,I)=>{if(!(O.kind!=="person"||O.nationalityFrom===void 0)){if(O.subject!==!0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${O.id}' deklariert nationalityFrom, ist aber nicht das Subjekt der Bewerbung \u2014 die Staatsangeh\xF6rigkeit wird nur f\xFCr das Subjekt der Bewerbung gelesen.`,en:`Effect '${O.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(O.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${O.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${O.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}O.nationalityFrom.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nationalityFrom[${D}]`,code:"nationality.unknown-field",message:{de:`Effekt '${O.id}': nationalityFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${O.id}' nationalityFrom references unknown field '${B}'.`}})})}});let H=e.effects.flatMap((O,I)=>O.kind==="person"&&O.contractParty!==void 0?[{e:O,i:I,decl:O.contractParty}]:[]);if(H.length>0){let O=H.filter(({decl:I})=>I.role==="beneficiary");O.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 '${O[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${I.id}' declares contractParty.role 'beneficiary', but '${O[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),O.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}'.`}})}),Y.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.`}})}),H.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((O,I)=>{O.kind==="fieldMap"&&O.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 '${O.id}': fieldMap from '${B.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${O.id}' fieldMap from '${B.from}' references unknown field.`}})})});for(let[O,I]of u){if(!I.sameAs)continue;let B=`fields[${O}].sameAs`,D=u.get(I.sameAs.source);D===void 0||I.sameAs.source===O?r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:I.sameAs.source===O?`Feld '${O}': sameAs.source verweist auf sich selbst.`:`Feld '${O}': sameAs.source verweist auf das unbekannte Feld '${I.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:I.sameAs.source===O?`Field '${O}' sameAs.source references itself.`:`Field '${O}' 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 '${O}' (${I.type}): sameAs.source '${I.sameAs.source}' hat einen anderen Typ (${D.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${O}' (${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 '${O}': sameAs.source '${I.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${O}' sameAs.source '${I.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let Z=u.get(I.sameAs.toggle);(Z===void 0||Z.type!=="boolean")&&r.push({severity:"error",path:`${B}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:Z===void 0?`Feld '${O}': sameAs.toggle verweist auf das unbekannte Feld '${I.sameAs.toggle}'.`:`Feld '${O}': sameAs.toggle '${I.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${Z.type}').`,en:Z===void 0?`Field '${O}' sameAs.toggle references unknown field '${I.sameAs.toggle}'.`:`Field '${O}' sameAs.toggle '${I.sameAs.toggle}' must be type 'boolean' (got '${Z.type}').`}}),I.required===!0&&r.push({severity:"error",path:`fields[${O}].required`,code:"config.sameas-static-required",message:{de:`Feld '${O}' deklariert sameAs, ist aber statisch Pflicht \u2014 solange es gespiegelt ist, hat es keinen eigenen Wert, die Slice-Validierung beim Commit w\xFCrde immer scheitern. required: false + requiredIf: "${I.sameAs.toggle} != true" verwenden.`,en:`Field '${O}' declares sameAs but is statically required \u2014 while mirrored it holds no own value, so commit-time slice validation would always fail. Use required: false + requiredIf: "${I.sameAs.toggle} != true".`}})}{let O=new Map;e.effects.forEach(I=>O.set(I.id,I.kind)),e.effects.forEach((I,B)=>{if(I.kind!=="shareValue")return;[["from",I.from],["to",I.to]].forEach(([le,ue])=>{let xe=O.get(ue.slice(1));xe!==void 0&&xe!=="person"&&xe!=="organization"&&r.push({severity:"error",path:`effects[${B}].${le}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${I.id}': shareValue ${le} '${ue}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${xe}').`,en:`Effect '${I.id}' shareValue ${le} '${ue}' must reference a person/organization effect (got '${xe}').`}})});let D=I.from.slice(1);e.effects.some(le=>le.kind==="fieldMap"&&le.target.slice(1)===D&&le.mappings.some(ue=>ue.to===I.field)||le.kind==="shareValue"&&le.id!==I.id&&le.to.slice(1)===D&&le.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((O,I)=>{O.kind==="person"&&O.bucket.includes(Lr)&&r.push({severity:"error",path:`effects[${I}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': bucket '${O.bucket}' darf '${Lr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' bucket '${O.bucket}' must not contain '${Lr}' (reserved for the per-row namespace).`}}),O.kind==="organization"&&O.orgKind.includes(Lr)&&r.push({severity:"error",path:`effects[${I}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': orgKind '${O.orgKind}' darf '${Lr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' orgKind '${O.orgKind}' must not contain '${Lr}' (reserved for the per-row namespace).`}})});let pe=new Set;function te(O,I){O.repeated?.forEach((B,D)=>{let Z=B.effects??[];if(Z.length>0){let le=`${I}.repeated[${D}]`,ue=new Set(Z.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"),it=s(ie=>ie.startsWith("$item.")?xe.has(ie.slice(6)):a.has(ie),"resolvesFrom"),Ht=s(ie=>{let Nt=ie.slice(1);return ue.has(Nt)||m.has(Nt)},"resolvesRef");Z.forEach((ie,Nt)=>{let pt=`${le}.effects[${Nt}]`;if(m.has(ie.id)||pe.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.`}}):pe.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:le,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(Lr)&&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 '${Lr}' nicht enthalten.`,en:`Repeated effect '${ie.id}' ${ie.kind==="person"?"bucket":"orgKind"} '${Ne}' must not contain '${Lr}'.`}}),ie.kind==="person"&&r.push(...eL(ie,Z,pt,ft)),ie.kind==="organization"&&ie.nameFrom?.forEach((Ue,In)=>{ft(Ue)||r.push({severity:"error",path:`${pt}.nameFrom[${In}]`,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,In)=>{it(Ue)||r.push({severity:"error",path:`${pt}.identity.keyFrom[${In}]`,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)=>{it(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.`}})})}}),O.subsections?.forEach((B,D)=>te(B,`${I}.subsections[${D}]`))}s(te,"visitRepeatedEffects"),e.sections.forEach((O,I)=>te(O,`sections[${I}]`));let oe=TF(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(...g4(e)),r}s(tL,"validateForm");function g4(e){let t={...e,effects:e.effects.map(nL),sections:e.sections.map(rL),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return Df(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:jy(n)}))}s(g4,"missingTranslationIssues");function nL(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(nL,"withoutSubjectFlag");function rL(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(nL)})),subsections:e.subsections?.map(rL)}}s(rL,"withoutRowSubjectFlags");function QF(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(QF,"exportGateIssues");function Xs(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${ZF(r,"de")} '${t}'`,en:`Duplicate ${ZF(r,"en")}: '${t}'`}}):e.add(t)}s(Xs,"reportIfDup");function ZF(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(ZF,"labelForCode");function Zb(e,t,n,r,i,o){e.visibleIf&&(pr(e.visibleIf,`${t}.visibleIf`,n,r,o),ea(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(pr(e.requiredIf,`${t}.requiredIf`,n,r,o),ea(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(pr(e.disabledIf,`${t}.disabledIf`,n,r,o),ea(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&pr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(Zb,"checkFieldAsts");function Xb(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo"}}s(Xb,"gatingMeta");function ea(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(XF(o.left,o.right,o.op,t,n,r),XF(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(ea,"checkGatingExpr");function XF(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(XF,"inspectEqualityOperand");function pr(e,t,n,r,i){i.push(...YF(e,n.declaredContext,t)),i.push(...zF(e,n.stageKeys,t));for(let o of kt(e))n.known.has(o)||Jb(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(pr,"checkAst");function eL(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 ${fr.firstName} / ${fr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${fr.firstName} / ${fr.lastName}. Remove nameFrom.`}});let o=DF(e.id,t);LF(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${fr.firstName} oder ${fr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${fr.firstName} or ${fr.lastName} \u2014 the person would get no name.`}});for(let a of FF(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(eL,"personNameIssues");var y4="blocked";function iL(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(w4(i))return r.id===y4?null:r.id}return null}s(iL,"resolveActiveOutcome");function w4(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(w4,"truthy");function oL(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(oL,"isScalar");function k4(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(oL(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))oL(a)&&(t[`${r}.${o}`]=a)}b4(e,t,n)}s(k4,"mergeRecord");function b4(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);ji(a).test(i)&&r.add(a)}for(let i of r){let o=Wb(e,i),a=0;for(let l=0;l<o;l++)RF(e,i,l)&&a++;t[`${i}.count`]=a}}s(b4,"mergeRepeatedCounts");function sL(e,t,n){let r={...n};return k4(e,r,t),r}s(sL,"flattenValues");function ev(e,t,n){return{code:e,fieldKey:t,text:n}}s(ev,"submitIssue");function aL(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(aL,"truthyEval");function lL(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(lL,"isEmptyValue");function v4(e,t,n){let r=!!e.required;if(!r&&e.requiredIf)try{r=aL(gt(e.requiredIf,{values:t}))}catch{r=!1}return r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(v4,"fieldIsLiveRequired");function x4(e,t,n){return dL(e,t,n).evalCtx}s(x4,"buildSubmitEvalContext");function dL(e,t,n){let r=S4(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=cL(e,l,n),c=new Set,u=new Set;fL(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(dL,"splitWithContext");function S4(e){let t=new Map,n=[];for(let r of nm(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:ji(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(S4,"fieldOwnership");function cL(e,t,n){let r=[];for(let o of nm(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=sL(t,r,n);for(let o of nm(e.sections))for(let a of o.computed??[])try{i[a.key]=gt(a.expression,{values:i})}catch{}return i}s(cL,"rawEvalContext");function uL(e,t,n){let{values:r,defaulted:i}=A4(e,t,n),o=dL(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(uL,"splitDraftValues");function A4(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of nm(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??=cL(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(A4,"applyFieldDefaults");function nm(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(nm,"walkSectionsDeep");function E4(e,t,n,r=!1){if(lL(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(E4,"fieldFormatIssue");function tm(e,t){if(!e)return!0;try{return aL(gt(e,{values:t}))}catch{return!1}}s(tm,"isVisibleUnder");function fL(e,t,n,r){let i=s(o=>{if(tm(o.visibleIf,t)){for(let a of o.fields)tm(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(tm(a.visibleIf,t))for(let l of a.fields)tm(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(fL,"forEachVisibleField");function pL(e,t,n,r={}){let i=x4(e,t,n),o=[],a=iL(e,i);a===null&&r.requireOutcome!==!1&&o.push(ev("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 fL(e,i,d=>{let c=t[d.key];if(lL(c)){!l.has(d.type)&&v4(d,i,a)&&o.push(ev("required",d.key,Ba([d.label],([f],m)=>m==="de"?`${f} ist ein Pflichtfeld.`:`${f} is a required field.`)));return}if(!r.registry)return;let u=E4(d,c,r.registry,r.testMode===!0);u!==null&&o.push(ev("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(pL,"checkSubmittable");function mL(e){let t=e.testScenarios??[];if(t.length===0)return[];let{compiled:n}=Fs(e),r=[];for(let i of t){let o=i.prefill??{};if(!UF(e,i.env))continue;let a=GF(e,i.env),{visible:l}=uL(n,o,a),d=pL(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:Ba([i.label,c.text],([u,f],m)=>m==="de"?`Szenario "${u}": ${f}`:`Scenario "${u}": ${f}`)})}}return r}s(mL,"validateScenarios");function rm(e){return e.filter(t=>(t.severity??"error")==="error")}s(rm,"blockingIssues");function im(e,t={}){return[...tL(e,t),...mL(e)]}s(im,"runFormValidators");function om(e){return rm(e)}s(om,"blockingFormErrors");function hL(e,t,n){return AP(e,t,n)}s(hL,"runWorkflowValidators");function gL(e){return rm(e)}s(gL,"blockingWorkflowErrors");var T4=["artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],yL={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"]}},cn={id:w.string(),label:Bs,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())},$4=w.object({...cn,type:w.literal("join")}),R4=w.object({...cn,type:w.literal("end")}),I4=w.object({...cn,type:w.literal("eventTrigger")}),O4=w.object({...cn,type:w.literal("form"),adoptForm:w.optional(w.any()),formExports:w.optional(w.any())}),P4=w.object({...cn,type:w.literal("roleAssign")}),_4=w.object({...cn,type:w.literal("setFlag")}),N4=w.object({...cn,type:w.literal("if"),condition:w.optional(w.any())}),C4=w.object({...cn,type:w.literal("countersign"),contract:w.optional(w.any()),signing:w.optional(w.any()),titles:w.optional(w.any())}),D4=w.object({...cn,type:w.literal("engagePush"),contract:w.optional(w.any()),engage:w.optional(w.any()),form:w.optional(w.any()),payment:w.optional(w.any())}),F4=w.object({...cn,type:w.literal("decision"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any()),requiresOneOf:w.optional(w.any())}),L4=w.object({...cn,type:w.literal("review"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any())}),M4=w.object({...cn,type:w.literal("waitlist")}),q4=w.object({...cn,type:w.literal("completenessCheck"),deadline:w.optional(w.any()),requires:w.optional(w.any())}),K4=w.object({...cn,type:w.literal("collectPayment")}),j4=w.object({...cn,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())}),WOe=w.union($4,R4,I4,O4,P4,_4,N4,C4,D4,F4,L4,M4,q4,K4,j4);function wL(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 yL)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=yL[a],d=new Set(["id","type","label",...T4,...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(wL,"workflowNodeEnvelopeIssues");function kL(e,t){return e.enumOptionLabels?.[t]??{de:t,en:t}}s(kL,"inlineEnumOptionLabel");var vL={string:"string",boolean:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function xL(e){return vL[e]!==void 0}s(xL,"isExportableFieldType");function B4(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(B4,"leafForComputed");function bL(e){let t=vL[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:kL(e,n)}))}:{}}}s(bL,"leafFor");function tv(e){let t=[],n=s(r=>{for(let i of r.fields)i.export===!0&&t.push(bL(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&t.push(bL(o));for(let i of r.computed??[])i.export===!0&&t.push(B4(i));for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(tv,"exportedFormLeaves");var SL=s(e=>e,"asEffectId"),Bi=s(e=>e,"asOutcomeId"),ta=s(e=>e,"asSectionId"),tn=s(e=>e,"asFieldKey");var ri=["string","boolean","date","enum","email","tel","address","docRef"],gd=["person","organization","relationship","fieldMap"],Ui=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],na=["fresh","keyed","manual"];function Co(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(Co,"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 yd(e){return Object.keys(e.smartforms??{})}s(yd,"carriedFormSlugs");function nv(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(nv,"boundFormSlugs");function sm(e,t){let n=yd(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(sm,"resolveFormSlug");function am(e,t){let n=e.smartforms?.[t];if(!n)throw new Error(`offer form: smartform "${t}" not found in bundle`);return n}s(am,"getForm");function qn(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(qn,"walkSections");function er(e,t){return qn(e).find(n=>n.id===t)}s(er,"findSection");function Do(e,t){for(let n of qn(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Do,"findField");function Fo(e){let t=new Set;for(let n of qn(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(Fo,"allFieldKeys");function U4(e){let t=ct(e.label,e.labelEn,"offer form add"),n={id:ta("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Bi("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(U4,"buildSkeletonSmartForm");function lm(e,t){let{key:n,label:r}=t;if(yd(e).includes(n))throw new Error(`offer form add: smartform "${n}" already exists in this bundle`);let i=U4({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(lm,"addForm");function AL(e,t){if(!yd(e).includes(t))throw new Error(`offer form rm: smartform "${t}" not found in bundle`);if(nv(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(AL,"removeForm");function EL(e,t){let n=am(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(EL,"setForm");function TL(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(TL,"nodesOf");function $L(e,t,n){let r=TL(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($L,"nodeOf");function RL(e){return e.flatMap(t=>{if(t.type!=="form"||wn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(RL,"creatingFormNodes");function IL(e){return om(im(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(IL,"formErrors");function dm(e){let t="offer workflow restamp-exports",n=TL(e,t),r=[];for(let{node:i,slug:o}of RL(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=IL(l);if(d.length>0)throw new Error(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
9761
+ `)}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}},Yk=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=pY(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:Xk(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}},Jk=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:Xk(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}},od=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function bp(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":od(t[r],""),...n===null?{}:{platform:od(n[r],"")}}))}s(bp,"chromeTextRows");var Qk=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=>[...bp("greeting",r.greeting,r.defaults.greeting),...bp("closing",r.closing,r.defaults.closing),{field:"senderName",school:od(r.senderName,"\u2014 (platform)"),platform:od(r.defaults.senderName,"")}],["field","school","platform"]),0}},Zk=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=>[...bp("greeting",l.greeting,null),...bp("closing",l.closing,null),{field:"senderName",school:od(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},dC=[Bk,Uk,Vk,Gk,zk,Wk,Hk,Yk,Jk,Qk,Zk];var hY="-stufe-",gY=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function eb(e){return`${e}${hY}`}s(eb,"stageKeyPrefix");function tb(e,t){return`${eb(e)}${t}`}s(tb,"stageStorageKey");function uC(e,t){let n=eb(e);return t.startsWith(n)&&t.length>n.length}s(uC,"isUnderProgram");function Cr(e,t){let n=eb(e);return uC(e,t)||ce("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(Cr,"bareStageKey");function vp(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"||!gY.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(vp,"stageSpecIssues");function cC(e){return{de:e.de.trim(),en:e.en.trim()}}s(cC,"trimmedText");function yY(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(yY,"describeNameChange");function xp(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:cC(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:cC(a)},u=tb(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={};is(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:uC(e,a.key)?Cr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(xp,"planStageReconcile");function Sp(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(yY(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(Sp,"describeStageStep");var wY=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ei(e,t){return`${e}-${t}`}s(ei,"runStorageKey");function fC(e,t){typeof t!="string"&&ce("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)&&ce("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(fC,"bareRunKey");function Ap(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"||!wY.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(Ap,"runSpecIssues");var kY={capacity:null,isOpen:!1},bY={capacity:null,isOpen:!0};function vY(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(vY,"isCapacity");function Ep(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)||!vY(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(Ep,"capacitySpecIssues");function mC(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(Cr(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===ei(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?kY:bY;v.capacity===k.capacity&&v.isOpen===k.isOpen||d.push({run:c.key,stageKey:f,from:v,to:k})}}return d}s(mC,"planRunCapacities");function pC(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(pC,"describeCell");function Tp(e){return`~cap ${e.run}\xD7${e.stageKey} ${pC(e.from)} \u2192 ${pC(e.to)}`}s(Tp,"describeCapacityStep");function hC(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(hC,"assertBackendHasStageKeys");async function nb(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}));hC(i);let a=xp(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(nb,"planStages");async function $p(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});hC(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Cr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return mC(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===ei(d,c)))})}s($p,"planCapacities");async function xY(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===ei(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(xY,"assertNoArchivedRunKey");var rb={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...vp(o??[]),...Ap(n.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(g=>g.message.de).join("; ")}`);let l=Ep(n.program?.runs??[],o?.map(g=>g.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await xY(e,i,t,n);let d=await $p(e,i,t,n),c=await e.query(S.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=SY(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 nb(e,i,t,o);m.push(...g.map(Sp))}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===ei(y.programKey,g.key));if(v!==void 0){is(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 $p(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(P=>P.key===ei(v,$.run))?.runId,A=g.stages.find(P=>Cr(v,P.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(Tp)),m.join(", ")}};function SY(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(SY,"bundleUnitKey");var gC={role:"control",effect:"pure",cardinality:"N-to-1"};var Rp=["add","remove","replace"];function yC(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(yC,"roleAssignLiteral");var wC={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=yC(e,"roleKey")?.trim()??"",o=yC(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"}),Rp.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 ${Rp.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${Rp.join(" | ")}.`},severity:"error"}),r},"validate")};var AY=["event","effect","outcomes"],ib=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),kC={outcomes:[{id:lr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of AY)i in r&&n.push(ib(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${lr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${lr}" itself.`));return Pn(t.nodes).some(i=>i.target===e.id)&&n.push(ib(`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?.[lr]===void 0&&n.push(ib(`nodes.${e.id}.next.${lr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${lr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${lr}" nowhere.`)),n},"validate")};var EY="submit",bC=[{id:EY,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function vC(e){return e==="draft"}s(vC,"isWritableSmartFormState");var ob=["draft","committed"],$xe=ob.filter(e=>vC(e));async function xC(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(xC,"getSmartFormInstance");var SC="form:fill",sb="request:collectPayment";var TY={key:SC,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},AC={key:"bearbeitung",label:ne("In Bearbeitung","In progress"),scope:"node"},EC={[$$]:{label:ne("In Bearbeitung","In progress"),tone:"neutral",phase:AC,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")},[Nu]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:AC,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."))}},TC={role:"user-action",effect:"side-effect",progressDefaults:EC,progressEvents:Pt(EC),actions:s(()=>bC,"actions"),workItemTemplates:s(()=>[TY],"workItemTemplates"),states:ob,currentState:s(async(e,t)=>{let n=await xC(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=>wn(e)?[]:[{id:Cu,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 $C={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:HR(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"&&tf(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 $Y="true",RY="false",ab=[{id:$Y,label:{de:"Ja",en:"Yes"}},{id:RY,label:{de:"Nein",en:"No"}}];var RC={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:ab,validate:s((e,t,n)=>IY(e,t,n),"validate")};function IY(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=ab.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=B$(t),a=Of(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 _y(e.condition,o)){let c=RO(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(IY,"ifNodeIssues");var sd="decision",OY=new Set(["decision","review"]),Xxe=new Set([...OY,"governedDocument"]);var OC=[{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 IC={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."))}},Fi={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:OC,progressDefaults:IC,progressEvents:Pt(IC),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,...bi(t.semantic)?{semantic:t.semantic}:{}})),...aP(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:sd,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===sd&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),validate:lb};function lb(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 ${yn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${d.id}" of "${e.id}" does not say what it means \u2014 one of ${yn.join(", ")}.`},severity:"error"}):bi(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: ${yn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${d.id}" of "${e.id}" has the meaning "${String(f)}" \u2014 allowed: ${yn.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(lb,"validateDecisionNode");var db=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],PC=[{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 Qn="processFooter";var cb="promoted";var _C="promote",NC="Nachr\xFCcken";var ub={key:"warteliste",label:ne("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},CC={waitlisted:{label:ne("Warteliste","Waitlisted"),tone:"amber",phase:ub,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:ub,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:ub,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."))}},DC={outcomes:db,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:zn.map(e=>({value:e,label:X$[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=Ig(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=Ig(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:CC,progressEvents:Pt(CC),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:db).some(n=>n.id===cb)?[{id:_C,kind:"advance",outcome:cb,semantic:"other",label:{de:NC,en:"Promote from waitlist"},surface:Qn,superUserOnly:!0}]:[],"actions")};var PY="complete",Ip="acceptedIncomplete",Op="rejected",_Y="absage",FC="closeWithoutDocuments",LC="rejectAtCompleteness",MC="Ohne Nachreichung abschlie\xDFen",qC="Ablehnen",KC="awaitingDocuments",fb="documentsComplete",pb="closedWithoutDocuments",mb="rejected",hb="withdrawn",jC="requested",xSe={[PY]:{event:fb,status:"complete",endsRole:!0},[Ip]:{event:pb,status:"acceptedIncomplete",endsRole:!1},[Op]:{event:mb,status:"rejected",endsRole:!0},[_Y]:{event:hb,status:"withdrawn",endsRole:!0}};var ad=s(()=>el[0],"beneficiary"),gb=366;function NY(e){let t=e.reads,n=tl(e).flatMap(({address:r})=>st(r)&&!el.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(st):[],...n]}s(NY,"printedFields");function CY(e,t){let n=se(t);return e.nodes.filter(r=>r.type==="governedDocument"&&NY(r).some(i=>se(i)===n))}s(CY,"documentsPrinting");function DY(e,t){if(!st(t)||t.path!==ad())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!wn(n)}s(DY,"isCreatedFormBeneficiary");function Gt(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Gt,"issue");var yb={key:"unterlagen",label:ne("Unterlagen nachreichen","Outstanding documents"),scope:"node"},BC={[KC]:{label:ne("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:yb,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."))},[fb]:{label:ne("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:yb,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."))},[pb]:{label:ne("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:yb,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."))},[mb]:{label:ne("Abgelehnt","Rejected"),tone:"red",phase:PI,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."))},[hb]:{label:ne("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:gf,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."))}},UC={outcomes:PC,progressDefaults:BC,progressEvents:Pt(BC),notificationEvents:s(()=>[{id:jC,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(Ip)&&n.push({id:FC,kind:"advance",outcome:Ip,semantic:"other",label:{de:MC,en:"Close without documents"},surface:Qn,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(Op)&&n.push({id:LC,kind:"advance",outcome:Op,semantic:"rejected",label:{de:qC,en:"Reject application"},surface:Qn,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),!st(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 P=Ir(n,R);if(P==null)continue;let L=Ii("requires",Ri(P));L==="computed"||L==="repeated"?r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(R)} ist ${P.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(R)} is ${P.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(Gt(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(R)} (\u201E${$i(P,"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)} ("${$i(P,"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||$>gb)&&r.push(Gt(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String($)}" ist keine ganze Zahl von 0 bis ${gb} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String($)}" is not a whole number from 0 to ${gb} days.`}))}else typeof u.until!="string"||wy(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<JI(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(st).map(R=>[se(R),R]));for(let R of $.values())for(let A of CY(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>.${en}.${ad()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${en}.${ad()}).`}))),be(v)&&!DY(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>.${en}.${ad()}).`,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>.${en}.${ad()}).`})),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 FY=[{id:tR,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],ld=s(e=>e,"asDecision"),VC={[nR]:{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."))}},GC={role:"user-action",effect:"side-effect",outcomes:FY,progressDefaults:VC,progressEvents:Pt(VC),notificationEvents:s(e=>Fi.notificationEvents(ld(e)),"notificationEvents"),actions:s(e=>[...Fi.actions(ld(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:_g,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Fi.optionalActionKinds,workItemTemplates:s(e=>Fi.workItemTemplates(ld(e)).map(t=>t.key===sd?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,_g]}:t),"workItemTemplates"),taskDocuments:s((e,t)=>Fi.taskDocuments(ld(e),t),"taskDocuments"),validate:s((e,t,n)=>{let r=lb(ld(e),t,n),i=Array.isArray(e.reads)?e.reads:[];for(let o of e.outcomes??[]){let a=o.semantic;typeof a!="string"||!Wu.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(!st(o))continue;let a=Ir(n,o);a==null||Ii("nodeReads",Ri(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 zC=["awaitingAnswer","answered"];async function WC(e,t){return(await hl(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(WC,"externalRequestState");var JC=[{id:vs,label:{de:"Bezahlt",en:"Paid"}}],iAe=new Set(JC.map(e=>e.id));var LY=vs,HC=[{id:LY,kind:"advance",outcome:vs,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],MY={id:ay,kind:"advance",outcome:vs,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:Qn,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"}}},qY={id:ay,kind:"advance",outcome:vs,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:Qn,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 wb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(wb,"literalOf");function Ys(e){let t=wb(e,Wn);return sf(t)?t:null}s(Ys,"settlementOrNull");function KY(e){let t=wb(e,Ei);return typeof t=="string"&&t.length>0?t:null}s(KY,"articleKeyOrNull");function jY(e){let t=wb(e,Hn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(jY,"payeeKeyOrNull");var BY={id:Ei,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},UY={id:Wn,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)"}}]},VY={id:Ti,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},GY={id:Hn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function zY(e){return[BY,UY,...Ys(e)==="online"?[GY]:[],VY]}s(zY,"collectPaymentInputs");var WY=["amount","currency","settlement"];function HY(e,t){if(Ys(e)!=="online")return[];let n=jY(e);if(n===null)return[];let r=`nodes.${e.id}.inputs.${Hn}`,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(HY,"payeeIssues");var YC={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."))}},QC={outputs:s(()=>[{name:MR,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>zY(e),"inputs"),outcomes:JC,progressDefaults:YC,progressEvents:Pt(YC),notificationEvents:s(e=>Ys(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=Ys(e);return t==="online"?[...HC,qY]:t==="separate"?[MY]:[]},"actions"),states:zC,currentState:s((e,t)=>WC(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:sb}),"currentState"),workItemTemplates:s(e=>{let t=e;return Ys(t)!=="online"?[]:[{key:sb,recipient:"external",title:t.label,unlocks:HC.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 WY)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(...HY(e,n)),Ys(e)===null&&i(`inputs.${Wn}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${bs.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[Wn])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${bs.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[Wn])}.`});let o=e.inputs?.[Ti];if(o?.kind==="literal"){let d=of(o.value);d!==null&&i(`inputs.${Ti}`,{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=KY(e);if(a===null)return i(`inputs.${Ei}`,{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.${Ei}`;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 ${ly.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${ly.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 Ln="traeger",ZC={de:"Tr\xE4ger",en:"Provider"};function Pp(e){let t=e.inputs?.[Ln];return t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0?t.value:null}s(Pp,"traegerKeyOfNode");var _p={name:"input.traeger.name",address:"input.traeger.anschrift"},aAe=Object.values(_p);var XC="governedDocument",To="prepareDocument",dd="prepareDocument:revision",Dr="releaseApproval",$o="documentResponse",Fr="responseCheck",Np="returnSigned";var eD="requestApproval";var tD="issueDocument",nD="correctInPlace",rD="rescindAndReissue",Cp="requestChange";var Js="releaseArtifact",dn="signingRecovery",Ro="resendESignature",Io="switchToPaper";var kb=new Set([To,dd]),iD=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],Dp=["upload","resolver","template","none"],Oo=1,Po=366,ti="responseDueInDays";function bb(e){let t=e.inputs?.[ti];return t?.kind==="literal"&&cd(t.value)?t.value:void 0}s(bb,"responseDueInDaysForVocabulary");function cd(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Oo&&e<=Po}s(cd,"isValidResponseDueInDays");var Fp=["generatedAt","responseDueInDays"],_o=["release","none"],Lp=["confirm","signedUpload","signedUploadChecked","eSignature"];function oD(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(oD,"localeFieldMissingText");var vb=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),sD=/^[a-z][a-z0-9_]*$/;function aD(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"||!sD.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(!Ai(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 (${ks.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 (${ks.join(", ")}).`}});continue}if(vb.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 ${[...vb].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a letter only prints ${[...vb].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!sD.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&&!Fp.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Fp.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Fp.join(", ")}.`}})}return n.push(...YY(e,t)),n}s(aD,"templateParameterIssues");function YY(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:oD(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(YY,"localeFieldIssues");function lD(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(lD,"applyTemplateStamp");var xb=50;async function Mp(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take(xb+1);return n.length>xb&&N(`signing_returns: Vorgang ${t} has more than ${xb} returns`),n}s(Mp,"returnsOf");var Sb=50;async function Ab(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(Sb+1);return n.length>Sb&&N(`signing_returns: return ${t} has more than ${Sb} files`),n.length===0&&N(`[signing/noDocument] return ${t} carries no file`),n}s(Ab,"returnDocumentsOf");async function dD(e,t){let n=await Ab(e,t);return n.length!==1&&N(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(dD,"soleReturnDocumentOf");var qp=200,RAe=qp*20;async function JY(e,t){let n=await e.db.get(t);return n===null&&N(`[process] application ${t} not found`),n.redactedAt!==void 0}s(JY,"processRedacted");async function Eb(e,t){await JY(e,t)&&ce("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(Eb,"assertProcessReadable");function QY(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(QY,"rowOf");async function cD(e,t,n){await Eb(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(qp+1);return r.length>qp&&N(`[process] application ${t} has more than ${qp} results of ${n.scope}.${n.owner}.${n.key}`),r.map(QY)}s(cD,"storeHistory");async function ZY(e,t,n){if(n.key===en){await Eb(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 cD(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(ZY,"nodeResultAt");async function Kp(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return XY(await ZY(e,t.applicationId,n),n,t.applicationId)}s(Kp,"readOwnResult");function XY(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(XY,"refOf");var Tb={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},eJ=Object.keys(Tb),tJ=eJ.filter(e=>Tb[e]==="open"),LAe=tJ.filter(e=>e!=="pending");function uD(e){return Tb[e]==="terminal"}s(uD,"isTerminalSigningStatus");var Li=["docusign","insign"];var ud={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var rJ=uD;function pD(e){return!rJ(e.status)&&e.voidRequestedAt===void 0}s(pD,"holdsContract");async function mD(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(mD,"traegerLegalEntityOfParty");async function iJ(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(iJ,"isOrganizationParty");async function hD(e,t){return await mD(e,t)!==null?"traeger":await iJ(e,t)?"organization":"person"}s(hD,"signerKindOf");async function gD(e,t){t.length===0&&N("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await oJ(e,n.partyId)==="family")return"family";return"traeger"}s(gD,"signingSideOf");async function oJ(e,t){return await hD(e,t)==="traeger"?"traeger":"family"}s(oJ,"sideOfParty");var gEe=16*1024;var yEe=15*6e4;var wEe=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()}))},DEe=Br({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 KEe=w.object($b);var Rb=200;async function aJ(e,t,n,r){t.length>Rb&&N(`${r} is carried by more than ${Rb} 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(aJ,"requestsOfMembers");async function yD(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(Rb+1);return await aJ(e,r,n,`revision ${t}`)}s(yD,"requestsOfSnapshot");var wD=100;async function lJ(e,t){let n=await yD(e,t);n.length>wD&&N(`requestsBySideOf: revision ${t} has more than ${wD} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await gD(e,i.signers)].push(i);return r}s(lJ,"requestsBySideOf");async function Ib(e,t){return(await lJ(e,t)).family}s(Ib,"familyRequestsOf");var Ob=100;async function dJ(e,t){let n=await e;return n.length>Ob&&N(`contractChain: more than ${Ob} ${t}`),n}s(dJ,"bounded");async function cJ(e,t,n){let r=await Kp(e,{applicationId:t,nodeId:n,key:hs});return r.state==="pending"?null:(r.ref.kind!=="contract"&&N(`contractChain: $node.${n}.${hs} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(cJ,"nodeContractRef");async function kD(e,t){return await dJ(e.db.query("contract_snapshots").withIndex("by_contractId_and_revisionNumber",n=>n.eq("contractId",t)).take(Ob+1),`revisions on contract ${t}`)}s(kD,"snapshotsAsc");async function Pb(e,t){let n=(await Ib(e,t)).filter(pD);return n.length>1&&N(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s(Pb,"openFamilyRequest");async function uJ(e,t){for(let n of await kD(e,t))if((await Ib(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(uJ,"familyRoute");async function bD(e,t){for(let n of t)if(await uJ(e,n)==="paper")return"paper";return"provider"}s(bD,"familyRouteOf");async function fJ(e,t){let n=await dD(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(fJ,"toReturn");function jp(e){async function t(a,l){return await cJ(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 kD(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 Pb(a,c._id);if(u===null)return null;let f=(await Mp(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 fJ(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(jp,"contractNodeReads");function Bp(e){return e.addedParts??[]}s(Bp,"addedPartsOf");var _b=50;async function pJ(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(_b+1);return n.length>_b&&N(`groupRunsOf: generation group ${t} has more than ${_b} runs`),n.length===0&&N(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(pJ,"groupRunsOf");async function vD(e,t){let n=await pJ(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),...Bp(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(vD,"groupRunsInOrder");function xD(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(xD,"isCompleteGroup");var Nb=200;function mJ(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(mJ,"groupPartKeys");async function hJ(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(Nb+1);return r.length>Nb&&N(`groupChain: more than ${Nb} generation runs on node ${n}`),r}s(hJ,"nodeRuns");async function gJ(e,t,n){let r=mJ(n),i=new Set;for(let a of await hJ(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 vD(e,a);if(!xD(l))continue;let d=await e.db.get(a);d===null&&N(`groupChain: generation group ${a} has no package run`);let c=new Set(Bp(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(gJ,"groupRevisionRows");async function Cb(e,t,n){let r=await Kp(e,{applicationId:t,nodeId:n,key:gs});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&N(`groupChain: $node.${n}.${gs} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(Cb,"nodeGroupContracts");async function yJ(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await Pb(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(yJ,"openGroupRequest");async function wJ(e,t){let n=[];for(let i of await Ab(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(wJ,"toGroupReturn");function SD(e){async function t(i,o,a,l){let d=(await gJ(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 yJ(i,l);if(d===null)return null;let c=(await Mp(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 wJ(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await Cb(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(SD,"groupNodeReads");var kJ={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"}}},AD={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"}}},ED={...AD,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},bJ={...ED,kind:"eSignature",issuesBy:"provider"},ni={confirm:kJ,signedUpload:AD,signedUploadChecked:ED,eSignature:bJ};function Mi(e){let t=e.responseStrategy;if(typeof t=="string"&&t in ni)return ni[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(Mi,"responseStrategyOf");function TD(e){if(e.type!==XC||e.production!=="resolver")return!1;let t=e.responseStrategy;return typeof t=="string"&&t in ni?ni[t].acceptEvent==="contractEvent":!1}s(TD,"isFamilySignedContractNode");function fd(e){return e.label}s(fd,"governedDocTitle");function Db(e){return e.approval==="release"?eD:tD}s(Db,"submitActionId");function $D(e,t,n){return{key:t,recipient:"internal",title:n,unlocks:[Db(e)],gatesNode:!0,advancesNode:!0}}s($D,"producerTemplate");function vJ(e){return e.titles?.respond??e.label}s(vJ,"responseTitle");var Qs={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Fb(e){let t=Mi(e),n=[];if(e.production!=="none"&&n.push($D(e,To,e.titles?.prepare??Qs),$D(e,dd,e.titles?.revise??Qs)),e.approval==="release"&&n.push({key:Dr,recipient:"internal",title:e.titles?.approve??Qs,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),n.push({key:$o,recipient:"external",title:vJ(e),unlocks:t.producesResponseArtifact?[t.checksReturn?Np:t.acceptOutcomeId,t.declineOutcomeId,Cp]:[t.acceptOutcomeId,t.declineOutcomeId],advancesNode:!0,...bb(e)!==void 0?{dueInDays:bb(e)}:{}}),t.checksReturn&&n.push({key:Fr,recipient:"internal",title:e.titles?.check??Qs,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),t.issuesBy==="provider"){let r=fd(e);n.push({key:dn,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Ro,Io],gatesNode:!1,advancesNode:!1})}return n}s(Fb,"governedDocIntrinsicTemplates");function xJ(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(xJ,"governedDocSlot");function Up(e){return xJ(e).key}s(Up,"governedDocSlotKey");function SJ(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(SJ,"toRevision");function AJ(e){let t=SJ(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(AJ,"toReturn");function RD(e){let t=Up(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;ce("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 AJ(c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(RD,"artifactNodeReads");function Vp(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(Vp,"documentChainKind");function ID(e){switch(Vp(e)){case"contract":return jp(e).reads;case"group":return SD(e).reads;case"artifact":return RD(e).reads}}s(ID,"documentReadsFor");var EJ={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function pd(e){let t=e.responseStrategy;return typeof t=="string"&&t in ni?ni[t].producesResponseArtifact:!1}s(pd,"returnsSignedCopy");function TJ(e){return pd(e)&&e.confirmContractTerms!==!1}s(TJ,"asksContractTerms");function OD(e){return TJ(e)?{title:e.contractTermsQuestionText??EJ,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(OD,"contractTermsConfirm");async function $J(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:Oy(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Fr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&N(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${Fr} row`),a}s($J,"rejectedReturnOfAsk");async function PD(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await $J(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(PD,"returnedCopyOfAsk");var Lb=new Set([...kb,Dr,$o,Fr,dn]),DD={id:Ft,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},FD={id:so,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function RJ(e){let t=[],n=[{slot:DD,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:FD,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=nl(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(RJ,"referenceInputIssues");var IJ={id:ti,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},OJ={id:Ln,type:"legalEntity",label:ZC,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function PJ(e,t){let n=`inputs.${Ln}`,r=e.inputs?.[Ln];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=Pp(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 (${_p.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 (${_p.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(PJ,"traegerIssues");function zp(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}}:(wi(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(zp,"generatorFields");function _J(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(_J,"deferredToCockpit");function NJ(e){return Ai(e.type)?e.type:void 0}s(NJ,"resolverSlotType");function CJ(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=fd(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(CJ,"issueConfirmation");function Re(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Re,"issue");function Gp(e){return Dp.includes(e.production)&&_o.includes(e.approval)&&Lp.includes(e.responseStrategy)}s(Gp,"hasValidModes");async function Mb(e,t){let n=await hl(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&&kb.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";let o=r.find(l=>l.templateKey===Dr);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===dn))return"signatureStalled";let a=r.find(l=>l.templateKey===$o);if(a!==void 0){if(Mi(t.node).issuesBy==="provider"){let d=Vp(t.node)==="group"?(await Cb(e,t.applicationId,t.node.id)).map(c=>c.contractId):[await jp(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 bD(e,d)==="provider")return"awaitingSignature"}return Mi(t.node).producesResponseArtifact?await PD(e,{chain:ID(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===Fr)?"responseInCheck":"done"}s(Mb,"governedDocCurrentState");function _D(e){return e.production!=="none"&&Vp(e)!=="artifact"}s(_D,"keepsDocumentInContractDomain");function DJ(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!be(r)||r.scope!=="env"||!sr(r.key))return[];let i=oo(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(DJ,"envCoverageIssues");function LD(e,t){let n=[];for(let r of zp(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...DJ(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"}:_J(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(LD,"fieldSourceIssues");function FJ(e){let t=ar(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=aD(e.templateStamp,t).map(({path:r,reason:i})=>Re(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...LD(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(FJ,"templateIssues");function LJ(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(LJ,"eSignatureAnchorIssues");function MJ(e,t){return t===void 0||t.sendable?[]:Mi(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(MJ,"eSignatureProviderIssues");var ND={key:"dokument",label:ne("Dokument","Document"),scope:"node"},CD={producing:{label:ne("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:ND,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:ND,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"))}},MD={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>To,"processHoldTemplate"),progressDefaults:CD,progressEvents:Pt(CD),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(!Gp(e))return[];let t=Mi(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:Db(e),kind:"internal",surface:Js,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...CJ(e)??{}}),n.push({id:nD,kind:"internal",surface:Js,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:rD,kind:"internal",surface:Js,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:Np,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:Cp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:Ro,kind:"internal",surface:Js,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Io,kind:"internal",surface:Js,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:iD,currentState:Mb,workItemTemplates:s(e=>{let t=e;return Gp(t)?Fb(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e;if(!Gp(n)||n.production==="none")return[];let r=Fb(n).find(i=>i.key===t);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:Up(n)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[DD,OJ]:[],...e.production==="template"?[FD]:[],IJ,...zp(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=NJ(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"&&vi(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:Za,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===$o||t===dd||t===Fr||t===dn){let n=t===$o?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===Fr?{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===dn?{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: ${To}${e.approval==="release"?`, ${Dr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${To}${e.approval==="release"?`, ${Dr}`:""}.`}}return t===Dr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Dr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Dr}" 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(_D(t.node))return!1;let n=await Mb(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&Mi(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=OD(t.node);if(n===null||_D(t.node))return null;let r=await Mb(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Gp(e))return r.push(Re(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${Dp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${_o.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Lp.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 {${Dp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${_o.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Lp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=ni[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(...LJ(e,n),...MJ(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.`})),pd(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??[])Lb.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 (${[...Lb].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${v.key}" on node "${e.id}" collides with an intrinsic template (${[...Lb].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...PJ(e,n)):e.inputs?.[Ln]!==void 0&&r.push(Re(e,`inputs.${Ln}`,{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(...RJ(e)),e.production==="resolver"){let v=zr(e);if(v!==null){let $=W$(v);for(let R of zp(e)){if(!Ai(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 (${ks.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 (${ks.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(...LD(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(...FJ(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?.[ti],g=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return g!==void 0&&!cd(g)&&r.push(Re(e,`inputs.${ti}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(g)} \u2014 erlaubt ist eine ganze Zahl von ${Oo} bis ${Po} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(g)} \u2014 a whole number from ${Oo} to ${Po} days is allowed.`})),g===void 0&&zp(e).some(v=>v.processSource==="responseDueInDays")&&r.push(Re(e,`inputs.${ti}`,{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 Wp="countersign",qb="countersign",qD="countersigned",KD="countersigning",jD="countersigned",BD={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},md=["scan","eSignature"],Hp="service_provider:1",UD=["countersigning","awaitingSignature","signatureStalled","done"],VD={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function GD(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(GD,"traegerSignatoryMissingReason");function Zn(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Zn,"issue");function HD(e,t){return e.nodes.filter(n=>{let r=n.contract;return n.type==="countersign"&&be(r)&&r.scope==="node"&&r.owner===t})}s(HD,"countersignersOf");function hd(e){return e.signing==="eSignature"}s(hd,"isElectronic");function qJ(e,t){if(t===void 0||t.sendable||!hd(e))return[];let n=e.label?.de??e.id,r=e.label?.en||e.id;return[Zn(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(qJ,"countersignProviderIssues");function KJ(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 TD(r)||i.push("sourceNotCheckedContract"),HD(e,r.id).some(o=>o.id!==t)&&i.push("twice"),i}s(KJ,"countersignContractRefusals");function zD(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(zD,"validDueInDays");function jJ(e,t,n){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!md.includes(o))return[Zn(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?.[dn];if(!hd(e))return a===void 0?[]:[Zn(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(Zn(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(...BJ(e,t,n),...UJ(e,t,n),...qJ(e,n?.signingProvider)),l}s(jJ,"signingIssues");function YD(e,t){let n=e.contract;if(!(!be(n)||n.scope!=="node"))return t.nodes.find(r=>r.id===n.owner)}s(YD,"contractNodeOf");function BJ(e,t,n){let r=YD(e,t),i=r===void 0?null:Pp(r),o=i===null?void 0:n?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[Zn(e,"signing",GD(o.name))]}s(BJ,"traegerSignatoryIssues");function UJ(e,t,n){let r=YD(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(Zn(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(Hp)||l.push(Zn(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Hp}/ \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:${Hp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(UJ,"traegerAnchorIssues");var Kb=100;async function VJ(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(Kb+1);n.length>Kb&&N(`countersign node "${t.node.id}" of ${t.applicationId} holds more than ${Kb} 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)===dn)?"signatureStalled":r.some(o=>i(o)===Wp)?"countersigning":hd(t.node)?"awaitingSignature":"done"}s(VJ,"countersignCurrentState");var WD={[KD]:{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."))}},JD={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:qD,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:WD,progressEvents:Pt(WD),notificationEvents:s(()=>[{id:jD,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:qb,kind:"internal",label:BD,surface:Qn,availableIn:["countersigning"]},...hd(e)?[{id:Ro,kind:"internal",surface:Qn,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Io,kind:"internal",surface:Qn,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Wp,recipient:"internal",title:e.titles?.countersign??Qs,unlocks:[qb],advancesNode:!0,...zD(e)!==void 0?{dueInDays:zD(e)}:{}},...hd(e)?[{key:dn,recipient:"internal",title:VD,unlocks:[Ro,Io],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:UD,currentState:VJ,validate:s((e,t,n)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[Wp];(typeof a!="string"||a.length===0)&&r.push(Zn(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.`})),wi(e.titles?.countersign)||r.push(Zn(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(Zn(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(...jJ(e,t,n));let d=e.contract;if(!be(d))return r;let c=KJ(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(Zn(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=HD(t,u.id).filter(m=>m.id!==e.id);r.push(Zn(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 QD={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 Mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Mn,"isRecord");var jb=["field","join","literal","address","payment","contract"],GJ=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),zJ=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function Xn(e){return typeof e=="string"&&e.trim().length>0}s(Xn,"nonEmptyString");function Yp(e,t,n,r,i="value"){if(!Mn(e)||!Mn(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=jb.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${jb.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${jb.join(" | ")}).`}});return}let[l]=a;l==="field"&&!Xn(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(Xn))&&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)||Xn(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"&&sr(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&&!GJ.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&&!(Xn(e.lookup)&&Mn(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"||Mn(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Mn(d)&&zJ.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(Yp,"checkMapping");function qi(e,t,n,r,i){if(!Mn(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=QD[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))Yp(l,`${t}.${a}`,r,i)}s(qi,"checkBody");function ZD(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(!Mn(o)||!Xn(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),Yp(o.value,`${l}.value`,n,r),o.unless!==void 0&&Yp(o.unless,`${l}.unless`,n,r,"condition")})}s(ZD,"checkAif");function Bb(e){let t=[];if(!Mn(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=Mn(e.lookups)?e.lookups:{};Mn(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))(!Mn(i)||!Object.values(i).every(Xn))&&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(Xn(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),qi(e.pupil,"engage.pupil","addPupil",n,t),qi(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&qi(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&qi(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&qi(e.medical,"engage.medical","addMedical",n,t),ZD(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(!Mn(i)||!Xn(i.key)||!Xn(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),qi(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&qi(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)=>qi(u,`${a}.${l}[${f}]`,d,n,t))}}ZD(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&Yp(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Mn(r)||!Xn(r.repeated)||!Xn(r.field)||!Xn(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(Bb,"engagePushConfigIssues");function*Ub(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(Ub,"mappingsOf");function XD(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of Ub(e))for(let i of WJ(n.from))t.add(HJ(i,r));return[...t]}s(XD,"configFieldKeys");function WJ(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(WJ,"formFieldsOf");function HJ(e,t){return e.startsWith(".")?(t===void 0&&N(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(HJ,"resolveFieldKey");function eF(e,t){for(let{mapping:n}of Ub(e))if(t in n.from)return!0;return!1}s(eF,"configReadsSource");function tF(e){let t=new Set;for(let{mapping:n}of Ub(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(tF,"configEnvLeaves");var nF="done",rF=["sandbox","production"];var Jp="engagePush",G$e=660*1e3;function Ki(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(Ki,"issue");function Vb(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Vb,"literal");function iF(e){return Bb(e.engage).length===0?e.engage:null}s(iF,"validConfig");function YJ(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(YJ,"bypassingPath");var oF={role:"system-action",effect:"side-effect",outcomes:[{id:nF,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=iF(e);return t===null?[]:tF(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=Vb(e,"target");rF.includes(a)||o.push(Ki(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=Vb(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(Ki(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?.[Jp];(typeof d!="string"||d.length===0)&&o.push(Ki(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${Jp}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${Jp}\` names the team.`}));for(let g of Bb(e.engage))o.push(Ki(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"&&Vb(g,"target")===a);c.length>0&&o.push(Ki(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.`})),YJ(t,e.id)&&o.push(Ki(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=iF(e),f=e;for(let[g,v,$,R]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!eF(u,g)||f[v]!==void 0||o.push(Ki(e,v,{de:Ss("address/missing",{where:`\u201E${r}\u201C \u203A ${$}`},"de"),en:Ss("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=XD(u).filter($=>!g.has($)&&!/\[\d+\]\./.test($));if(v.length>0){let $=t.nodes.find(R=>R.id===y);o.push(Ki(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 No={join:gC,end:NI,roleAssign:wC,eventTrigger:kC,waitlist:DC,completenessCheck:UC,form:TC,setFlag:$C,if:RC,decision:Fi,review:GC,collectPayment:QC,governedDocument:MD,countersign:JD,engagePush:oF};NR(No);function sF(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(sF,"graphOf");function aF(e){let t=new Map;for(let n of e.nodes)for(let r of $r(e,n))t.set(se(r.address),r.nodeId);return t}s(aF,"producedOf");function lF(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(po(e,n).map(r=>se(r.address))));return t}s(lF,"readsOf");function dF(e,t){let n=sF(e,"bundle"),r=sF(t.graph,"live head"),i=aF(n),o=aF(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=lF(n),d=lF(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(dF,"planAddresses");function cF(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(cF,"addressPlanRows");function uF(e,t){return t==null?!0:Pe(e)!==Pe(t)}s(uF,"changed");async function fF(e,t,n){if(t.index.module!==rb.name)throw new Error(`offer: unknown module "${t.index.module}"`);return VP(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return rb.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(fF,"applyOffer");async function pF(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(pF,"exportOffer");async function Gb(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?uF(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=uF(k&&{graph:ls(t.workflow.graph),progressLayout:t.workflow.progressLayout??k.progressLayout,progressWiring:t.workflow.progressWiring??k.progressWiring},k&&{graph:ls(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=dF(t.workflow.graph,y))}}let c=n.program?.stages,u=c===void 0?[]:i?await nb(e,n.tenant,n.slugs.manifest,c):xp(null,[],c),f=await $p(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(Gb,"diffOffer");function Qp(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(Qp,"contractProductionModeOf");function mF(e){return Qp(e)==="resolver"}s(mF,"isResolverCarrierNode");function Zp(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=zr(n);return!mF(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(Zp,"authoredPins");var hF={type:"address",dataType:"composite"};var gF={type:"boolean",dataType:"boolean"};var yF={type:"date",dataType:"date"};var wF={type:"docRef",dataType:"file"};var kF={type:"email",dataType:"text"};var bF={type:"enum",dataType:"option"};var vF={type:"string",dataType:"text"};var xF={type:"tel",dataType:"text"};var JJ={address:hF.dataType,boolean:gF.dataType,date:yF.dataType,docRef:wF.dataType,email:kF.dataType,enum:bF.dataType,string:vF.dataType,tel:xF.dataType};function zb(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(zb,"shapeOf");function SF(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,zb(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,zb(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}`,zb(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(SF,"fieldMapScopes");function QJ(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(QJ,"computedKeysOf");function AF(e){let t=[],n=QJ(e);for(let r of SF(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(AF,"validateFieldMapSources");function EF(e){let t=[],n=new Set;for(let o of SF(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(EF,"validateFieldPersistence");var ZJ="$";function XJ(e){return typeof e=="string"&&e.startsWith(ZJ)}s(XJ,"isRef");function Xp(e){return e.slice(1)}s(Xp,"stripRef");function*e4(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(e4,"refSlots");function t4(e){let t=new Set;for(let n of e4(e))XJ(n)&&t.add(Xp(n));return[...t]}s(t4,"collectRefs");function n4(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 t4(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=Xp(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&Xp(l.target)===a||l.kind==="shareValue"&&Xp(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(n4,"buildAdjacency");function TF(e){let{refsOf:t}=n4(e),r=_f(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(TF,"detectCycle");function $F(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s($F,"escapeRegExp");function ji(e){return new RegExp(`^${$F(e)}\\[(\\d+)\\]\\.(.+)$`)}s(ji,"repeatedRowKeyPattern");function Wb(e,t){let n=ji(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(Wb,"countRepeatedRows");function RF(e,t,n){let r=ji(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(RF,"repeatedRowHasData");function IF(e){return e.endsWith(".count")?e.slice(0,-6):e}s(IF,"readKeyOf");function Hb(e){return{sections:e,fields:[]}}s(Hb,"hiddenSectionsOnly");function OF(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??[])OF(r,t,n)}s(OF,"collectKeys");function PF(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;OF(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(ji)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(PF,"restrictedSectionsOf");function _F(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(_F,"matchesKey");function r4(e,t){return t.find(n=>_F(e,n))??null}s(r4,"hiddenSectionOfKey");function i4(e,t){for(let n=e;;){if(_F(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(i4,"fieldOwnsKey");function o4(e,t){return t.find(n=>i4(e,n))??null}s(o4,"restrictedFieldOfKey");function s4(e,t){let n=r4(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=o4(e,t.fields);return r===null?null:{kind:"field",field:r}}s(s4,"hiddenOwnerOfKey");function em(e,t){return s4(e,t)!==null}s(em,"isKeyHidden");function a4(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(a4,"visibleToListIssues");function NF(e,t,n){let r=[],i=s((c,u,f)=>{let m=c.visibleTo;m!==void 0&&r.push(...a4(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=PF(e);if(o.length===0)return r;let a=s((c,u,f)=>{if(c===void 0)return;let m=Hb(f);for(let y of kt(c)){let k=IF(y);(em(y,m)||em(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&&em(c.sameAs.source,Hb(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(NF,"sectionVisibilityIssues");var Lr="#";var CF=s(e=>{let t=kw.find(n=>n.systemColumn===e);return t===void 0&&N(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),fr={firstName:CF("persons.firstName"),lastName:CF("persons.lastName")};function DF(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===fr.firstName?n.firstName.push(o):a===fr.lastName&&n.lastName.push(o);return n}s(DF,"personNameKeys");function FF(e){return[...e.firstName,...e.lastName]}s(FF,"personNameKeyList");function LF(e){return e.firstName.length>0||e.lastName.length>0}s(LF,"hasPersonName");function Zs(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 Zs(i.subsections??[],a,i.id))r.push(l)}),r}s(Zs,"walkSections");function l4(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(l4,"findFieldInSection");function MF(e,t){for(let n of Zs(e.sections)){let r=l4(n.section,t);if(r)return{section:n.section,field:r}}return null}s(MF,"findField");var d4=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],c4=["blue","rose","amber","violet","teal","emerald","slate"];function qF(e){return d4.includes(e)}s(qF,"isBucketIconName");function KF(e){return c4.includes(e)}s(KF,"isBucketColorName");var u4="__clear__";function jF(e){return e===""?"empty":e===u4?"reserved":null}s(jF,"selectOptionValueDefect");var jIe=Object.freeze({});function f4(e,t){return Object.freeze($f(Vr,e,t))}s(f4,"formContextEntries");function BF(e){return e.env??[]}s(BF,"declaredContextKeys");function UF(e,t){return BF(e).every(n=>VF(n,t?.[n]))}s(UF,"scenarioContextComplete");function VF(e,t){return pO(Vr,e,t)}s(VF,"contextValueComplete");function GF(e,t){return f4(t??{},BF(e))}s(GF,"scenarioContextEntries");function Jb(e){return wl(e)}s(Jb,"isContextIdentifier");function p4(e,t,n){let r=Tf(Vr,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(p4,"contextIdentifierIssue");var Yb=qu("stage.key");function m4(e){let t=[],n=s(i=>i.kind==="ident"&&i.path===Yb,"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(m4,"stageKeyLiterals");function zF(e,t,n){return t===void 0?[]:m4(e).filter(r=>!t.has(r)).map(r=>HF(r,t,n))}s(zF,"stageKeyAstIssues");function WF(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(HF(i.key,t,`scenario:${r.id}/env`))}return n}s(WF,"scenarioStageKeyIssues");function HF(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.")+` \`${Yb}\` 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.")+` \`${Yb}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(HF,"unknownStageKeyIssue");function YF(e,t,n){let r=[];for(let i of kt(e)){if(!Jb(i))continue;let o=p4(i,t,n);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Ny(e,Lu))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(YF,"contextAstIssues");function JF(e,t){let n=[...h4(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!as(i)){n.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${ss.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${ss.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=>as(a)&&!VF(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??{}))as(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(JF,"formContextIssues");function h4(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(h4,"retiredContextFields");var Qb=N_.docRef.allowedMime;function tL(e,t={}){let n=Fs(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(O,I){if(i.has(O))return;i.add(O);let B=o.get(O.id);B&&B!==O?r.push({severity:"error",path:`sections[${I.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${O.id}' ist mehrfach deklariert.`,en:`Section id '${O.id}' is declared more than once.`}}):o.set(O.id,O);let D=`sections[${I.join(".")}]`;O.fields.forEach((Z,le)=>{Xs(a,Z.key,`${D}.fields[${le}]`,"duplicate.field-key",r),l.add(Z.key),u.set(Z.key,Z),c.set(Z.key,Xb(Z)),Z.externalFlag&&(Z.type!=="boolean"&&r.push({severity:"error",path:`${D}.fields[${le}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${Z.key}' muss den Typ 'boolean' haben (ist '${Z.type}').`,en:`External flag '${Z.key}' must be type 'boolean' (got '${Z.type}').`}}),Z.notice!==void 0&&r.push({severity:"error",path:`${D}.fields[${le}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${Z.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${Z.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),Z.defaultValue==null&&r.push({severity:"error",path:`${D}.fields[${le}]`,code:"flag.missing-default",message:{de:`Externes Flag '${Z.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${Z.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...QF(Z,`${D}.fields[${le}]`))}),O.groups?.forEach((Z,le)=>{Z.fields.forEach((ue,xe)=>{Xs(a,ue.key,`${D}.groups[${le}].fields[${xe}]`,"duplicate.field-key",r),l.add(ue.key),u.set(ue.key,ue),c.set(ue.key,Xb(ue)),ue.externalFlag&&r.push({severity:"error",path:`${D}.groups[${le}].fields[${xe}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ue.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${ue.key}' must be a direct section field, not a group field.`}}),r.push(...QF(ue,`${D}.groups[${le}].fields[${xe}]`))})}),O.repeated?.forEach((Z,le)=>{Z.itemTemplate.forEach((ue,xe)=>{Xs(a,ue.key,`${D}.repeated[${le}].itemTemplate[${xe}]`,"duplicate.field-key",r),c.set(ue.key,Xb(ue)),ue.externalFlag&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ue.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${ue.key}' must be a direct section field, not a repeated item field.`}}),ue.export&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"export.in-repeated",message:{de:`Feld '${ue.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${ue.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),ue.sameAs&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${ue.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${ue.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),ue.notice!==void 0&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"config.notice-in-repeated",message:{de:`Feld '${ue.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 '${ue.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),ue.type==="docRef"&&ue.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${D}.repeated[${le}].itemTemplate[${xe}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${ue.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${ue.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),O.computed?.forEach(Z=>{d.add(Z.key),Xs(a,Z.key,`${D}.computed[${Z.key}]`,"duplicate.field-key",r),Z.export===!0&&Z.exportType===void 0&&r.push({severity:"error",path:`${D}.computed[${Z.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${Z.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${Z.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),O.subsections?.forEach((Z,le)=>f(Z,[...I,le]))}s(f,"visitRawSection"),e.sections.forEach((O,I)=>f(O,[I]));let m=new Set;n.effects.forEach((O,I)=>{Xs(m,O.id,`effects[${I}]`,"duplicate.effect-id",r)});let y=new Set;n.outcomes.forEach((O,I)=>{Xs(y,O.id,`outcomes[${I}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((O,I)=>{O.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 '${O.id}' verweist auf den unbekannten Effekt '${B.effect}'.`,en:`Outcome '${O.id}' references unknown effect '${B.effect}'.`}})})}),n.outcomes.forEach((O,I)=>{O.output.fields?.forEach((B,D)=>{MF(n,B.path)||r.push({severity:"error",path:`outcomes[${I}].output.fields[${D}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${O.id}' verweist auf das unbekannte Feld '${B.path}'.`,en:`Outcome '${O.id}' references unknown field '${B.path}'.`}})})});let k=new Set;for(let O of Zs(n.sections))for(let I of O.section.repeated??[])k.add(`${I.key}.count`);for(let O of k)(a.has(O)||d.has(O))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${O}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${O}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let g={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...JF(e)),r.push(...NF(e,n,t.visibleToKeys)),r.push(...WF(e,t.stageKeys));for(let O of Zs(n.sections)){let I=O.section,B=`sections[${O.path.join(".")}]`;I.visibleIf&&(pr(I.visibleIf,`${B}.visibleIf`,g,!1,r),ea(I.visibleIf,`${B}.visibleIf`,c,r)),I.fields.forEach((D,Z)=>Zb(D,`${B}.fields[${Z}]`,g,!1,c,r)),I.groups?.forEach((D,Z)=>{D.visibleIf&&(pr(D.visibleIf,`${B}.groups[${Z}].visibleIf`,g,!1,r),ea(D.visibleIf,`${B}.groups[${Z}].visibleIf`,c,r)),D.fields.forEach((le,ue)=>Zb(le,`${B}.groups[${Z}].fields[${ue}]`,g,!1,c,r))}),I.repeated?.forEach((D,Z)=>{D.itemVisibleIf&&(pr(D.itemVisibleIf,`${B}.repeated[${Z}].itemVisibleIf`,g,!0,r),ea(D.itemVisibleIf,`${B}.repeated[${Z}].itemVisibleIf`,c,r)),D.itemTemplate.forEach((le,ue)=>Zb(le,`${B}.repeated[${Z}].itemTemplate[${ue}]`,g,!0,c,r)),D.effects?.forEach((le,ue)=>{le.when&&pr(le.when,`${B}.repeated[${Z}].effects[${ue}].when`,g,!0,r)})}),I.computed?.forEach((D,Z)=>pr(D.expression,`${B}.computed[${Z}].expression`,g,!1,r))}n.effects.forEach((O,I)=>{O.when&&pr(O.when,`effects[${I}].when`,g,!1,r)}),n.outcomes.forEach((O,I)=>{pr(O.when,`outcomes[${I}].when`,g,!1,r)});let v=new Set(n.outcomes.map(O=>O.id));function $(O,I){O.requiredFor&&O.requiredFor.forEach((B,D)=>{v.has(B)||r.push({severity:"error",path:`${I}.requiredFor[${D}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${O.key}": requiredFor verweist auf das unbekannte Ergebnis "${B}"`,en:`field "${O.key}": requiredFor references unknown outcome "${B}"`}})})}s($,"checkRequiredFor");for(let O of Zs(n.sections)){let I=O.section,B=`sections[${O.path.join(".")}]`;I.fields.forEach((D,Z)=>$(D,`${B}.fields[${Z}]`)),I.groups?.forEach((D,Z)=>{D.fields.forEach((le,ue)=>$(le,`${B}.groups[${Z}].fields[${ue}]`))}),I.repeated?.forEach((D,Z)=>{D.itemTemplate.forEach((le,ue)=>$(le,`${B}.repeated[${Z}].itemTemplate[${ue}]`))})}function R(O,I){let B=s((D,Z)=>{let le=(D.type==="docRef"?D.docRefConstraints?.mimeType??[]:[]).filter(xe=>!Qb.includes(xe));le.length>0&&r.push({severity:"error",path:Z,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${D.key}' erlaubt ${le.map(xe=>`'${xe}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${Qb.join(", ")}).`,en:`Field '${D.key}' allows ${le.map(xe=>`'${xe}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${Qb.join(", ")}).`}}),D.multiple===!0&&D.type!=="enum"&&r.push({severity:"error",path:Z,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:Z,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:Z,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:Z,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 ue=D.enumRef;ue!==void 0&&r.push({severity:"error",path:`${Z}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${D.key}' nennt den entfernten Options-Katalog (enumRef '${String(ue)}'). 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(ue)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(D.enumOptions??[]).forEach((xe,Ge)=>{let ft=jF(xe);ft!==null&&r.push({severity:"error",path:`${Z}.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:`${Z}.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!=="",it=xe.url!==void 0&&xe.url!=="";ft===it&&r.push({severity:"error",path:`${Z}.attachments[${Ge}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${D.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${ft&&it?"beide":"keines"}).`,en:`Field '${D.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${ft&&it?"both":"neither"}).`}}),xe.renderAs==="inlineLink"&&xe.label===void 0&&r.push({severity:"error",path:`${Z}.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");O.fields.forEach((D,Z)=>B(D,`${I}.fields[${Z}]`)),O.groups?.forEach((D,Z)=>{D.fields.forEach((le,ue)=>B(le,`${I}.groups[${Z}].fields[${ue}]`))}),O.repeated?.forEach((D,Z)=>{D.itemTemplate.forEach((le,ue)=>B(le,`${I}.repeated[${Z}].itemTemplate[${ue}]`))}),O.subsections?.forEach((D,Z)=>R(D,`${I}.subsections[${Z}]`))}s(R,"visitFieldConfig"),e.sections.forEach((O,I)=>R(O,`sections[${I}]`)),e.effects.forEach((O,I)=>{if(O.kind==="person"){r.push(...eL(O,e.effects,`effects[${I}]`,B=>l.has(B)));return}O.kind==="organization"&&O.nameFrom?.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nameFrom[${D}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${O.id}': nameFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${O.id}' nameFrom references unknown field '${B}'.`}})})});let A=s((O,I)=>{if(O.kind!=="person"&&O.kind!=="organization")return;let B=O.display;if(!B){r.push({severity:"error",path:`${I}.display`,code:"display.missing",message:{de:`Effekt '${O.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${O.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}qF(B.icon)||r.push({severity:"error",path:`${I}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${O.id}': display.icon '${B.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${O.id}' display.icon '${B.icon}' is not a known bucket icon.`}}),KF(B.color)||r.push({severity:"error",path:`${I}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${O.id}': display.color '${B.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${O.id}' display.color '${B.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((O,I)=>A(O,`effects[${I}]`));let P=new Set,L=s(O=>{O.kind==="person"?P.add(O.bucket):O.kind==="organization"&&P.add(O.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(L);let b=new Set,E=s(O=>{for(let I of O)I.repeated?.forEach(B=>B.effects?.forEach(D=>L(D))),E(I.subsections??[])},"collectRepeatedBuckets");E(e.sections);let q=s((O,I)=>{P.size!==0&&O.forEach((B,D)=>{B.bucket===void 0||P.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((O,I)=>{if(b.has(O))return;b.add(O);let B=`sections[${I.join(".")}]`;q(O.fields,`${B}.fields`),O.groups?.forEach((D,Z)=>q(D.fields,`${B}.groups[${Z}].fields`)),O.repeated?.forEach((D,Z)=>q(D.itemTemplate,`${B}.repeated[${Z}].itemTemplate`)),O.subsections?.forEach((D,Z)=>_(D,[...I,Z]))},"visitBucketSection");e.sections.forEach((O,I)=>_(O,[I]));let Y=e.effects.flatMap((O,I)=>O.kind==="person"&&O.subject===!0?[{e:O,i:I}]:[]);Y.length>1&&Y.slice(1).forEach(({e:O,i:I})=>{r.push({severity:"error",path:`effects[${I}].subject`,code:"subject.duplicate",message:{de:`Effekt '${O.id}' deklariert subject:true, aber '${Y[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${O.id}' declares subject:true, but '${Y[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((O,I)=>{if(!(O.kind!=="person"||O.nationalityFrom===void 0)){if(O.subject!==!0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${O.id}' deklariert nationalityFrom, ist aber nicht das Subjekt der Bewerbung \u2014 die Staatsangeh\xF6rigkeit wird nur f\xFCr das Subjekt der Bewerbung gelesen.`,en:`Effect '${O.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(O.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${I}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${O.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${O.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}O.nationalityFrom.forEach((B,D)=>{l.has(B)||r.push({severity:"error",path:`effects[${I}].nationalityFrom[${D}]`,code:"nationality.unknown-field",message:{de:`Effekt '${O.id}': nationalityFrom verweist auf das unbekannte Feld '${B}'.`,en:`Effect '${O.id}' nationalityFrom references unknown field '${B}'.`}})})}});let H=e.effects.flatMap((O,I)=>O.kind==="person"&&O.contractParty!==void 0?[{e:O,i:I,decl:O.contractParty}]:[]);if(H.length>0){let O=H.filter(({decl:I})=>I.role==="beneficiary");O.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 '${O[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${I.id}' declares contractParty.role 'beneficiary', but '${O[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),O.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}'.`}})}),Y.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.`}})}),H.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((O,I)=>{O.kind==="fieldMap"&&O.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 '${O.id}': fieldMap from '${B.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${O.id}' fieldMap from '${B.from}' references unknown field.`}})})});for(let[O,I]of u){if(!I.sameAs)continue;let B=`fields[${O}].sameAs`,D=u.get(I.sameAs.source);D===void 0||I.sameAs.source===O?r.push({severity:"error",path:`${B}.source`,code:"ref.unknown-sameas-source",message:{de:I.sameAs.source===O?`Feld '${O}': sameAs.source verweist auf sich selbst.`:`Feld '${O}': sameAs.source verweist auf das unbekannte Feld '${I.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:I.sameAs.source===O?`Field '${O}' sameAs.source references itself.`:`Field '${O}' 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 '${O}' (${I.type}): sameAs.source '${I.sameAs.source}' hat einen anderen Typ (${D.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${O}' (${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 '${O}': sameAs.source '${I.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${O}' sameAs.source '${I.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let Z=u.get(I.sameAs.toggle);(Z===void 0||Z.type!=="boolean")&&r.push({severity:"error",path:`${B}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:Z===void 0?`Feld '${O}': sameAs.toggle verweist auf das unbekannte Feld '${I.sameAs.toggle}'.`:`Feld '${O}': sameAs.toggle '${I.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${Z.type}').`,en:Z===void 0?`Field '${O}' sameAs.toggle references unknown field '${I.sameAs.toggle}'.`:`Field '${O}' sameAs.toggle '${I.sameAs.toggle}' must be type 'boolean' (got '${Z.type}').`}}),I.required===!0&&r.push({severity:"error",path:`fields[${O}].required`,code:"config.sameas-static-required",message:{de:`Feld '${O}' deklariert sameAs, ist aber statisch Pflicht \u2014 solange es gespiegelt ist, hat es keinen eigenen Wert, die Slice-Validierung beim Commit w\xFCrde immer scheitern. required: false + requiredIf: "${I.sameAs.toggle} != true" verwenden.`,en:`Field '${O}' declares sameAs but is statically required \u2014 while mirrored it holds no own value, so commit-time slice validation would always fail. Use required: false + requiredIf: "${I.sameAs.toggle} != true".`}})}{let O=new Map;e.effects.forEach(I=>O.set(I.id,I.kind)),e.effects.forEach((I,B)=>{if(I.kind!=="shareValue")return;[["from",I.from],["to",I.to]].forEach(([le,ue])=>{let xe=O.get(ue.slice(1));xe!==void 0&&xe!=="person"&&xe!=="organization"&&r.push({severity:"error",path:`effects[${B}].${le}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${I.id}': shareValue ${le} '${ue}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${xe}').`,en:`Effect '${I.id}' shareValue ${le} '${ue}' must reference a person/organization effect (got '${xe}').`}})});let D=I.from.slice(1);e.effects.some(le=>le.kind==="fieldMap"&&le.target.slice(1)===D&&le.mappings.some(ue=>ue.to===I.field)||le.kind==="shareValue"&&le.id!==I.id&&le.to.slice(1)===D&&le.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((O,I)=>{O.kind==="person"&&O.bucket.includes(Lr)&&r.push({severity:"error",path:`effects[${I}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': bucket '${O.bucket}' darf '${Lr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' bucket '${O.bucket}' must not contain '${Lr}' (reserved for the per-row namespace).`}}),O.kind==="organization"&&O.orgKind.includes(Lr)&&r.push({severity:"error",path:`effects[${I}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': orgKind '${O.orgKind}' darf '${Lr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' orgKind '${O.orgKind}' must not contain '${Lr}' (reserved for the per-row namespace).`}})});let pe=new Set;function te(O,I){O.repeated?.forEach((B,D)=>{let Z=B.effects??[];if(Z.length>0){let le=`${I}.repeated[${D}]`,ue=new Set(Z.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"),it=s(ie=>ie.startsWith("$item.")?xe.has(ie.slice(6)):a.has(ie),"resolvesFrom"),Ht=s(ie=>{let Nt=ie.slice(1);return ue.has(Nt)||m.has(Nt)},"resolvesRef");Z.forEach((ie,Nt)=>{let pt=`${le}.effects[${Nt}]`;if(m.has(ie.id)||pe.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.`}}):pe.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:le,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(Lr)&&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 '${Lr}' nicht enthalten.`,en:`Repeated effect '${ie.id}' ${ie.kind==="person"?"bucket":"orgKind"} '${Ne}' must not contain '${Lr}'.`}}),ie.kind==="person"&&r.push(...eL(ie,Z,pt,ft)),ie.kind==="organization"&&ie.nameFrom?.forEach((Ue,In)=>{ft(Ue)||r.push({severity:"error",path:`${pt}.nameFrom[${In}]`,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,In)=>{it(Ue)||r.push({severity:"error",path:`${pt}.identity.keyFrom[${In}]`,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)=>{it(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.`}})})}}),O.subsections?.forEach((B,D)=>te(B,`${I}.subsections[${D}]`))}s(te,"visitRepeatedEffects"),e.sections.forEach((O,I)=>te(O,`sections[${I}]`));let oe=TF(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(...g4(e)),r}s(tL,"validateForm");function g4(e){let t={...e,effects:e.effects.map(nL),sections:e.sections.map(rL),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return Df(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:jy(n)}))}s(g4,"missingTranslationIssues");function nL(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(nL,"withoutSubjectFlag");function rL(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(nL)})),subsections:e.subsections?.map(rL)}}s(rL,"withoutRowSubjectFlags");function QF(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(QF,"exportGateIssues");function Xs(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${ZF(r,"de")} '${t}'`,en:`Duplicate ${ZF(r,"en")}: '${t}'`}}):e.add(t)}s(Xs,"reportIfDup");function ZF(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(ZF,"labelForCode");function Zb(e,t,n,r,i,o){e.visibleIf&&(pr(e.visibleIf,`${t}.visibleIf`,n,r,o),ea(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(pr(e.requiredIf,`${t}.requiredIf`,n,r,o),ea(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(pr(e.disabledIf,`${t}.disabledIf`,n,r,o),ea(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&pr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(Zb,"checkFieldAsts");function Xb(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo"}}s(Xb,"gatingMeta");function ea(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(XF(o.left,o.right,o.op,t,n,r),XF(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(ea,"checkGatingExpr");function XF(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(XF,"inspectEqualityOperand");function pr(e,t,n,r,i){i.push(...YF(e,n.declaredContext,t)),i.push(...zF(e,n.stageKeys,t));for(let o of kt(e))n.known.has(o)||Jb(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(pr,"checkAst");function eL(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 ${fr.firstName} / ${fr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${fr.firstName} / ${fr.lastName}. Remove nameFrom.`}});let o=DF(e.id,t);LF(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${fr.firstName} oder ${fr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${fr.firstName} or ${fr.lastName} \u2014 the person would get no name.`}});for(let a of FF(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(eL,"personNameIssues");var y4="blocked";function iL(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(w4(i))return r.id===y4?null:r.id}return null}s(iL,"resolveActiveOutcome");function w4(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(w4,"truthy");function oL(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(oL,"isScalar");function k4(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(oL(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))oL(a)&&(t[`${r}.${o}`]=a)}b4(e,t,n)}s(k4,"mergeRecord");function b4(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);ji(a).test(i)&&r.add(a)}for(let i of r){let o=Wb(e,i),a=0;for(let l=0;l<o;l++)RF(e,i,l)&&a++;t[`${i}.count`]=a}}s(b4,"mergeRepeatedCounts");function sL(e,t,n){let r={...n};return k4(e,r,t),r}s(sL,"flattenValues");function ev(e,t,n){return{code:e,fieldKey:t,text:n}}s(ev,"submitIssue");function aL(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(aL,"truthyEval");function lL(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(lL,"isEmptyValue");function v4(e,t,n){let r=!!e.required;if(!r&&e.requiredIf)try{r=aL(gt(e.requiredIf,{values:t}))}catch{r=!1}return r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(v4,"fieldIsLiveRequired");function x4(e,t,n){return dL(e,t,n).evalCtx}s(x4,"buildSubmitEvalContext");function dL(e,t,n){let r=S4(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=cL(e,l,n),c=new Set,u=new Set;fL(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(dL,"splitWithContext");function S4(e){let t=new Map,n=[];for(let r of nm(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:ji(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(S4,"fieldOwnership");function cL(e,t,n){let r=[];for(let o of nm(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=sL(t,r,n);for(let o of nm(e.sections))for(let a of o.computed??[])try{i[a.key]=gt(a.expression,{values:i})}catch{}return i}s(cL,"rawEvalContext");function uL(e,t,n){let{values:r,defaulted:i}=A4(e,t,n),o=dL(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(uL,"splitDraftValues");function A4(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of nm(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??=cL(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(A4,"applyFieldDefaults");function nm(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(nm,"walkSectionsDeep");function E4(e,t,n,r=!1){if(lL(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(E4,"fieldFormatIssue");function tm(e,t){if(!e)return!0;try{return aL(gt(e,{values:t}))}catch{return!1}}s(tm,"isVisibleUnder");function fL(e,t,n,r){let i=s(o=>{if(tm(o.visibleIf,t)){for(let a of o.fields)tm(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(tm(a.visibleIf,t))for(let l of a.fields)tm(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(fL,"forEachVisibleField");function pL(e,t,n,r={}){let i=x4(e,t,n),o=[],a=iL(e,i);a===null&&r.requireOutcome!==!1&&o.push(ev("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 fL(e,i,d=>{let c=t[d.key];if(lL(c)){!l.has(d.type)&&v4(d,i,a)&&o.push(ev("required",d.key,Ba([d.label],([f],m)=>m==="de"?`${f} ist ein Pflichtfeld.`:`${f} is a required field.`)));return}if(!r.registry)return;let u=E4(d,c,r.registry,r.testMode===!0);u!==null&&o.push(ev("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(pL,"checkSubmittable");function mL(e){let t=e.testScenarios??[];if(t.length===0)return[];let{compiled:n}=Fs(e),r=[];for(let i of t){let o=i.prefill??{};if(!UF(e,i.env))continue;let a=GF(e,i.env),{visible:l}=uL(n,o,a),d=pL(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:Ba([i.label,c.text],([u,f],m)=>m==="de"?`Szenario "${u}": ${f}`:`Scenario "${u}": ${f}`)})}}return r}s(mL,"validateScenarios");function rm(e){return e.filter(t=>(t.severity??"error")==="error")}s(rm,"blockingIssues");function im(e,t={}){return[...tL(e,t),...mL(e)]}s(im,"runFormValidators");function om(e){return rm(e)}s(om,"blockingFormErrors");function hL(e,t,n){return AP(e,t,n)}s(hL,"runWorkflowValidators");function gL(e){return rm(e)}s(gL,"blockingWorkflowErrors");var T4=["artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],yL={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"]}},cn={id:w.string(),label:Bs,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())},$4=w.object({...cn,type:w.literal("join")}),R4=w.object({...cn,type:w.literal("end")}),I4=w.object({...cn,type:w.literal("eventTrigger")}),O4=w.object({...cn,type:w.literal("form"),adoptForm:w.optional(w.any()),formExports:w.optional(w.any())}),P4=w.object({...cn,type:w.literal("roleAssign")}),_4=w.object({...cn,type:w.literal("setFlag")}),N4=w.object({...cn,type:w.literal("if"),condition:w.optional(w.any())}),C4=w.object({...cn,type:w.literal("countersign"),contract:w.optional(w.any()),signing:w.optional(w.any()),titles:w.optional(w.any())}),D4=w.object({...cn,type:w.literal("engagePush"),contract:w.optional(w.any()),engage:w.optional(w.any()),form:w.optional(w.any()),payment:w.optional(w.any())}),F4=w.object({...cn,type:w.literal("decision"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any()),requiresOneOf:w.optional(w.any())}),L4=w.object({...cn,type:w.literal("review"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any())}),M4=w.object({...cn,type:w.literal("waitlist")}),q4=w.object({...cn,type:w.literal("completenessCheck"),deadline:w.optional(w.any()),requires:w.optional(w.any())}),K4=w.object({...cn,type:w.literal("collectPayment")}),j4=w.object({...cn,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())}),WOe=w.union($4,R4,I4,O4,P4,_4,N4,C4,D4,F4,L4,M4,q4,K4,j4);function wL(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 yL)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=yL[a],d=new Set(["id","type","label",...T4,...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(wL,"workflowNodeEnvelopeIssues");function kL(e,t){return e.enumOptionLabels?.[t]??{de:t,en:t}}s(kL,"inlineEnumOptionLabel");var vL={string:"string",boolean:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function xL(e){return vL[e]!==void 0}s(xL,"isExportableFieldType");function B4(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(B4,"leafForComputed");function bL(e){let t=vL[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:kL(e,n)}))}:{}}}s(bL,"leafFor");function tv(e){let t=[],n=s(r=>{for(let i of r.fields)i.export===!0&&t.push(bL(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&t.push(bL(o));for(let i of r.computed??[])i.export===!0&&t.push(B4(i));for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(tv,"exportedFormLeaves");var SL=s(e=>e,"asEffectId"),Bi=s(e=>e,"asOutcomeId"),ta=s(e=>e,"asSectionId"),tn=s(e=>e,"asFieldKey");var ri=["string","boolean","date","enum","email","tel","address","docRef"],gd=["person","organization","relationship","fieldMap"],Ui=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],na=["fresh","keyed","manual"];function Co(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(Co,"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 yd(e){return Object.keys(e.smartforms??{})}s(yd,"carriedFormSlugs");function nv(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(nv,"boundFormSlugs");function sm(e,t){let n=yd(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(sm,"resolveFormSlug");function am(e,t){let n=e.smartforms?.[t];if(!n)throw new Error(`offer form: smartform "${t}" not found in bundle`);return n}s(am,"getForm");function qn(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(qn,"walkSections");function er(e,t){return qn(e).find(n=>n.id===t)}s(er,"findSection");function Do(e,t){for(let n of qn(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Do,"findField");function Fo(e){let t=new Set;for(let n of qn(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(Fo,"allFieldKeys");function U4(e){let t=ct(e.label,e.labelEn,"offer form add"),n={id:ta("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Bi("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(U4,"buildSkeletonSmartForm");function lm(e,t){let{key:n,label:r}=t;if(yd(e).includes(n))throw new Error(`offer form add: smartform "${n}" already exists in this bundle`);let i=U4({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(lm,"addForm");function AL(e,t){if(!yd(e).includes(t))throw new Error(`offer form rm: smartform "${t}" not found in bundle`);if(nv(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(AL,"removeForm");function EL(e,t){let n=am(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(EL,"setForm");function TL(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(TL,"nodesOf");function $L(e,t,n){let r=TL(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($L,"nodeOf");function RL(e){return e.flatMap(t=>{if(t.type!=="form"||wn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(RL,"creatingFormNodes");function IL(e){return om(im(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(IL,"formErrors");function dm(e){let t="offer workflow restamp-exports",n=TL(e,t),r=[];for(let{node:i,slug:o}of RL(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=IL(l);if(d.length>0)throw new Error(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
9762
9762
  ${d.join(`
9763
9763
  `)}`);let c=tv(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"&&wn(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(dm,"restampFormExports");function OL(e){let t=e.workflow?.graph?.nodes??[];return RL(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 IL(o).length>0?[]:Pe(n.formExports)===Pe(tv(o))?[]:[{node:n.id,form:r}]})}s(OL,"staleFormExports");var rv=["string","number","boolean","date"];function PL(e,t){let n="offer form field export";for(let r of qn(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&&!xL(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 (${rv.join("|")}); an expression has none to infer`);if(!rv.includes(d))throw new Error(`${n}: --type "${d}" is no computed export type (${rv.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(PL,"setFieldExport");function _L(e,t,n){let r="offer workflow node set-generator",i=$L(e,t,r);if(Qp(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=zr(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!==Ln);return{before:l,after:{key:a,kind:n.kind},droppedStamp:c,keptParameterCells:u}}s(_L,"setGeneratorPin");function NL(e,t,n){let r="offer workflow node set-cockpit-fields",i=$L(e,t,r),o=Qp(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"?zr(i)!==null:ar(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(NL,"setCockpitFields");var V4=new Set(["graph","progressLayout","progressWiring"]);function CL(e){let{label:t,...n}=e;return n}s(CL,"definitionOf");function G4(e){let t=[];for(let o of Object.keys(e))V4.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(J$.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(...wL(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(G4,"workflowShapeIssues");function DL(e){let t=e.nodes??[],n=new Map;for(let r of t){let i=BR(r);i!==void 0&&n.set(r.id,i)}return n}s(DL,"formNodeSlugById");function z4(e,t){let n=e.smartforms??{},r=new Map;for(let[i,o]of DL(t)){let a=n[o];if(a===void 0)return;r.set(i,CL(a))}return HO(r)}s(z4,"readinessContext");function W4(e){return[...DL(e).values()]}s(W4,"formNodeSlugs");function cm(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(cm,"describe");function Tn(e){let t=[];for(let l of Bu(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 vp(e.index.program?.stages??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of Ap(e.index.program?.runs??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of Ep(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 G4(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 Y$(d))t.push({severity:"error",area:"workflow",message:v});let u=[];for(let{node:v,key:$,kind:R}of Zp(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 ${ar(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 OL(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=z4(e,l),m=s(v=>{let $=hL(v,{layout:d,wiring:c},f),R=new Set(gL($));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 P of v.nodes)u.includes(P.id)&&(P.generatorStamp={...P.generatorStamp??{},parts:[{partKey:"?"}]});let $=m(v),R=new Set($.issues.filter($.isError).map(cm)),A=s(P=>u.some(L=>P.includes(`$node.${L}.contract`)),"namesOutput");for(let P of y){let L=cm(P);k(P)&&!R.has(L)&&A(L)&&g.add(L)}}for(let v of y){let $=cm(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=CL(d);for(let k of Q$(u,`smartforms/${l}.json`))t.push({severity:"error",area:"smartform",message:k.de});let f=u,m=im(f,{stageKeys:a}),y=new Set(om(m));for(let k of m)t.push({severity:y.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${cm(k)}`});for(let k of[...EF(f),...AF(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(W4(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(Tn,"validateBundle");async function iv(e,t,n){let r=Zp(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}H$(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(iv,"stampResolverPins");async function ov(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=ar(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=ar(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(lD(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(ov,"stampTemplatePins");async function FL(e,t,n){let r=Ke(n),i=await iv(e,t,r),o=await ov(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");Sn(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=Tn(r).filter(f=>f.severity==="error"&&c(f.message));return{rows:a,refused:[],open:u}}s(FL,"restampPinsOnDisk");var H4=G.join("contract","resolver-setup.json"),ii="resolver setup",ra=s((e,t)=>Rt(e,t,ii),"record"),Vi=s((e,t)=>Ve(e,t,ii),"text");function Y4(e,t){let n=ra(e,"Datei"),r=ra(n.contractTemplate,"contractTemplate"),i=ra(n.resolver,"resolver");return{dir:t,contractTemplate:{key:Vi(r.key,"contractTemplate.key"),name:ln(r.name,"contractTemplate.name",ii,"Vorlagennamen"),file:Vi(r.file,"contractTemplate.file"),role:Vi(r.role,"contractTemplate.role")},revenueAccounts:Gf(n.revenueAccounts,ii),billingItems:zf(n.billingItems,ii),resolver:{key:Vi(i.key,"resolver.key"),name:ln(i.name,"resolver.name",ii,"Generatornamen"),description:i.description===void 0?null:ln(i.description,"resolver.description",ii,"Beschreibungen"),legalText:i.legalText??{},source:Vi(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:Nn(i.feeGroups,"resolver.feeGroups",ii)).map((o,a)=>{let l=ra(o,`resolver.feeGroups[${a}]`);return{key:Vi(l.key,"feeGroup.key"),name:ln(l.name,"feeGroup.name",ii,"Geb\xFChrengruppen"),billingItemKeys:sv(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:sv(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:sv(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:J4(i.scenarios??[]),config:ra(i.config,"resolver.config")}}}s(Y4,"parseResolverSetup");function sv(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(sv,"stringList");function J4(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=ra(t,"scenario");if(!("input"in n)||!("expected"in n))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:Vi(n.key,"scenario.key"),input:n.input,expected:n.expected}})}s(J4,"parseScenarios");function um(e){let t=G.resolve(e);return Y4(JSON.parse(ye(t,"utf8")),G.dirname(t))}s(um,"readResolverSetup");function Q4(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(Q4,"configValue");function LL(e){let t=s(()=>Vi(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),n=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...av(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"?Q4(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(LL,"billingSetupPayload");function ML(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(ML,"billingItemRef");function av(e){if(Array.isArray(e))return e.flatMap(av);if(typeof e!="object"||e===null)return[];let t=ML(e);return t!==void 0?[t]:Object.values(e).flatMap(av)}s(av,"billingItemRefs");function lv(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=ML(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(lv,"renderResolverConfig");function Z4(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(Z4,"assertPlaceholderParity");function X4(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(X4,"matchingSealedRevision");async function wd(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 Al(G.join(n.dir,n.contractTemplate.file));Z4(n.resolver.config,i);let o=await e.query(S.contractSetup.planBillingSetup,{client:t,...LL(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(P=>P.configKey===R);if(A===void 0)throw new Error(`Unknown grant template ${R}`);c[R]=A.id}let u=lv(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:X4([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(wd,"planResolverSetup");async function qL(e,t,n){let r=await wd(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,...LL(n)});if(r.match)return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}};let o=r.template.upload?await Vf(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:lv(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(`
9764
9764
  `));if(d=c.sourceRevision,await e.mutation(S.contractGeneratorRevisions.approveScenarios,{client:t,id:a,expectedSourceRevision:d,artifactHash:c.artifactHash,scenarios:lv({scenarios:n.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await e.mutation(S.contractGeneratorRevisions.seal,{client:t,id:a,expectedSourceRevision:d}),(await wd(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(qL,"applyResolverSetup");async function dv(e,t,n){let r=G.join(n.dir,H4);if(!Ae(r)||n.workflow===void 0)return[];let i=um(r);if((await wd(e,t,i)).match===void 0)throw new Error("Apply the generator setup before publishing the offer.");return[]}s(dv,"pinSetupRevisions");function e6(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(e6,"nodeText");function kd(e,t){let n=[],r=[],i=[],o={},a=t.progressEvents??[],l=e6(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=t6(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(kd,"deriveProgressEntriesForNode");function fm(e){return Object.entries(e).filter(([,t])=>t.outcome==="approved").map(([t])=>t)}s(fm,"seatedTerminalStates");function t6(e,t){return e.scope==="global"?`col.${e.key}`:`${t}.${e.key}`}s(t6,"columnIdFor");function KL(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(KL,"orderProcessColumns");var tr=s((e,t)=>({de:e,en:t}),"lt"),uv=os("start",[]),pm=os("form",[uv]),cv=os("end",[uv,pm]);function n6(e){let t=[kd({id:pm,type:"form",label:tr("Formular","Form")},No.form),kd({id:cv,type:"end",label:tr("Ende","End")},No.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=fm(o);return{layout:{id:`layout.${e}.starter`,buses:[{key:"process",states:n,terminalSemantics:o,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:tr("Prozess","Process"),audience:"both",columns:r}]}]},wiring:{mappings:i}}}s(n6,"buildStarterProgress");function jL(e){let{slug:t,title:n,tenant:r,unit:i,responsible:o}=e,a=t,l=`${t}-form`,d=`${t}-flow`,c=[{id:uv,type:"eventTrigger",label:tr("Start","Start"),sublabel:tr("Eingang externer Bewerber-Aktion","Incoming external applicant action"),next:{bewerbungOffen:{to:pm}}},{id:pm,type:"form",label:n,sublabel:tr("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:tr("Standard","Standard")}],next:{standard:{to:cv}},notifications:{submitted:{templateId:"applicant.applicationSubmitted"}}},{id:cv,type:"end",label:tr("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"}}}],u={nodes:c,assignmentRules:NO(DO([{slot:"responsible",rules:[{when:Ni,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:o}}]}],Pf({nodes:c})))},{layout:f,wiring:m}=n6(d),y={id:ta("section.applicant"),label:tr("Antragsteller","Applicant"),fields:[{key:tn("applicant.vorname"),label:tr("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:tn("applicant.nachname"),label:tr("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},k=[{id:Bi("standard"),label:tr("Standard","Standard"),when:"true",output:{fields:[{path:tn("applicant.vorname")},{path:tn("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(jL,"buildSkeletonBundle");var Lo={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 nn(e,t,n){return e.query(S.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0})}s(nn,"loadConfig");function fv(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(fv,"resolveUnitId");function ia(e,t){let n=BL(e),r=e.runs.find(i=>i.key===ei(n,t));if(!r)throw new Error(`offer: run "${t}" not found. Available keys: ${e.runs.map(i=>fC(n,i.key)).join(", ")||"(none)"}`);return r.runId}s(ia,"resolveRunId");function oa(e,t){let n=BL(e),r=e.stages.find(i=>i.key===tb(n,t));if(!r)throw new Error(`offer: level "${t}" not found. Available keys: ${e.stages.map(i=>Cr(n,i.key)).join(", ")||"(none)"}`);return r.stageId}s(oa,"resolveStageId");function BL(e){if(e.programKey===null)throw new Error("offer: the offer has no program yet \u2014 link a unit first");return e.programKey}s(BL,"requireProgramKey");async function pv(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(pv,"linkUnit");function Mo(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(Mo,"parsePositiveInt");var sa=s((e="Offer slug (required)")=>p.String("--offer",{description:e}),"offerOption"),mv=s(()=>p.String("--slug",{hidden:!0}),"retiredSlugOption");function hv(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 lt(e.context.stderr,"--slug","--offer"),e.retiredSlug}if(e.offer===void 0)throw new wt("Missing --offer <slug>.");return e.offer}s(hv,"requireOffer");var Xe=class extends C{static{s(this,"OfferCommand")}offer=sa();retiredSlug=mv();#e;get offerSlug(){return this.#e??=hv(this),this.#e}};var bd=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=sa("Manifest slug to export (required)");out=p.String("--out",{required:!0,description:"Output bundle directory (refused when not empty, unless --force)"});force=An();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=sw(this.out,this.force),n=await this.caller(),r=this.requireTenant(n),{bundle:i,generation:o,revision:a}=await pF(n,r,this.offerSlug,this.draft?"draft":"published");return Sn({...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}},vd=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=sa("New offer slug (identity key) (required)");retiredSlug=mv();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=An();async execute(){let t=hv(this);if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let n=sw(this.out??G.join("offers",this.tenant,t),this.force),r=jL({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 Sn({...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}},xd=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=Tn(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}},Sd=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 UL(n,t),a=await Gb(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:Lo[a.manifest],target:"manifest",detail:a.manifest},...Object.entries(a.smartforms).map(([l,d])=>({kind:Lo[d],target:`smartform:${l}`,detail:d})),{kind:Lo[a.workflow],target:"workflow",detail:a.workflow},...VL(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...GL(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...zL(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...WL(a).map(l=>({kind:l.icon,target:l.target,detail:l.status}))]),o.some(l=>l.severity==="error")?1:0}},Ad=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 dv(n,t.index.tenant,t),i=await Gb(n,t);return this.print(i,()=>[...r.map(o=>({icon:"=",target:o.target,status:o.detail})),{icon:Lo[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([o,a])=>({icon:Lo[a],target:`smartform:${o}`,status:a})),{icon:Lo[i.workflow],target:"workflow",status:i.workflow},...VL(i),...GL(i),...zL(i),...WL(i)]),0}};async function UL(e,t){let n=await dv(e,t.index.tenant,t),r=await iv(e,t.index.tenant,t),i=await ov(e,t.index.tenant,t);return{pins:n,stamps:{...r,rows:[...r.rows,...i.rows]},issues:[...r.issues,...i.issues,...Tn(t)]}}s(UL,"validateOnEnvironment");function VL(e){return e.addresses===null?[]:cF(e.addresses)}s(VL,"addressRows");function GL(e){let t={insert:"+",update:"~",archive:"-"};return e.stages.map(n=>({icon:t[n.op],target:`stage:${n.key}`,status:Sp(n)}))}s(GL,"stageRows");function zL(e){return e.capacities.map(t=>({icon:"~",target:`cap:${t.run}\xD7${t.stageKey}`,status:Tp(t)}))}s(zL,"capacityRows");function WL(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(WL,"publishPendingRows");var Ed=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 UL(n,t);for(let d of[...r,...i.rows])this.context.stderr.write(` = ${d.target}: ${d.detail}
@@ -9818,7 +9818,7 @@ A task with --result closes only by recording it: freetext (text, always require
9818
9818
  `,"utf8");let k=[...r.rows,{step:"review",target:n.key,action:"written",detail:`expected of ${y.join(", ")} written into ${G.basename(n.file)} \u2014 review it, then run apply again to seal`}];return m.length>0&&k.push({step:"review",target:n.key,action:"differs",detail:`the draft now produces another output for ${m.join(", ")} than its reviewed expected \u2014 the seal will refuse it`}),{rows:k,revisionId:i,sealed:!1,reviewWritten:y}}await e.mutation(S.contractPackages.seal,{client:t,id:i,expectedSourceRevision:d});let u=await _m(e,t,n);if(u.action!=="same")throw new Error(`${tt}: the sealed revision does not match the file (plan says ${u.action}).`);return{rows:r.rows,revisionId:i,sealed:!0,reviewWritten:[]}}s(dq,"applyPackageSetup");var ca=s(e=>e,"revisionId"),zx=s(e=>{let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--source-revision must be a whole number (got ${e})`);return t},"sourceRevisionOf"),Nm=s(e=>e.map(t=>({...t})),"tableRows"),Wx=class extends Qe{static{s(this,"PackageListCommand")}static paths=[["generator","package","list"]];static usage=T.Usage({category:"Contracts",description:"List the tenant's contract packages with their current and draft revision",details:"Ids for `show`, `clone`, `seal` and `delete-draft` are revision ids; `archive` takes the package id.",examples:[["List packages","$0 --env staging --tenant <slug> generator package list"]]});async execute(){let{caller:t,client:n}=await this.loadContext(),i=(await t.query(S.contractPackages.model,{client:n})).map(o=>{let a=o.revisions.find(d=>d._id===o.currentRevisionId),l=o.revisions.find(d=>d.status==="draft");return{key:o.definition.key,packageId:o.definition._id,name:o.definition.name.de,current:a===void 0?null:{revisionId:a._id,revisionNumber:a.revisionNumber},draft:l===void 0?null:{revisionId:l._id,revisionNumber:l.revisionNumber,sourceRevision:l.sourceRevision},archived:o.definition.archivedAt!==void 0}});return this.print(i,o=>o.map(a=>({key:a.key,name:a.name,current:a.current===null?"\u2014":`${a.current.revisionNumber} (${a.current.revisionId})`,draft:a.draft===null?"\u2014":`${a.draft.revisionNumber} (${a.draft.revisionId}, source-revision ${a.draft.sourceRevision})`,archived:a.archived?"yes":""}))),0}},Hx=class extends Qe{static{s(this,"PackageShowCommand")}static paths=[["generator","package","show"]];static usage=T.Usage({category:"Contracts",description:"Show one package revision: input mask, parts, scenarios and its source-revision counter",examples:[["Show a revision","$0 --env staging --tenant <slug> generator package show <revision-id>"]]});id=p.String({required:!0,name:"revision-id"});async execute(){let{caller:t,client:n}=await this.loadContext();return this.print(await t.query(S.contractPackages.detail,{client:n,id:ca(this.id)})),0}},Yx=class extends Qe{static{s(this,"PackageCreateCommand")}static paths=[["generator","package","create"]];static usage=T.Usage({category:"Contracts",description:"Create an empty contract package (identity + draft revision 1)",details:"Usually `generator package apply --file` does this together with parts, code and scenarios. The key is 2\u201363 lowercase letters, digits or hyphens.",examples:[["Create a package","$0 --env staging --tenant <slug> generator package create --key school-with-care --name 'Schule mit Betreuung' --name-en 'School with care'"]]});key=p.String("--key",{required:!0,description:"Stable package key"});name=p.String("--name",{required:!0,description:"German name"});nameEn=p.String("--name-en",{required:!0,description:"English name"});description=p.String("--description","",{description:"German description (with --description-en, or neither)"});descriptionEn=p.String("--description-en","",{description:"English description"});async execute(){let{caller:t,client:n}=await this.loadContext();return this.print(await t.mutation(S.contractPackages.create,{client:n,key:this.key,name:{de:this.name,en:this.nameEn},description:{de:this.description,en:this.descriptionEn}})),0}},Jx=class extends Qe{static{s(this,"PackageCloneCommand")}static paths=[["generator","package","clone"]];static usage=T.Usage({category:"Contracts",description:"Start a new draft from a package revision (parts, mask, code and scenarios copied)",examples:[["Revise the current revision","$0 --env staging --tenant <slug> generator package clone <sealed-revision-id>"]]});id=p.String({required:!0,name:"source-revision-id"});async execute(){let{caller:t,client:n}=await this.loadContext();return this.print({revisionId:await t.mutation(S.contractPackages.cloneDraft,{client:n,id:ca(this.id)})}),0}},Qx=class extends Qe{static{s(this,"PackageTestCommand")}static paths=[["generator","package","test"]];static usage=T.Usage({category:"Contracts",description:"Resolve a package revision for one input file without creating anything (the scenario output)",details:"The input is `{ shared, parts, skip, meta }`. `scenarioOutput` is what a scenario's `expected` holds.",examples:[["Try an input","$0 --env staging --tenant <slug> generator package test <revision-id> --input ./input.json"]]});id=p.String({required:!0,name:"revision-id"});input=p.String("--input",{required:!0,description:"JSON file with the package input"});async execute(){let{caller:t,client:n}=await this.loadContext();return this.print(await t.query(S.contractPackages.resolve,{client:n,id:ca(this.id),input:JSON.parse(await jn(this.input,"utf8"))})),0}},Zx=class extends Qe{static{s(this,"PackageSealCommand")}static paths=[["generator","package","seal"]];static usage=T.Usage({category:"Contracts",description:"Seal a package draft \u2014 it becomes the current revision new contracts are created from",details:"Sealing re-runs every scenario and refuses a different output. `--source-revision` is the draft's counter from `show`.",examples:[["Seal","$0 --env staging --tenant <slug> generator package seal <revision-id> --source-revision 4"]]});id=p.String({required:!0,name:"revision-id"});sourceRevision=p.String("--source-revision",{required:!0,description:"The draft's current source-revision counter"});async execute(){let{caller:t,client:n}=await this.loadContext();return await t.mutation(S.contractPackages.seal,{client:n,id:ca(this.id),expectedSourceRevision:zx(this.sourceRevision)}),this.print({sealed:this.id}),0}},Xx=class extends Qe{static{s(this,"PackageDeleteDraftCommand")}static paths=[["generator","package","delete-draft"]];static usage=T.Usage({category:"Contracts",description:"Discard a package draft (sealed revisions stay) \u2014 irreversible, plan unless --confirm",examples:[["Plan","$0 --env staging --tenant <slug> generator package delete-draft <revision-id> --source-revision 4"],["Discard","$0 --env staging --tenant <slug> generator package delete-draft <revision-id> --source-revision 4 --confirm"]]});id=p.String({required:!0,name:"revision-id"});sourceRevision=p.String("--source-revision",{required:!0,description:"The draft's current source-revision counter"});confirm=p.Boolean("--confirm",!1,{description:"Discard (without it, only the plan is printed)."});async execute(){let{caller:t,client:n}=await this.loadContext();return this.confirm?(await t.mutation(S.contractPackages.discardDraft,{client:n,id:ca(this.id),expectedSourceRevision:zx(this.sourceRevision)}),this.print({deleted:this.id}),0):(await t.query(S.contractPackages.detail,{client:n,id:ca(this.id)}),this.print({id:this.id,sourceRevision:zx(this.sourceRevision),deleted:!1}),this.context.stderr.write(`Would discard package draft ${this.id} \u2014 re-run with --confirm.
9819
9819
  `),0)}},eS=class extends Qe{static{s(this,"PackageArchiveCommand")}static paths=[["generator","package","archive"]];static usage=T.Usage({category:"Contracts",description:"Archive a contract package \u2014 it creates no new contracts; its key stays taken",examples:[["Archive","$0 --env staging --tenant <slug> generator package archive <package-id>"]]});id=p.String({required:!0,name:"package-id"});async execute(){let{caller:t,client:n}=await this.loadContext();return await t.mutation(S.contractPackages.archive,{client:n,id:this.id}),this.print({archived:this.id}),0}},cq="The file names the package and each part's generator by KEY: { key, name {de,en}, description {de,en}, inputSchema, parts [{ partKey, generator, position, optional, defaults, fixedValues }], source (the package code's .ts file, relative to the file, or null), scenarios [{ key, input, expected? }] }. A sealed revision equal to the file is left alone; otherwise the open draft \u2014 or a copy of the current revision \u2014 takes the file. A scenario without `expected` is evaluated on the draft and its output written into the file; apply then stops UNSEALED for review, and the next run seals.",tS=class extends Qe{static{s(this,"PackagePlanCommand")}static paths=[["generator","package","plan"]];static usage=T.Usage({category:"Contracts",description:"Compare a package file with the environment: create, same or revise (no write)",details:cq,examples:[["Plan","$0 --env staging --tenant <slug> generator package plan --file ./package.json"]]});file=p.String("--file",{required:!0,description:"The package file (JSON)"});async execute(){let{caller:t,client:n}=await this.loadContext();return this.print(Nm((await _m(t,n,Gx(this.file))).rows)),0}},nS=class extends Qe{static{s(this,"PackageApplyCommand")}static paths=[["generator","package","apply"]];static usage=T.Usage({category:"Contracts",description:"Create or revise a contract package from a file and seal it once its scenarios are reviewed",details:`${cq} Exit code 1 while the run stopped for review.`,examples:[["First run: draft + scenario outputs into the file","$0 --env staging --tenant <slug> generator package apply --file ./package.json"],["After reviewing the file: seal","$0 --env staging --tenant <slug> generator package apply --file ./package.json"]]});file=p.String("--file",{required:!0,description:"The package file (JSON); reviewed scenario outputs are written into it"});async execute(){let{caller:t,client:n}=await this.loadContext(),r=await dq(t,n,Gx(this.file));return this.print(r,i=>[...Nm(i.rows),{step:"result",target:i.revisionId??"\u2014",action:i.sealed?"sealed":"NOT sealed",detail:i.sealed?"":"review the written expected outputs, then run apply again"}]),r.sealed?0:1}};async function Cm(e){return await e.query(S.contractInputKeys.list,{})}s(Cm,"registry");var Nc="The registry is platform-wide (one vocabulary for every tenant) and needs a platform operator (_platform.config.manage). Every field a generator declares must be registered before the generator can be sealed. Entries are immutable: a key keeps its label, description and value type; a wrong one is deprecated and replaced by a new key.",rS=class extends C{static{s(this,"InputKeyListCommand")}static paths=[["generator","input-key","list"]];static usage=T.Usage({category:"Contracts",description:"List the contract input registry",details:Nc,examples:[["List","$0 --env staging generator input-key list"]]});async execute(){return this.print(await Cm(await this.caller()),t=>t.map(n=>({key:n.key,type:n.valueKind==="entity"?`entity:${n.entityKind}`:String(n.scalarType),label:n.label.de,deprecated:n.deprecatedAt===void 0?"":"yes"}))),0}},iS=class extends C{static{s(this,"InputKeyCreateCommand")}static paths=[["generator","input-key","create"]];static usage=T.Usage({category:"Contracts",description:"Register one contract input key (camelCase; an entity key ends in PartyId or LegalEntityId)",details:Nc,examples:[["A date",`$0 --env staging generator input-key create --key childBirthDate --label Geburtsdatum --label-en 'Date of birth' --description 'Geburtsdatum des Kindes' --description-en "The child's date of birth" --scalar date`],["A party reference","$0 --env staging generator input-key create --key payerPartyId --label Zahler --label-en Payer --description 'Wer zahlt' --description-en 'Who pays' --entity party"]]});key=p.String("--key",{required:!0,description:"camelCase key"});label=p.String("--label",{required:!0,description:"German label"});labelEn=p.String("--label-en",{required:!0,description:"English label"});description=p.String("--description",{required:!0,description:"German description"});descriptionEn=p.String("--description-en",{required:!0,description:"English description"});scalar=p.String("--scalar",{description:"Value type: string|number|boolean|date|enum|address"});entity=p.String("--entity",{description:"Entity reference: party|legalEntity"});async execute(){let t=Pm(this.scalar,this.entity),r=await(await this.caller()).mutation(S.contractInputKeys.create,{key:this.key,label:{de:this.label,en:this.labelEn},description:{de:this.description,en:this.descriptionEn},value:t});return this.print({id:r,key:this.key}),0}},oS=class extends C{static{s(this,"InputKeyDeprecateCommand")}static paths=[["generator","input-key","deprecate"]];static usage=T.Usage({category:"Contracts",description:"Deprecate a contract input key by key \u2014 no new draft may use it; sealed revisions keep working",details:Nc,examples:[["Deprecate","$0 --env staging generator input-key deprecate --key childBirthDate"]]});key=p.String("--key",{required:!0,description:"The registered key"});async execute(){let t=await this.caller(),n=aq(await Cm(t),this.key);return await t.mutation(S.contractInputKeys.deprecate,{id:n.id}),this.print({deprecated:this.key,alreadyDeprecated:n.deprecatedAt!==void 0}),0}},uq='The file is a JSON array of { key, label {de,en}, description {de,en}, value: { valueKind: "scalar", scalarType } | { valueKind: "entity", entityKind } }.',sS=class extends C{static{s(this,"InputKeyPlanCommand")}static paths=[["generator","input-key","plan"]];static usage=T.Usage({category:"Contracts",description:"Compare an input-key file with the registry: create, same, differs, deprecated (no write)",details:`${Nc} ${uq}`,examples:[["Plan","$0 --env staging generator input-key plan --file ./input-keys.json"]]});file=p.String("--file",{required:!0,description:"The input-key file (JSON array)"});async execute(){let t=Bx(JSON.parse(await jn(this.file,"utf8"))),n=Ux(t,await Cm(await this.caller()));return this.print(Nm(n)),n.some(Vx)?1:0}},aS=class extends C{static{s(this,"InputKeyApplyCommand")}static paths=[["generator","input-key","apply"]];static usage=T.Usage({category:"Contracts",description:"Register every key of a file that is missing; refuse the whole file when one differs or is deprecated",details:`${Nc} ${uq} Nothing is written while any row differs from the registry or names a deprecated key.`,examples:[["Apply","$0 --env staging generator input-key apply --file ./input-keys.json"]]});file=p.String("--file",{required:!0,description:"The input-key file (JSON array)"});async execute(){let t=Bx(JSON.parse(await jn(this.file,"utf8"))),n=await this.caller(),r=Ux(t,await Cm(n)),i=r.filter(Vx);if(i.length>0){for(let o of i)this.context.stderr.write(` \u2716 ${o.key}: ${o.detail}
9820
9820
  `);return this.context.stderr.write(` \u2192 nothing registered (fix the file or choose new keys)
9821
- `),1}for(let[o,a]of t.entries())r[o]?.action==="create"&&await n.mutation(S.contractInputKeys.create,a);return this.print(Nm(r)),0}},fq=[Wx,Hx,Yx,Jx,Qx,Zx,Xx,eS,tS,nS,rS,iS,oS,sS,aS];var Dm=s(e=>new Date(e).toISOString().slice(0,10),"isoDay");function Fm(e,t){return e.map(n=>({application:n.applicationId,classification:n.deleted?`${n.classification} (gel\xF6scht)`:n.classification,ended:Dm(n.endedAt),due:Dm(n.dueAt),test:n.testMode?"test":"",action:t}))}s(Fm,"retentionRows");async function Lm(e,t){return await e.query(S.retention.planDue,{client:t})}s(Lm,"planRetention");async function pq(e,t,n){let r=await Lm(e,t);if(r.length!==n)throw new Error(`retention apply: ${r.length} Anmeldungen sind jetzt f\xE4llig, erwartet waren ${n} \u2014 nichts gel\xF6scht. Erst \`retention plan\` erneut lesen, dann mit der neuen Zahl best\xE4tigen.`);let i=[];for(let o of r){try{await e.mutation(S.retention.eraseDue,{client:t,applicationId:o.applicationId})}catch(a){throw new Error(`retention apply: ${o.applicationId} nicht gel\xF6scht (${a instanceof Error?a.message:String(a)}); davor gel\xF6scht: ${i.length} von ${r.length}${i.length===0?"":` (${i.map(l=>l.applicationId).join(", ")})`}.`,{cause:a})}i.push(o)}return i}s(pq,"applyRetention");var a5=50;function Mm(e,t){return e.map(n=>({party:n.partyId,name:`${n.name??"(ohne Namen)"}${n.deleted?" (gel\xF6scht)":""}`,due:n.deadline===null?"\u2014":Dm(n.deadline),test:n.testMode?"test":"",action:n.blockedReason===null?t:`blocked: ${n.blockedReason.de}`}))}s(Mm,"partyRetentionRows");async function qm(e,t){let n=[],r=null;for(;;){let i=await e.query(S.partyRetention.planDue,{client:t,paginationOpts:{cursor:r,numItems:a5}});for(let o of i.page){let a=await e.query(S.partyRetention.checkDue,{client:t,partyId:o.partyId});n.push({...o,testMode:a.testMode,blockedReason:o.blockedReason??a.blockedReason})}if(i.isDone)break;r=i.continueCursor}return n}s(qm,"planPartyRetention");async function mq(e,t,n){let r=await qm(e,t),i=r.filter(a=>a.blockedReason===null);if(i.length!==n)throw new Error(`retention parties apply: ${i.length} Personen sind jetzt l\xF6schbar, erwartet waren ${n} \u2014 nichts gel\xF6scht. Erst \`retention parties plan\` erneut lesen, dann mit der neuen Zahl best\xE4tigen.`);let o=[];for(let a of i){try{await e.mutation(S.partyRetention.eraseDue,{client:t,partyId:a.partyId})}catch(l){throw new Error(`retention parties apply: ${a.partyId} nicht gel\xF6scht (${l instanceof Error?l.message:String(l)}); davor gel\xF6scht: ${o.length} von ${i.length}${o.length===0?"":` (${o.map(d=>d.partyId).join(", ")})`}.`,{cause:l})}o.push(a)}return r}s(mq,"applyPartyRetention");var lS=["application","classification","ended","due","test","action"],dS=class extends C{static{s(this,"RetentionPlanCommand")}static paths=[["retention","plan"]];static usage=T.Usage({category:"Admission",description:"Read-only: the tenant's applications whose retention period has ended (what `retention apply --confirm` would erase)."});async execute(){let t=await this.caller(),n=await Lm(t,this.requireTenant(t));return this.print(n,r=>Fm(r,"would-erase"),lS),0}},cS=class extends C{static{s(this,"RetentionApplyCommand")}static paths=[["retention","apply"]];static usage=T.Usage({category:"Admission",description:"Erase (DSGVO redaction) every application of the tenant whose retention period has ended. Dry run unless --confirm; --confirm needs --expect <n>, the count `retention plan` showed."});confirm=p.Boolean("--confirm",!1,{description:"Actually erase (default: dry run)"});expect=p.String("--expect",{description:"With --confirm: how many applications you reviewed in `retention plan`; a different count erases nothing"});async execute(){let t=await this.caller(),n=this.requireTenant(t);if(!this.confirm)return this.print(await Lm(t,n),r=>Fm(r,"would-erase"),lS),0;if(this.expect===void 0||!/^\d+$/.test(this.expect))throw new Error("retention apply --confirm: --expect <n> fehlt \u2014 die Zahl der Anmeldungen, die `retention plan` gezeigt hat.");return this.print(await pq(t,n,Number(this.expect)),r=>Fm(r,"erased"),lS),0}},uS=["party","name","due","test","action"],fS=class extends C{static{s(this,"RetentionPartiesPlanCommand")}static paths=[["retention","parties","plan"]];static usage=T.Usage({category:"Stammdaten",description:"Read-only: the tenant's persons past its deletion rule, each with whether the hard delete may run (what `retention parties apply --confirm` would delete; blocked ones are skipped)."});async execute(){let t=await this.caller(),n=await qm(t,this.requireTenant(t));return this.print(n,r=>Mm(r,"would-erase"),uS),0}},pS=class extends C{static{s(this,"RetentionPartiesApplyCommand")}static paths=[["retention","parties","apply"]];static usage=T.Usage({category:"Stammdaten",description:"Hard-delete (with history and files) every person past the tenant's deletion rule that nothing blocks. Dry run unless --confirm; --confirm needs --expect <n>, the would-erase count `retention parties plan` showed."});confirm=p.Boolean("--confirm",!1,{description:"Actually delete (default: dry run)"});expect=p.String("--expect",{description:"With --confirm: how many deletable persons you reviewed in `retention parties plan`; a different count deletes nothing"});async execute(){let t=await this.caller(),n=this.requireTenant(t);if(!this.confirm)return this.print(await qm(t,n),r=>Mm(r,"would-erase"),uS),0;if(this.expect===void 0||!/^\d+$/.test(this.expect))throw new Error("retention parties apply --confirm: --expect <n> fehlt \u2014 die Zahl der l\xF6schbaren Personen, die `retention parties plan` gezeigt hat.");return this.print(await mq(t,n,Number(this.expect)),r=>Mm(r,"erased"),uS),0}},hq=[dS,cS,fS,pS];import{loadavg as b5}from"node:os";var Cc={add:{budgetMs:3e4},addFinance:{budgetMs:9e4},lean:{budgetMs:12e4,selects:{applicants:"none",finance:"none"}},financeCases:{budgetMs:18e4,selects:{applicants:"none",finance:"cases"}},financeFull:{budgetMs:3e5,selects:{applicants:"none",finance:"full"}},minimal:{budgetMs:45e4,selects:{applicants:"minimal",finance:"none"}},full:{budgetMs:6e5,selects:{applicants:"full",finance:"full"}}};function gq(e){if(e.only)return null;for(let[t,n]of Object.entries(Cc))if(n.selects?.applicants===e.applicants&&n.selects.finance===e.finance)return t;return null}s(gq,"seedShapeOf");var yq={fullSeedMs:Cc.full.budgetMs,applicantCallsMs:4e4,driveWaitMs:75e3};var kq=6e5,mS="drive:",l5="driveWait:";function d5(e){return{drive:`${mS}${e}`,wait:`${l5}${e}`}}s(d5,"driveTimingKeys");function bq(e){let t=e.perPhaseMs??{},n=[],r=s((o,a,l)=>{a>l&&n.push({over:a/l,line:`${o} ${wq(a)} > budget ${wq(l)}`})},"check");if(e.shape!==null){let o=Cc[e.shape].budgetMs;e.shape==="add"&&(o*=Math.max(1,e.addedCases??1)),e.shape==="addFinance"&&(o+=Cc.add.budgetMs*(e.addedCases??0)),r(`${e.shape} seed`,e.elapsedMs,o)}let i=0;for(let[o,a]of Object.entries(t)){if(!o.startsWith(mS))continue;let l=o.slice(mS.length),d=t[d5(l).wait]??0;i+=d,r(`applicant ${l}: own calls`,a-d,yq.applicantCallsMs)}return e.shape==="full"&&r("drive waits on scheduled work",i,yq.driveWaitMs),n.sort((o,a)=>a.over-o.over).map(o=>o.line)}s(bq,"seedBudgetBreaches");var wq=s(e=>`${(e/1e3).toFixed(1)} s`,"seconds");var hS=["none","cases","full"],vq="finance";function xq(e){return hS.includes(e)}s(xq,"isFinanceShowcase");function gS(e){return e.financeShowcase!==void 0?e.financeShowcase:e.applicantKeys!==void 0&&e.applicantKeys.length>0?"none":"full"}s(gS,"resolveFinanceShowcase");async function yS(e){let t=e.now??Date.now,n=e.sleep??(d=>new Promise(c=>setTimeout(c,d))),r=e.maxConsecutiveFailures??5,i=`seed run ${e.runId}`,o=s(d=>`${Math.round(d/1e3)}s`,"seconds"),a=0,l="";for(;;){let d;try{d=e.poll(),a=0}catch(c){if(a++,a>=r){let u=c instanceof Error?c.message:String(c);throw new Error(`could not read the status of ${i} ${a} times in a row (it may still be running); last error: ${u}`,{cause:c})}}if(d===null)throw new Error(`${i} not found in seed_runs.`);if(d!==void 0){if(d.phase&&d.phase!==l&&(l=d.phase,e.onPhase(d.phase,d.elapsedMs)),d.status==="completed")return d;if(d.status==="failed")throw new Error(`${i} FAILED in phase "${d.phase??"?"}" after ${o(d.elapsedMs)} \u2014 ${d.error??"no error recorded"}`);if(d.status==="unknown")throw new Error(`${i} has no status (phase "${d.phase??"?"}").`);if(!d.live)throw new Error(`${i} is no longer live: its owner died in phase "${d.phase??"?"}" after ${o(d.elapsedMs)}. Rebuild explicitly (pnpm seed / pnpm seed:lean).`)}if(t()>=e.deadline){let c=e.budgetMs===void 0?"":` after ${o(e.budgetMs)}`;throw new Error(`timed out${c} waiting for ${i} (phase "${l||"?"}"; it may still be running \u2014 poll init/seed:seedStatus).`)}await n(e.pollMs)}}s(yS,"pollSeedRun");import{spawnSync as c5}from"node:child_process";import{closeSync as wS,ftruncateSync as u5,mkdirSync as f5,openSync as p5,readFileSync as m5,writeSync as h5}from"node:fs";import{homedir as g5}from"node:os";import Sq from"node:path";var y5=2;function Aq(e=process.env){let t=e.PLEXUS_SEED_SLOTS;if(t===void 0||t==="")return y5;if(!/^[1-9][0-9]*$/.test(t))throw new Error(`PLEXUS_SEED_SLOTS must be a positive integer, got '${t}'.`);return Number.parseInt(t,10)}s(Aq,"seedSlotCount");function Eq(){return Sq.join(g5(),".cache","plexus","seed-slots")}s(Eq,"seedSlotDir");function w5(e,t){return Sq.join(e,`slot-${t}.lock`)}s(w5,"slotFile");function k5(e){f5(e.dir,{recursive:!0});let t=[];for(let n=0;n<e.slots;n++){let r=w5(e.dir,n),i=p5(r,"a+"),o=c5("flock",["--nonblock","--exclusive","3"],{stdio:["ignore","ignore","pipe",i],encoding:"utf8"});if(o.error)throw wS(i),new Error(`seed slot: cannot run flock(1) \u2014 ${o.error.message}`);if(o.status===0){u5(i,0),h5(i,`${e.holder}
9821
+ `),1}for(let[o,a]of t.entries())r[o]?.action==="create"&&await n.mutation(S.contractInputKeys.create,a);return this.print(Nm(r)),0}},fq=[Wx,Hx,Yx,Jx,Qx,Zx,Xx,eS,tS,nS,rS,iS,oS,sS,aS];var Dm=s(e=>new Date(e).toISOString().slice(0,10),"isoDay");function Fm(e,t){return e.map(n=>({application:n.applicationId,classification:n.deleted?`${n.classification} (gel\xF6scht)`:n.classification,ended:Dm(n.endedAt),due:Dm(n.dueAt),test:n.testMode?"test":"",action:t}))}s(Fm,"retentionRows");async function Lm(e,t){return await e.query(S.retention.planDue,{client:t})}s(Lm,"planRetention");async function pq(e,t,n){let r=await Lm(e,t);if(r.length!==n)throw new Error(`retention apply: ${r.length} Anmeldungen sind jetzt f\xE4llig, erwartet waren ${n} \u2014 nichts gel\xF6scht. Erst \`retention plan\` erneut lesen, dann mit der neuen Zahl best\xE4tigen.`);let i=[];for(let o of r){try{await e.mutation(S.retention.eraseDue,{client:t,applicationId:o.applicationId})}catch(a){throw new Error(`retention apply: ${o.applicationId} nicht gel\xF6scht (${a instanceof Error?a.message:String(a)}); davor gel\xF6scht: ${i.length} von ${r.length}${i.length===0?"":` (${i.map(l=>l.applicationId).join(", ")})`}.`,{cause:a})}i.push(o)}return i}s(pq,"applyRetention");var a5=50;function Mm(e,t){return e.map(n=>({party:n.partyId,name:`${n.name??"(ohne Namen)"}${n.deleted?" (gel\xF6scht)":""}`,due:n.deadline===null?"\u2014":Dm(n.deadline),test:n.testMode?"test":"",action:n.blockedReason===null?t:`blocked: ${n.blockedReason.de}`}))}s(Mm,"partyRetentionRows");async function qm(e,t){let n=[],r=null;for(;;){let i=await e.query(S.partyRetention.planDue,{client:t,paginationOpts:{cursor:r,numItems:a5}});for(let o of i.page){let a=await e.query(S.partyRetention.checkDue,{client:t,partyId:o.partyId});n.push({...o,testMode:a.testMode,blockedReason:o.blockedReason??a.blockedReason})}if(i.isDone)break;r=i.continueCursor}return n}s(qm,"planPartyRetention");async function mq(e,t,n){let r=await qm(e,t),i=r.filter(a=>a.blockedReason===null);if(i.length!==n)throw new Error(`retention parties apply: ${i.length} Personen sind jetzt l\xF6schbar, erwartet waren ${n} \u2014 nichts gel\xF6scht. Erst \`retention parties plan\` erneut lesen, dann mit der neuen Zahl best\xE4tigen.`);let o=[];for(let a of i){try{await e.mutation(S.partyRetention.eraseDue,{client:t,partyId:a.partyId})}catch(l){throw new Error(`retention parties apply: ${a.partyId} nicht gel\xF6scht (${l instanceof Error?l.message:String(l)}); davor gel\xF6scht: ${o.length} von ${i.length}${o.length===0?"":` (${o.map(d=>d.partyId).join(", ")})`}.`,{cause:l})}o.push(a)}return r}s(mq,"applyPartyRetention");var lS=["application","classification","ended","due","test","action"],dS=class extends C{static{s(this,"RetentionPlanCommand")}static paths=[["retention","plan"]];static usage=T.Usage({category:"Admission",description:"Read-only: the tenant's applications whose retention period has ended (what `retention apply --confirm` would erase)."});async execute(){let t=await this.caller(),n=await Lm(t,this.requireTenant(t));return this.print(n,r=>Fm(r,"would-erase"),lS),0}},cS=class extends C{static{s(this,"RetentionApplyCommand")}static paths=[["retention","apply"]];static usage=T.Usage({category:"Admission",description:"Erase (DSGVO redaction) every application of the tenant whose retention period has ended. Dry run unless --confirm; --confirm needs --expect <n>, the count `retention plan` showed."});confirm=p.Boolean("--confirm",!1,{description:"Actually erase (default: dry run)"});expect=p.String("--expect",{description:"With --confirm: how many applications you reviewed in `retention plan`; a different count erases nothing"});async execute(){let t=await this.caller(),n=this.requireTenant(t);if(!this.confirm)return this.print(await Lm(t,n),r=>Fm(r,"would-erase"),lS),0;if(this.expect===void 0||!/^\d+$/.test(this.expect))throw new Error("retention apply --confirm: --expect <n> fehlt \u2014 die Zahl der Anmeldungen, die `retention plan` gezeigt hat.");return this.print(await pq(t,n,Number(this.expect)),r=>Fm(r,"erased"),lS),0}},uS=["party","name","due","test","action"],fS=class extends C{static{s(this,"RetentionPartiesPlanCommand")}static paths=[["retention","parties","plan"]];static usage=T.Usage({category:"Stammdaten",description:"Read-only: the tenant's persons past its deletion rule, each with whether the hard delete may run (what `retention parties apply --confirm` would delete; blocked ones are skipped)."});async execute(){let t=await this.caller(),n=await qm(t,this.requireTenant(t));return this.print(n,r=>Mm(r,"would-erase"),uS),0}},pS=class extends C{static{s(this,"RetentionPartiesApplyCommand")}static paths=[["retention","parties","apply"]];static usage=T.Usage({category:"Stammdaten",description:"Hard-delete (with history and files) every person past the tenant's deletion rule that nothing blocks. Dry run unless --confirm; --confirm needs --expect <n>, the would-erase count `retention parties plan` showed."});confirm=p.Boolean("--confirm",!1,{description:"Actually delete (default: dry run)"});expect=p.String("--expect",{description:"With --confirm: how many deletable persons you reviewed in `retention parties plan`; a different count deletes nothing"});async execute(){let t=await this.caller(),n=this.requireTenant(t);if(!this.confirm)return this.print(await qm(t,n),r=>Mm(r,"would-erase"),uS),0;if(this.expect===void 0||!/^\d+$/.test(this.expect))throw new Error("retention parties apply --confirm: --expect <n> fehlt \u2014 die Zahl der l\xF6schbaren Personen, die `retention parties plan` gezeigt hat.");return this.print(await mq(t,n,Number(this.expect)),r=>Mm(r,"erased"),uS),0}},hq=[dS,cS,fS,pS];import{loadavg as b5}from"node:os";var Cc={add:{budgetMs:3e4},addFinance:{budgetMs:6e4},lean:{budgetMs:12e4,selects:{applicants:"none",finance:"none"}},financeCases:{budgetMs:18e4,selects:{applicants:"none",finance:"cases"}},financeFull:{budgetMs:3e5,selects:{applicants:"none",finance:"full"}},minimal:{budgetMs:45e4,selects:{applicants:"minimal",finance:"none"}},full:{budgetMs:6e5,selects:{applicants:"full",finance:"full"}}};function gq(e){if(e.only)return null;for(let[t,n]of Object.entries(Cc))if(n.selects?.applicants===e.applicants&&n.selects.finance===e.finance)return t;return null}s(gq,"seedShapeOf");var yq={fullSeedMs:Cc.full.budgetMs,applicantCallsMs:4e4,driveWaitMs:75e3};var kq=6e5,mS="drive:",l5="driveWait:";function d5(e){return{drive:`${mS}${e}`,wait:`${l5}${e}`}}s(d5,"driveTimingKeys");function bq(e){let t=e.perPhaseMs??{},n=[],r=s((o,a,l)=>{a>l&&n.push({over:a/l,line:`${o} ${wq(a)} > budget ${wq(l)}`})},"check");if(e.shape!==null){let o=Cc[e.shape].budgetMs;e.shape==="add"&&(o*=Math.max(1,e.addedCases??1)),e.shape==="addFinance"&&(o+=Cc.add.budgetMs*(e.addedCases??0)),r(`${e.shape} seed`,e.elapsedMs,o)}let i=0;for(let[o,a]of Object.entries(t)){if(!o.startsWith(mS))continue;let l=o.slice(mS.length),d=t[d5(l).wait]??0;i+=d,r(`applicant ${l}: own calls`,a-d,yq.applicantCallsMs)}return e.shape==="full"&&r("drive waits on scheduled work",i,yq.driveWaitMs),n.sort((o,a)=>a.over-o.over).map(o=>o.line)}s(bq,"seedBudgetBreaches");var wq=s(e=>`${(e/1e3).toFixed(1)} s`,"seconds");var hS=["none","cases","full"],vq="finance";function xq(e){return hS.includes(e)}s(xq,"isFinanceShowcase");function gS(e){return e.financeShowcase!==void 0?e.financeShowcase:e.applicantKeys!==void 0&&e.applicantKeys.length>0?"none":"full"}s(gS,"resolveFinanceShowcase");async function yS(e){let t=e.now??Date.now,n=e.sleep??(d=>new Promise(c=>setTimeout(c,d))),r=e.maxConsecutiveFailures??5,i=`seed run ${e.runId}`,o=s(d=>`${Math.round(d/1e3)}s`,"seconds"),a=0,l="";for(;;){let d;try{d=e.poll(),a=0}catch(c){if(a++,a>=r){let u=c instanceof Error?c.message:String(c);throw new Error(`could not read the status of ${i} ${a} times in a row (it may still be running); last error: ${u}`,{cause:c})}}if(d===null)throw new Error(`${i} not found in seed_runs.`);if(d!==void 0){if(d.phase&&d.phase!==l&&(l=d.phase,e.onPhase(d.phase,d.elapsedMs)),d.status==="completed")return d;if(d.status==="failed")throw new Error(`${i} FAILED in phase "${d.phase??"?"}" after ${o(d.elapsedMs)} \u2014 ${d.error??"no error recorded"}`);if(d.status==="unknown")throw new Error(`${i} has no status (phase "${d.phase??"?"}").`);if(!d.live)throw new Error(`${i} is no longer live: its owner died in phase "${d.phase??"?"}" after ${o(d.elapsedMs)}. Rebuild explicitly (pnpm seed / pnpm seed:lean).`)}if(t()>=e.deadline){let c=e.budgetMs===void 0?"":` after ${o(e.budgetMs)}`;throw new Error(`timed out${c} waiting for ${i} (phase "${l||"?"}"; it may still be running \u2014 poll init/seed:seedStatus).`)}await n(e.pollMs)}}s(yS,"pollSeedRun");import{spawnSync as c5}from"node:child_process";import{closeSync as wS,ftruncateSync as u5,mkdirSync as f5,openSync as p5,readFileSync as m5,writeSync as h5}from"node:fs";import{homedir as g5}from"node:os";import Sq from"node:path";var y5=2;function Aq(e=process.env){let t=e.PLEXUS_SEED_SLOTS;if(t===void 0||t==="")return y5;if(!/^[1-9][0-9]*$/.test(t))throw new Error(`PLEXUS_SEED_SLOTS must be a positive integer, got '${t}'.`);return Number.parseInt(t,10)}s(Aq,"seedSlotCount");function Eq(){return Sq.join(g5(),".cache","plexus","seed-slots")}s(Eq,"seedSlotDir");function w5(e,t){return Sq.join(e,`slot-${t}.lock`)}s(w5,"slotFile");function k5(e){f5(e.dir,{recursive:!0});let t=[];for(let n=0;n<e.slots;n++){let r=w5(e.dir,n),i=p5(r,"a+"),o=c5("flock",["--nonblock","--exclusive","3"],{stdio:["ignore","ignore","pipe",i],encoding:"utf8"});if(o.error)throw wS(i),new Error(`seed slot: cannot run flock(1) \u2014 ${o.error.message}`);if(o.status===0){u5(i,0),h5(i,`${e.holder}
9822
9822
  `);let a=!1;return{index:n,release:s(()=>{a||(a=!0,wS(i))},"release")}}if(wS(i),o.status!==1)throw new Error(`seed slot: flock ${r} exited ${o.status} \u2014 ${(o.stderr??"").trim()}`);t.push(m5(r,"utf8").trim()||"unknown holder")}return{busy:t}}s(k5,"tryAcquireSeedSlot");async function Tq(e){let t=e.now??Date.now,n=e.sleep??(i=>new Promise(o=>setTimeout(o,i))),r="";for(;;){let i=k5(e);if("index"in i)return i;let o=`${i.busy.length} in use: ${i.busy.join(", ")}`;if(t()>=e.deadline)throw new Error(`no seed slot became free before the timeout (${o})`);let a=`waiting for a seed slot (${o})`;a!==r&&(e.onWait(a),r=a),await n(e.pollMs)}}s(Tq,"acquireSeedSlot");function Rq(){let e=process.cwd();for(;;){if(Ae(G.join(e,"convex")))return e;let t=G.dirname(e);if(t===e)throw new Error("plexus seed: no Convex project found above the current directory \u2014 run this from inside the worktree (e.g. the app/ dir).");e=t}}s(Rq,"findConvexProjectDir");function v5(e,t,n=!1,r){let i=["convex","run",e];t!==void 0&&i.push(t),n&&i.push("--push");let o=PN("npx",i,{cwd:Rq(),encoding:"utf8",stdio:["ignore","pipe","pipe"],...r===void 0?{}:{timeout:r,killSignal:"SIGTERM"}});if(r!==void 0&&o.error?.code==="ETIMEDOUT"){let c=n?`functions push (convex run ${e} --push)`:`convex run ${e}`;throw new Error(`${c} did not finish within ${r/1e3}s (--push-timeout); nothing was seeded.`)}if(o.status!==0){let c=(o.stderr??"").trim();throw new Error(c||`convex run ${e} exited ${o.status}`)}let a=(o.stdout??"").trim();try{return JSON.parse(a)}catch{}let l=a.indexOf("{"),d=a.lastIndexOf("}");if(l<0||d<l)throw new Error(`convex run ${e}: no JSON in output:
9823
9823
  ${a}`);return JSON.parse(a.slice(l,d+1))}s(v5,"convexRun");function kS(){return b5().map(e=>e.toFixed(2)).join(" ")}s(kS,"loadAverage");var x5={convexRun:v5,now:Date.now,sleep:s(e=>new Promise(t=>setTimeout(t,e)),"sleep"),slotDir:Eq,worktree:s(()=>G.basename(G.dirname(Rq())),"worktree")},bS=kq/1e3,vS=s((e,t)=>Math.max(1,Number.parseInt(e,10)||t),"secondsOption"),$q=s(e=>(e??"").split(",").map(t=>t.trim()).filter(t=>t.length>0),"splitList"),xS=class extends Se{static{s(this,"SeedCommand")}static paths=[["seed"]];static usage=T.Usage({category:"Operations",description:"Kick off the destructive local reseed and poll its run marker to completion.",details:`Which shape to seed for a task, what each costs and its budget: docs/engineering/seed-index.md.
9824
9824
 
@@ -9886,6 +9886,6 @@ ${n.length} unusable ${o}:
9886
9886
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli users relink-auth <email>
9887
9887
  `),i.length>0&&this.context.stdout.write(` ${i.length} without any login account \u2014 plexus-cli users provision --tenant <slug> --email <email> --name <name>
9888
9888
  `)}else this.context.stdout.write(`No unusable identities.
9889
- `);return n.length>0?1:0}},DA=class extends Rn{static{s(this,"UsersRelinkAuthCommand")}static paths=[["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 eK(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(eK,"requireOnOff");var tK=[gA,yA,wA,kA,bA,vA,xA,SA,AA,EA,TA,$A,Dc,RA,IA,OA,PA,_A,NA,CA,DA];function nK(e){return e.de??e.en??Object.values(e)[0]??""}s(nK,"titleDe");function i3(e){return{id:e._id,kind:e.kind,status:e.status,title:nK(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(i3,"row");var o3=["id","kind","status","title","assignee","group","outcome"],LA=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(i3),o3),0}},MA=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:nK(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}},qA=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}},KA=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}},jA=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}},rK=[LA,MA,qA,KA,jA];var Qm=[...b$,...p_,...SN,...xN,...YN,...nC,...tC,...Zq,...tK,...Qq,...nq,...ZP,...GN,...jq,...w$,...V$,...YP,...oC,...iC,...lC,...dC,...UN,...IN,...rK,...n0,...j0,...eq,...B0,...Iq,...Lq,...rq,...fq,...hq,...Kq,...Gq,...F$];var iK="0.1.29";function oK(){return Qm.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=m$[qa(n)];return{path:n,effect:ro(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(oK,"plexusCommandCatalog");import jo from"node:path";function s3(e){let t=ot()?.workspaceRoot??process.cwd(),n=jo.resolve(t,e),r=jo.relative(t,n);if(jo.isAbsolute(e)||r===".."||r.startsWith(`..${jo.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(s3,"workspacePath");function a3(e){let{absolute:t,relative:n}=s3(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of kr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=jo.join(o,a.name);if(a.isDirectory()?i(l):r.push(jo.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 at(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(jo.dirname(t),{recursive:!0}),at(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Go(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(a3,"plexusWorkspace");function sK(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=ja[n];if(!o||!Object.hasOwn(ja,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(pg,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:pg[i.path],skillHash:Pu}}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 a3(i)},"executePlexusAgentTool")}s(sK,"createPlexusAgentToolExecutor");var Zm=sK({inspectCommand:lK,executeCommand:dK});function Xm(){let e=new Yo({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:iK});e.register(Sa.HelpCommand),e.register(Sa.VersionCommand);for(let n of Qm)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 c3(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(Xm,"createPlexusCli");function c3(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&Ma[n]===r&&lt(t,n,r),n in Ma&&ro(n)==="confirm"&&!Ka(e)&&t.write(`plexus-cli: \`${Ma[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
9889
+ `);return n.length>0?1:0}},DA=class extends Rn{static{s(this,"UsersRelinkAuthCommand")}static paths=[["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 eK(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(eK,"requireOnOff");var tK=[gA,yA,wA,kA,bA,vA,xA,SA,AA,EA,TA,$A,Dc,RA,IA,OA,PA,_A,NA,CA,DA];function nK(e){return e.de??e.en??Object.values(e)[0]??""}s(nK,"titleDe");function i3(e){return{id:e._id,kind:e.kind,status:e.status,title:nK(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(i3,"row");var o3=["id","kind","status","title","assignee","group","outcome"],LA=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(i3),o3),0}},MA=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:nK(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}},qA=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}},KA=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}},jA=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}},rK=[LA,MA,qA,KA,jA];var Qm=[...b$,...p_,...SN,...xN,...YN,...nC,...tC,...Zq,...tK,...Qq,...nq,...ZP,...GN,...jq,...w$,...V$,...YP,...oC,...iC,...lC,...dC,...UN,...IN,...rK,...n0,...j0,...eq,...B0,...Iq,...Lq,...rq,...fq,...hq,...Kq,...Gq,...F$];var iK="0.1.31";function oK(){return Qm.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=m$[qa(n)];return{path:n,effect:ro(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(oK,"plexusCommandCatalog");import jo from"node:path";function s3(e){let t=ot()?.workspaceRoot??process.cwd(),n=jo.resolve(t,e),r=jo.relative(t,n);if(jo.isAbsolute(e)||r===".."||r.startsWith(`..${jo.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(s3,"workspacePath");function a3(e){let{absolute:t,relative:n}=s3(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of kr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=jo.join(o,a.name);if(a.isDirectory()?i(l):r.push(jo.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 at(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(jo.dirname(t),{recursive:!0}),at(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Go(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(a3,"plexusWorkspace");function sK(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=ja[n];if(!o||!Object.hasOwn(ja,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(pg,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:pg[i.path],skillHash:Pu}}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 a3(i)},"executePlexusAgentTool")}s(sK,"createPlexusAgentToolExecutor");var Zm=sK({inspectCommand:lK,executeCommand:dK});function Xm(){let e=new Yo({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:iK});e.register(Sa.HelpCommand),e.register(Sa.VersionCommand);for(let n of Qm)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 c3(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(Xm,"createPlexusCli");function c3(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&Ma[n]===r&&lt(t,n,r),n in Ma&&ro(n)==="confirm"&&!Ka(e)&&t.write(`plexus-cli: \`${Ma[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
9890
9890
  `)}s(c3,"noteRetiredPath");function lK(e){let t=Xm().process(ma(e),{executePlexusAgentTool:Zm}),n=t.path.join(" ");if(n.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=oK().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"?mp(Ws(Hs),i.fn??"",i.kind):void 0,a=Iu(n,{confirm:Ka(t),callKind:o});return{...r,writes:a}}s(lK,"inspectPlexusCommand");async function dK(e,t){if(t)return VA(t,()=>dK(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=Xm();if(ot()){let l=lK(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(ma(e.argv),{executePlexusAgentTool:Zm,stdin:d3.from(e.stdin===void 0?[]:[e.stdin]),stdout:new aK({write(l,d,c){n+=String(l),c()}}),stderr:new aK({write(l,d,c){r+=String(l),c()}})}),stdout:n,stderr:r}}s(dK,"executePlexusCommand");YA({source:u3.join(import.meta.dirname,"skill")});Xm().runExit(ma(process.argv.slice(2)),{executePlexusAgentTool:Zm});
9891
9891
  //# sourceMappingURL=cli.mjs.map