@questwork/p-templates-model 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -5,7 +5,8 @@ Template model, template kinds and the Questwork template syntax engine, shared
5
5
  - `Template` (TenantAwareEntity), the `TemplateEmail` kind, `TemplateBlock` versions with `LifecycleTemplateBlock`, and `TemplateLayout` versions (email layouts: shared pieces such as a header or footer that templates place).
6
6
  - Data contexts and template projections: the fields each data root shows in the editor; values the loader supplies beyond them also reach templates, unchecked.
7
7
  - Questwork template syntax ([specification V2](docs/template-syntax-v2.md), a curated Liquid subset): parser, save-time checks and rendering with liquidjs.
8
- - Email rendering: parts, CSS inlining (juice), envelope fields and `cid:` inline attachment references.
8
+ - Email rendering: parts, CSS inlining (juice), envelope fields (including an optional fixed `to` for direct transactional jobs) and `cid:` inline attachment references.
9
+ - `templateRevision` tracks renderable content independently from optimistic `meta.revision`, so operational envelope changes do not become content revisions.
9
10
 
10
11
  It does not send messages. Sending (jobs, deliveries, providers) belongs to the later messaging packages.
11
12
 
@@ -32,6 +33,8 @@ Each example is runnable (`node examples/<file>`; all: `pnpm examples`) and has
32
33
 
33
34
  The example consumer in [examples/congressConsumer](examples/congressConsumer) shows the consumer side: contexts (and the `LAYOUT` context for layout editors), projections, functions, blocks, header and footer layouts and a `TemplateEmailCongress` subclass.
34
35
 
36
+ Templates can store an optional plain-text `documentReference`. Set `includeTemplateDocumentReference: true` on a data context to expose `template.documentReference` to the editor and renderer. The value comes from the template, not the data loader; an unset value renders blank. See [the document reference example](examples/10-template-document-reference.js).
37
+
35
38
  ## Development
36
39
 
37
40
  ```bash
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@questwork/q-utilities"),A=require("liquidjs"),Ht=require("juice/client"),Wt=t=>t&&t.__esModule?t:{default:t},Xt=Wt(Ht),Oe=2,$e=Object.freeze([2]),b=Object.freeze({BLOCK_CONTEXT_MISMATCH:"BLOCK_CONTEXT_MISMATCH",BLOCK_DEPRECATED:"BLOCK_DEPRECATED",BLOCK_ELEMENT_INVALID:"BLOCK_ELEMENT_INVALID",BLOCK_NOT_ALLOWED:"BLOCK_NOT_ALLOWED",BLOCK_NOT_PUBLISHED:"BLOCK_NOT_PUBLISHED",BLOCK_PARAMS_INVALID:"BLOCK_PARAMS_INVALID",BLOCK_ROOT_NOT_IN_CONTEXT:"BLOCK_ROOT_NOT_IN_CONTEXT",FIELD_EXPRESSION_NOT_ALLOWED:"FIELD_EXPRESSION_NOT_ALLOWED",FUNCTION_ARGUMENTS_INVALID:"FUNCTION_ARGUMENTS_INVALID",FUNCTION_NOT_ALLOWED:"FUNCTION_NOT_ALLOWED",LAYOUT_EMPTY:"LAYOUT_EMPTY",LAYOUT_NOT_ALLOWED:"LAYOUT_NOT_ALLOWED",LAYOUT_NOT_FOUND:"LAYOUT_NOT_FOUND",LOOP_SOURCE_NOT_LIST:"LOOP_SOURCE_NOT_LIST",OUTPUT_NOT_SCALAR:"OUTPUT_NOT_SCALAR",PART_REQUIRED:"PART_REQUIRED",PART_UNKNOWN:"PART_UNKNOWN",PATH_UNKNOWN:"PATH_UNKNOWN",ROOT_UNKNOWN:"ROOT_UNKNOWN",SYNTAX_ERROR:"SYNTAX_ERROR",SYNTAX_VERSION_UNSUPPORTED:"SYNTAX_VERSION_UNSUPPORTED",TAG_NOT_ALLOWED:"TAG_NOT_ALLOWED",UNKNOWN_BLOCK:"UNKNOWN_BLOCK",UNKNOWN_FUNCTION:"UNKNOWN_FUNCTION",VARIABLE_INVALID:"VARIABLE_INVALID"}),K=Object.freeze({ERROR:"ERROR",WARNING:"WARNING"}),Ue=Object.freeze(["blank","empty","false","forloop","nil","null","params","true"]),V="params",J=/^[A-Z_]\w*$/i,P=Object.freeze({BOOLEAN:"boolean",DATE:"date",LIST:"list",NUMBER:"number",OBJECT:"object",STRING:"string"}),Qt=new Set([P.BOOLEAN,P.DATE,P.NUMBER,P.STRING]),ae=Symbol("templateProjectionNode"),Jt=10;class ke{constructor({projectionCode:e,label:n,description:r,fields:i}={}){if(!e||typeof e!="string")throw new TypeError("TemplateProjection requires a projectionCode.");Object.defineProperty(this,ae,{enumerable:!1,value:ue({description:r,fields:i,label:n,type:P.OBJECT},e)}),this.projectionCode=e,Object.freeze(this)}describe(){return pe(this[ae])}project(e){return de(this[ae],e)}}function v(t){return new ke(t)}function ge(t,{label:e,description:n,value:r}={}){return{description:n,item:t,label:e,type:P.LIST,value:r}}function Zt(t,e="root"){return ue(t,e)}function en(t){return pe(t)}function tn(t,e){return de(t,e)}function ue(t,e){if(t instanceof ke)return t[ae];if(!t||typeof t!="object")throw new TypeError(`Template field "${e}" must be an object definition.`);const{description:n,label:r,type:i,value:s}=t;if(s!==void 0&&typeof s!="function")throw new TypeError(`Template field "${e}" value must be a function.`);const o={description:n,label:r,type:i,value:s};if(i===P.OBJECT)o.fields=Object.entries(t.fields||{}).reduce((a,[c,l])=>(nn(c,e),a[c]=ue(l,`${e}.${c}`),a),{});else if(i===P.LIST)o.item=ue(t.item,`${e}[]`);else if(!Qt.has(i))throw new TypeError(`Template field "${e}" has unsupported type "${i}".`);return Object.freeze(o)}function nn(t,e){if(!J.test(t)||t.startsWith("__")||Ue.includes(t))throw new TypeError(`Template field name "${e}.${t}" is not allowed.`)}function pe(t){const e={type:t.type};return t.label&&(e.label=t.label),t.description&&(e.description=t.description),t.fields&&(e.fields=Object.entries(t.fields).reduce((n,[r,i])=>(n[r]=pe(i),n),{})),t.item&&(e.item=pe(t.item)),e}function de(t,e){if(t.type===P.OBJECT){if(e===null||typeof e!="object")return null;const n=Be(e,0,new WeakSet)||{};return Object.entries(t.fields).reduce((r,[i,s])=>(r[i]=de(s,s.value?s.value(e):e[i]),r),n)}return t.type===P.LIST?Array.isArray(e)?e.map(n=>de(t.item,n)):[]:e instanceof Date?Number.isNaN(e.getTime())?null:e.getTime():["string","number","boolean"].includes(typeof e)?typeof e=="number"&&!Number.isFinite(e)?null:e:null}function Be(t,e,n){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.getTime();if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(typeof t!="object"||e>=Jt||n.has(t))return null;n.add(t);try{if(Array.isArray(t))return t.map(i=>i===void 0||typeof i=="function"||typeof i=="symbol"?null:Be(i,e+1,n));const r=typeof t.toObject=="function"?t.toObject():t;return Object.entries(r).reduce((i,[s,o])=>(o!==void 0&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="bigint"&&(i[s]=Be(o,e+1,n)),i),{})}finally{n.delete(t)}}class it{constructor({contextCode:e,name:n,subjectType:r,roots:i,recipientRules:s=[],functionNames:o=[],loadData:a,sampleData:c}={}){if(!e||typeof e!="string")throw new TypeError("DataContext requires a contextCode.");if(a!==void 0&&typeof a!="function")throw new TypeError(`DataContext ${e} loadData must be a function.`);const l=Object.entries(i||{}).reduce((f,[u,d])=>{if(!J.test(u)||u.startsWith("__")||Ue.includes(u))throw new TypeError(`DataContext ${e} root name "${u}" is not allowed.`);return f[u]=Zt(d,u),f},{});if(!Object.keys(l).length)throw new TypeError(`DataContext ${e} requires at least one data root.`);Object.defineProperties(this,{_loadData:{enumerable:!1,value:a},_rootNodes:{enumerable:!1,value:Object.freeze(l)},_sampleData:{enumerable:!1,value:c}}),this.contextCode=e,this.functionNames=Object.freeze([...new Set(o)]),this.name=n||e,this.recipientRules=Object.freeze(s.map(({recipientType:f,name:u,description:d})=>{if(!f)throw new TypeError(`DataContext ${e} recipient rules require recipientType.`);return Object.freeze({description:d,name:u||f,recipientType:f})})),this.subjectType=r,Object.freeze(this)}get rootNames(){return Object.keys(this._rootNodes)}describe(){return{contextCode:this.contextCode,functionNames:[...this.functionNames],name:this.name,recipientRules:this.recipientRules.map(e=>({...e})),roots:Object.entries(this._rootNodes).reduce((e,[n,r])=>(e[n]=en(r),e),{}),subjectType:this.subjectType}}project(e={}){return Object.entries(this._rootNodes).reduce((n,[r,i])=>(n[r]=tn(i,e[r]),n),{})}async load({subjectRef:e,recipientType:n,...r}={}){if(!this._loadData)throw new Error(`DataContext ${this.contextCode} has no loadData.`);if(this.recipientRules.length&&!this.recipientRules.some(s=>s.recipientType===n))throw new RangeError(`DataContext ${this.contextCode} does not support recipientType "${n}".`);const i=await this._loadData({recipientType:n,subjectRef:e,...r});if(!Array.isArray(i))throw new TypeError(`DataContext ${this.contextCode} loadData must return an array.`);return i.map(({recipientRef:s,roots:o})=>({data:this.project(o),...s!==void 0?{recipientRef:s}:{}}))}getSampleData(){return this._sampleData?structuredClone(this._sampleData):null}}function Z(t){return new it(t)}function ee(t){return t?typeof t.describe=="function"?t.describe():t:null}const $=Object.freeze({ANY:"any",ARRAY:"array",BOOLEAN:"boolean",NUMBER:"number",OBJECT:"object",STRING:"string"}),rn=new Set(Object.values($)),sn=/^__[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/,q=new Map;let Ve=0;function st({name:t,fn:e,signature:n=[],trustedHtml:r=!1,label:i,description:s}={}){if(!sn.test(t||""))throw new TypeError(`Template function name "${t}" must be "__" followed by snake_case letters and digits.`);if(typeof e!="function")throw new TypeError(`Template function ${t} requires fn.`);if(q.has(t))throw new Error(`Template function ${t} is already registered.`);if(!n.length)throw new TypeError(`Template function ${t} requires a signature with at least the piped value.`);const o=n.map((a,c)=>{const l=(a==null?void 0:a.types)||[];if(!l.length||l.some(f=>!rn.has(f)))throw new TypeError(`Template function ${t} argument #${c+1} has invalid types.`);return Object.freeze({...a.optional?{optional:!0}:{},types:Object.freeze([...l]),...a.variadic?{variadic:!0}:{}})});q.set(t,Object.freeze({descriptor:Object.freeze({...s?{description:s}:{},...i?{label:i}:{},name:t,signature:Object.freeze(o),trustedHtml:!!r}),filter:cn(t,e,o)})),Ve+=1}function te(){return[...q.values()].map(({descriptor:t})=>({...t,signature:t.signature.map(e=>({...e,types:[...e.types]}))}))}function on(t){var e;return((e=q.get(t))==null?void 0:e.descriptor)||null}function an(){return{filters:[...q.values()].map(({descriptor:t,filter:e})=>({handler:e,name:t.name,raw:t.trustedHtml})),version:Ve}}function ln(){q.clear(),Ve+=1}function cn(t,e,n){return(...r)=>{const i=r.map(o=>o===void 0?null:o);i.forEach((o,a)=>{const c=n[Math.min(a,n.length-1)];if(o!==null&&c&&!c.types.some(l=>un(o,l)))throw new TypeError(`${t} argument #${a+1} must be ${c.types.join(" or ")}.`)});const s=e(...i);return s===void 0?null:s}}function un(t,e){switch(e){case $.ANY:return!0;case $.ARRAY:return Array.isArray(t);case $.OBJECT:return typeof t=="object"&&!Array.isArray(t);case $.BOOLEAN:return typeof t=="boolean";case $.NUMBER:return typeof t=="number";default:return typeof t=="string"}}function C({code:t,message:e,severity:n=K.ERROR,...r}={}){const i={code:t,message:e,severity:n};return["partCode","offset","line","column","source","blockRef","detail"].forEach(s=>{typeof r[s]<"u"&&(i[s]=r[s])}),i}function z(t=[]){return t.some(e=>e.severity===K.ERROR)}class Y extends Error{constructor(e=[],n){const r=e.filter(i=>i.severity===K.ERROR);super(n||pn(r)),this.name="TemplateSyntaxError",this.code="TEMPLATE_SYNTAX_INVALID",this.issues=e}}class w extends Error{constructor({message:e,partCode:n,source:r,cause:i}={}){super(e||"Template rendering failed.",i?{cause:i}:void 0),this.name="TemplateRenderError",this.code="TEMPLATE_RENDER_FAILED",this.partCode=n,this.source=r}}function pn(t){if(!t.length)return"Template is invalid.";const[e]=t,n=e.partCode?` (${e.partCode}${e.line?`:${e.line}:${e.column}`:""})`:"",r=t.length>1?` and ${t.length-1} more issue(s)`:"";return`${e.code}: ${e.message}${n}${r}`}const ze="data-qw-layout",dn=`<([a-z][a-z0-9-]*)\\b[^>]*\\s${ze}\\s*=\\s*"([^"]*)"[^>]*>\\s*</\\1\\s*>`,mn="PUBLISHED",ot=()=>new RegExp(dn,"gi"),fn=t=>typeof(t==null?void 0:t.describe)=="function"?t.describe():t;function Tn(t){return`<div ${ze}="${t}"></div>`}function Ae(t){return[...new Set([...String(t||"").matchAll(ot())].map(([,,e])=>e))]}function Fe({layouts:t=[],layoutCode:e}={}){return e&&t.map(fn).filter(n=>(n==null?void 0:n.layoutCode)===e&&n.stateCode===mn).sort((n,r)=>r.version-n.version)[0]||null}function at({html:t,layouts:e=[]}={}){const n=new Set,r=new Set;return{html:String(t||"").replace(ot(),(s,o,a)=>{const c=Fe({layoutCode:a,layouts:e});return c?(n.add(`${c.layoutCode}@${c.version}`),c.html||""):(r.add(a),s)}),layoutRefs:[...n],missingLayoutCodes:[...r]}}function Ke(t){return String(t||"").trim()?Ae(t).map(e=>C({code:b.LAYOUT_NOT_ALLOWED,layoutCode:e,message:`Layout ${e} cannot be placed inside another layout.`,partCode:"layout"})):[C({code:b.LAYOUT_EMPTY,message:"The layout is empty.",partCode:"layout"})]}const qe=Object.freeze(["#","case","comment","for","if","unless"]),me=Object.freeze(["assign","capture"]),we=(t=!1)=>({...t?{optional:t}:{},types:["any"]}),_=(t,e=!1)=>({...e?{optional:e}:{},types:t}),Ge=Object.freeze([{description:'Format a timestamp (milliseconds) or date text, e.g. date: "%Y-%m-%d". Dates are UTC unless a time zone is given.',label:"date",name:"date",signature:[_(["number","string"]),_(["string"],!0),_(["number","string"],!0)]},{description:"The argument when the value is nil, false or empty.",name:"default",signature:[we(),we()]},{description:"Join list items with a separator.",label:"joined",name:"join",signature:[_(["array"]),_(["string"],!0)]},{description:"The given field of every list item.",name:"map",signature:[_(["array"]),_(["string"])]},{description:"List items whose field is truthy or equals a value.",name:"where",signature:[_(["array"]),_(["string"]),we(!0)]},{description:'List items for which an expression is true, e.g. where_exp: "line", "line.qty > 0".',name:"where_exp",signature:[_(["array"]),_(["string"]),_(["string"])]},{description:"The first list item.",label:"first",name:"first",signature:[_(["array"])]},{description:"Number of list items or characters.",label:"count",name:"size",signature:[_(["array","string"])]},{description:"Text in upper case.",label:"upper case",name:"upcase",signature:[_(["string"])]},{description:"Text in lower case.",label:"lower case",name:"downcase",signature:[_(["string"])]},{description:"Shorten text to a length, ending with an ellipsis.",label:"shortened",name:"truncate",signature:[_(["string"]),_(["number"],!0),_(["string"],!0)]},{description:"Text without HTML tags.",name:"strip_html",signature:[_(["string"])]},{description:"Add a number.",name:"plus",signature:[_(["number"]),_(["number"])]},{description:"Subtract a number.",name:"minus",signature:[_(["number"]),_(["number"])]},{description:"Multiply by a number.",name:"times",signature:[_(["number"]),_(["number"])]},{description:"Divide by a number.",name:"divided_by",signature:[_(["number"]),_(["number"])]},{description:"Round to a number of decimals.",label:"rounded",name:"round",signature:[_(["number"]),_(["number"],!0)]}].map(t=>Object.freeze({...t,builtin:!0,signature:Object.freeze(t.signature.map(Object.freeze))}))),hn=new Set(Ge.map(({name:t})=>t)),lt=Object.freeze({"&#34;":'"',"&#39;":"'","&#60;":"<","&#62;":">","&#x27;":"'","&amp;":"&","&apos;":"'","&gt;":">","&lt;":"<","&nbsp;":" ","&quot;":'"'}),En=/\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}/g;function ct(t){return String(t??"").replace(En,e=>e.replace(/&(?:#34|#39|#60|#62|#x27|amp|apos|gt|lt|nbsp|quot);/g,n=>lt[n]).replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/\xA0/g," ").replace(/[\u200B-\u200D\uFEFF]/g,""))}function Ze(t){return String(t??"").replace(/&(?:#34|#39|#60|#62|#x27|amp|apos|gt|lt|nbsp|quot);/g,e=>lt[e])}function ut({escape:t=!1,limits:e={},tags:n}={}){const r=new A.Liquid({cache:!1,dynamicPartials:!1,jsTruthy:!1,ownPropertyOnly:!0,strictFilters:!1,strictVariables:!1,timezoneOffset:0,...t?{outputEscape:"escape"}:{},...e});Object.keys(r.filters).forEach(s=>{hn.has(s)||r.unregisterFilter(s)});const i=r.filters.date;if(r.registerFilter("date",function(s,...o){return i.call(this,typeof s=="number"?new Date(s):s,...o)}),n){const s=new Set(n);Object.keys(r.tags).forEach(o=>{s.has(o)||delete r.tags[o]})}return r}const U="data-qw-block",fe="data-qw-params",bn=/^([A-Z][A-Z0-9_]*)@([1-9]\d*)$/,yn=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]),_n=ut();function H(t,{partCode:e,allowBlocks:n=!0}={}){const r=ct(typeof t=="string"?t:""),i=Nn(r,e),s=[],o=[],a=[];let c=0,l=he(r,c);for(;l;)a.push(l),c=l.end,l.issue?s.push(C({...l.issue,...i(l.start)})):n?o.push({...l.node,end:l.end,location:i(l.start),start:l.start}):s.push(C({blockRef:l.node.blockRef,code:b.BLOCK_NOT_ALLOWED,message:"Block instances are not allowed here.",...i(l.start)})),l=he(r,c);let f=[];try{f=_n.parse(An(r,a))}catch(u){s.push(On(u,i))}return{blockRefs:[...new Set(o.map(({blockRef:u})=>u))],blocks:o,issues:s,locate:i,templates:f,text:r}}function pt(t){const e=typeof t=="string"?t:"",n=new Set;let r=he(e,0);for(;r;)r.node&&n.add(r.node.blockRef),r=he(e,r.end);return[...n]}function On(t,e,n=0){var i;if(!(t!=null&&t.token)&&!/^(?:Parse|Tokenization|Liquid)Error$/.test((t==null?void 0:t.name)||""))throw t;const r=String(t.message||"Template syntax error.").replace(/, line:\d+, col:\d+$/,"");return C({code:b.SYNTAX_ERROR,message:r,...e?e(n+(((i=t.token)==null?void 0:i.begin)??0)):{}})}function dt(t){const e=bn.exec(typeof t=="string"?t.trim():"");return e?{blockCode:e[1],version:Number(e[2])}:null}function Te({blockCode:t,version:e}={}){return`${t}@${e}`}function gn({blockCode:t,version:e,params:n={},tagName:r="div"}={}){const i=JSON.stringify(n||{}).replace(/&/g,"&amp;").replace(/'/g,"&#39;");return`<${r} ${U}="${Te({blockCode:t,version:e})}" ${fe}='${i}'></${r}>`}function An(t,e){if(!e.length)return t;let n="",r=0;return e.forEach(({start:i,end:s})=>{n+=t.slice(r,i)+t.slice(i,s).replace(/[^\n]/g," "),r=s}),n+t.slice(r)}function he(t,e){let n=e;for(;n<t.length;){const r=t.indexOf(U,n);if(r===-1)return null;const i=t.lastIndexOf("<",r),s=i>=e?Cn(t,i):null;if(!s||s.end<=r||!Object.hasOwn(s.attributes,U)){n=r+U.length;continue}const o=s.selfClosing||yn.has(s.name)?s.end:Rn(t,s.name,s.end);if(o===-1)return{end:t.length,issue:{code:b.BLOCK_ELEMENT_INVALID,message:`Block element <${s.name}> is not closed.`},start:i};const a=dt(Ze(s.attributes[U]));if(!a)return{end:o,issue:{code:b.BLOCK_ELEMENT_INVALID,message:`Block reference "${s.attributes[U]}" must look like BLOCK_CODE@1.`},start:i};let c={};const l=s.attributes[fe];if(l){try{c=JSON.parse(Ze(l))}catch{c=null}if(!c||typeof c!="object"||Array.isArray(c))return{end:o,issue:{blockRef:Te(a),code:b.BLOCK_PARAMS_INVALID,message:`${fe} must be a JSON object.`},start:i}}return{end:o,node:{blockCode:a.blockCode,blockRef:Te(a),params:c,type:"Block",version:a.version},start:i}}return null}function Cn(t,e){const n=/^<([A-Z][\w-]*)/i.exec(t.slice(e));if(!n)return null;const r={};let i=e+n[0].length;for(;i<t.length;){const s=t.slice(i),o=/^\s*(\/?)>/.exec(s);if(o)return{attributes:r,end:i+o[0].length,name:n[1].toLowerCase(),selfClosing:o[1]==="/"};const a=/^\s+([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/.exec(s);if(!a)return null;r[a[1].toLowerCase()]=a[2]??a[3]??a[4]??"",i+=a[0].length}return null}function Rn(t,e,n){const r=new RegExp(`<(/?)${e}(?=[\\s/>])[^>]*>`,"gi");r.lastIndex=n;let i=1,s=r.exec(t);for(;s;){if(s[1]){if(i-=1,i===0)return s.index+s[0].length}else s[0].endsWith("/>")||(i+=1);s=r.exec(t)}return-1}function Nn(t,e){const n=[0];for(let r=0;r<t.length;r+=1)t[r]===`
2
- `&&n.push(r+1);return r=>{let i=0;for(;i+1<n.length&&n[i+1]<=r;)i+=1;return{column:r-n[i]+1,line:i+1,offset:r,...e?{partCode:e}:{}}}}const Sn=["active","created","creator","deleted","modified","owner","revision"],Ln=["contextCode","name","templateCode","templateSyntaxVersion"],Pn=["contextCode","name","templateSyntaxVersion"];class mt extends g.TenantAwareEntity{constructor(e={}){e=e||{},super(e),this._type=e._type||"Template",this.contextCode=e.contextCode,this.name=e.name,this.partContent=et(e.partContent),this.templateCode=e.templateCode,this.templateSyntaxVersion=Number(e.templateSyntaxVersion||Oe)}static get _classname(){return"Template"}static get _superclass(){return"Template"}static get kind(){return null}static get partDefinitions(){var e;return((e=this.kind)==null?void 0:e.partDefinitions)||[]}get isValid(){return super.isValid&&!!this.templateCode&&!!this.contextCode}getCode(){return this.templateCode}getId(){return this.id}getContentParts(){return this.constructor.partDefinitions.map(e=>({...e,content:this.partContent[e.partCode]??""}))}getPartContent(e){return this.partContent[e]??""}getBlockRefs(){const e=new Set;return this.getContentParts().forEach(({content:n})=>{pt(n).forEach(r=>e.add(r))}),[...e]}getLayoutCodes(){return[...new Set(this.getContentParts().flatMap(({content:e})=>Ae(e)))]}setPartContent(e,n){if(!this.constructor.partDefinitions.some(r=>r.partCode===e))throw new RangeError(`${this.constructor._classname} has no part "${e}".`);return n===null?delete this.partContent[e]:this.partContent[e]=String(n),this}update(e={}){return Pn.forEach(n=>{Object.hasOwn(e,n)&&(this[n]=n==="templateSyntaxVersion"?Number(e[n]):e[n])}),e.partContent&&typeof e.partContent=="object"&&Object.entries(e.partContent).forEach(([n,r])=>{this.setPartContent(n,r)}),super.update(e)}toJSON(){return this.toObject()}toObject(){const e={_type:this._type,meta:g.copySerializableProperties(this.meta,Sn),metadata:g.copySerializableKeyValueObjects(this.metadata),partContent:et(this.partContent),remarks:g.copySerializableKeyValueObjects(this.remarks),tenantCode:this.tenantCode,...g.copySerializableProperties(this,Ln)};return typeof this.id<"u"&&(e.id=this.id),e}}function et(t){return!t||typeof t!="object"?{}:Object.entries(t).reduce((e,[n,r])=>(typeof r=="string"&&(e[n]=r),e),{})}const k=Object.freeze({DEPRECATED:"DEPRECATED",DRAFT:"DRAFT",PUBLISHED:"PUBLISHED"}),In=new Set(Object.values(k)),wn=Object.freeze({DEPRECATED:new Set,DRAFT:new Set(["PUBLISHED"]),PUBLISHED:new Set(["DEPRECATED"])});class Ee extends g.Lifecycle{constructor(e={}){super(e),this._setPublicationState(e.publication)}static get _classname(){return"LifecycleTemplateBlock"}static get entityType(){return"TemplateBlock"}static create({actionRevision:e,modified:n=Date.now()}={}){return this.init({publication:{actionRevision:e,modified:n,stateCode:k.DRAFT}})}canTransition(e,n){var i,s;const r=(i=this.getState(e))==null?void 0:i.stateCode;return e==="publication"&&!!((s=wn[r])!=null&&s.has(n))}transition(e,{actionRevision:n,modified:r=Date.now(),stateCode:i}={}){var s;if(!this.canTransition(e,i))throw new Error(`Invalid ${this.constructor.entityType} lifecycle transition: ${e} ${((s=this.getState(e))==null?void 0:s.stateCode)||"UNKNOWN"} -> ${i||"UNKNOWN"}`);return this._setPublicationState({actionRevision:n,modified:r,stateCode:i})}_setPublicationState(e){if(!In.has(e==null?void 0:e.stateCode))throw new TypeError(`Invalid ${this.constructor.entityType} lifecycle state for publication.`);return this._setState("publication",e)}}const N=Object.freeze({BOOLEAN:"boolean",MULTI_SELECT:"multiSelect",SELECT:"select",TEXT:"text"}),Dn=new Set(Object.values(N)),tt=new Set([N.MULTI_SELECT,N.SELECT]);function G(t=[]){const e=[],n=new Set;return{definitions:(Array.isArray(t)?t:[]).map((i,s)=>{const{paramCode:o,type:a,label:c,description:l,required:f=!1,options:u=[]}=i||{};return!J.test(o||"")||o.startsWith("__")?e.push(`Param #${s+1} has an invalid paramCode "${o}".`):n.has(o)&&e.push(`Param "${o}" is declared twice.`),n.add(o),Dn.has(a)||e.push(`Param "${o}" has unsupported type "${a}".`),tt.has(a)&&(!Array.isArray(u)||!u.length?e.push(`Param "${o}" requires options.`):u.some(d=>!J.test(String((d==null?void 0:d.value)??"")))&&e.push(`Param "${o}" option values must match [A-Za-z_]\\w*.`)),{...l?{description:l}:{},..."default"in(i||{})?{default:i.default}:{},label:c||o,...tt.has(a)?{options:u.map(({value:d,label:E})=>({label:E||d,value:d}))}:{},paramCode:o,required:!!f,type:a}}),errors:e}}function Ye(t=[],e={}){const n=[],r=e&&typeof e=="object"?e:{},i=new Set(t.map(({paramCode:o})=>o));Object.keys(r).forEach(o=>{i.has(o)||n.push(`Unknown param "${o}".`)});const s=t.reduce((o,a)=>{const{paramCode:c,type:l,required:f}=a,u=Object.hasOwn(r,c)?r[c]:a.default;if(u==null||u==="")return f&&n.push(`Param "${c}" is required.`),o[c]=l===N.MULTI_SELECT?[]:l===N.BOOLEAN?!1:null,o;const d=jn(a,u);return d&&n.push(d),o[c]=u,o},{});return{errors:n,values:s}}function vn(t=[],e={}){return t.reduce((n,{paramCode:r,type:i})=>(i===N.MULTI_SELECT?n[r]=(Array.isArray(e[r])?e[r]:[]).reduce((s,o)=>(s[o]=!0,s),{}):n[r]=e[r]??null,n),{})}function He(t=[]){return{fields:t.reduce((e,{paramCode:n,type:r,label:i,options:s})=>(r===N.MULTI_SELECT?e[n]={fields:s.reduce((o,a)=>(o[a.value]={label:a.label,type:"boolean"},o),{}),label:i,type:"object"}:e[n]={label:i,type:r===N.BOOLEAN?"boolean":"string"},e),{}),type:"object"}}function jn({paramCode:t,type:e,options:n=[]},r){const i=new Set(n.map(s=>s.value));switch(e){case N.BOOLEAN:return typeof r=="boolean"?null:`Param "${t}" must be a boolean.`;case N.TEXT:return typeof r=="string"?null:`Param "${t}" must be text.`;case N.SELECT:return i.has(r)?null:`Param "${t}" must be one of ${[...i].join(", ")}.`;case N.MULTI_SELECT:return Array.isArray(r)&&r.every(s=>i.has(s))?null:`Param "${t}" must be a list of ${[...i].join(", ")}.`;default:return null}}const Ce=Object.freeze({EMAIL:"EMAIL"}),M=Object.freeze({TEXT_HTML:"text/html",TEXT_PLAIN:"text/plain"}),B=Object.freeze({MAILBOX:"mailbox",MAILBOX_LIST:"mailboxList",TEXT:"text"}),Re=Object.freeze({fieldDefinitions:Object.freeze([Object.freeze({emailExpression:!1,fieldCode:"from",label:"From",nameExpression:!0,type:B.MAILBOX}),Object.freeze({emailExpression:!0,fieldCode:"replyTo",label:"Reply to",nameExpression:!0,type:B.MAILBOX}),Object.freeze({emailExpression:!0,fieldCode:"cc",label:"CC",nameExpression:!0,type:B.MAILBOX_LIST}),Object.freeze({emailExpression:!0,fieldCode:"bcc",label:"BCC",nameExpression:!0,type:B.MAILBOX_LIST})]),label:"Email",partDefinitions:Object.freeze([Object.freeze({contentType:M.TEXT_PLAIN,label:"Subject",partCode:"subject",required:!0}),Object.freeze({contentType:M.TEXT_HTML,label:"HTML",partCode:"html",required:!0}),Object.freeze({contentType:M.TEXT_PLAIN,label:"Plain text",partCode:"text",required:!1})]),previewModes:Object.freeze([Object.freeze({label:"Desktop",previewModeCode:"DESKTOP",width:1024}),Object.freeze({label:"Tablet",previewModeCode:"TABLET",width:768}),Object.freeze({label:"Mobile",previewModeCode:"MOBILE",width:375})]),previewViews:Object.freeze([Object.freeze({label:"Inbox",previewViewCode:"INBOX"}),Object.freeze({label:"HTML",previewViewCode:"HTML"}),Object.freeze({label:"Plain text",previewViewCode:"TEXT"})]),templateKindCode:Ce.EMAIL}),Bn=Object.freeze({[Ce.EMAIL]:Re});function We(t){return Bn[t]||null}function Mn(t){return structuredClone({fieldDefinitions:t.fieldDefinitions||[],label:t.label,partDefinitions:t.partDefinitions||[],previewModes:t.previewModes||[],previewViews:t.previewViews||[],templateKindCode:t.templateKindCode})}function xn(t,e={}){return(t.fieldDefinitions||[]).flatMap(({fieldCode:n,type:r,emailExpression:i,nameExpression:s,expressionAllowed:o=!1})=>{const a=e[n];return r===B.TEXT?typeof a=="string"&&a?[{content:a,expressionAllowed:!!o,fieldPath:n}]:[]:(r===B.MAILBOX_LIST?Array.isArray(a)?a:[]:a?[a]:[]).flatMap((l,f)=>{const u=r===B.MAILBOX_LIST?`${n}[${f}]`:n;return[{content:(l==null?void 0:l.email)||"",expressionAllowed:i,fieldPath:`${u}.email`},{content:(l==null?void 0:l.name)||"",expressionAllowed:s,fieldPath:`${u}.name`}].filter(({content:d})=>d)})})}const ft=new Map(Ge.map(t=>[t.name,t])),L=Object.freeze({type:"number"}),Xe=Object.freeze({type:"string"}),Me=Object.freeze({type:"boolean"}),$n=Object.freeze({fields:Object.freeze({first:Me,index:L,index0:L,last:Me,length:L,rindex:L,rindex0:L}),label:"Loop",type:"object"}),Un=new Set([V,"forloop"]),kn=new Set(["where","where_exp"]),Vn=new Set(["date","downcase","join","strip_html","truncate","upcase"]),zn=new Set(["divided_by","minus","plus","round","size","times"]);function Ne(t,{locate:e,text:n,roots:r=null,variables:i=new Map,functionsByName:s=null,allowedFunctionNames:o=null,allowAssign:a=!1}={}){const c={allowAssign:a,allowedFunctionNames:o,assigned:new Map,functionsByName:s,issues:[],locate:e,requiredRoots:new Set,roots:r,text:n};return j(t,i,c),{issues:c.issues,requiredRoots:[...c.requiredRoots].sort()}}function Fn(t,e){return ft.get(t)||(e==null?void 0:e.get(t))||null}function j(t,e,n){(t||[]).forEach(r=>{const{token:i}=r;if(A.TypeGuards.isOutputToken(i)){const s=be(n,i),o=X(r.value,e,n,s);o&&(o.type==="list"||o.type==="object")&&S(n,b.OUTPUT_NOT_SCALAR,`"${s}" outputs a ${o.type}; output a field of it or use a filter such as join or size.`,i,s);return}A.TypeGuards.isTagToken(i)&&Kn(r,e,n)})}function Kn(t,e,n){var o;const{name:r,token:i}=t,s=be(n,i);if(!qe.includes(r)&&!(n.allowAssign&&me.includes(r))){const a=me.includes(r)?" outside block fragments":"";S(n,b.TAG_NOT_ALLOWED,`Tag "${r}" is not allowed${a}.`,i,s);return}switch(r){case"if":case"unless":t.branches.forEach(a=>{X(a.value,e,n,s),j(a.templates,e,n)}),j(t.elseTemplates,e,n);break;case"case":X(t.value,e,n,s),t.branches.forEach(a=>{a.values.forEach(c=>D(c,e,n,s)),j(a.templates,e,n)}),j(t.elseTemplates,e,n);break;case"for":{const{variable:a}=t;De(a,e,n,i,s);const c=D(t.collection,e,n,s);let l=null;A.TypeGuards.isRangeToken(t.collection)?l=L:c&&c.type!=="list"?S(n,b.LOOP_SOURCE_NOT_LIST,`"${be(n,t.collection)}" is not a list.`,t.collection,s):c&&(l=c.item||null),Object.values(((o=t.hash)==null?void 0:o.hash)||{}).forEach(f=>{f&&D(f,e,n,s)}),j(t.templates,new Map([...e,[a,l],["forloop",$n]]),n),j(t.elseTemplates,e,n);break}case"assign":{De(t.key,e,n,i,s),n.assigned.set(t.key,X(t.value,e,n,s));break}case"capture":De(t.variable,e,n,i,s),j(t.templates,e,n),n.assigned.set(t.variable,Xe);break}}function De(t,e,n,r,i){!J.test(t||"")||t.startsWith("__")?S(n,b.VARIABLE_INVALID,`Variable "${t}" must match [A-Za-z_]\\w* and must not start with "__".`,r,i):(Ue.includes(t)||e.has(t)||n.roots&&Object.hasOwn(n.roots,t))&&S(n,b.VARIABLE_INVALID,`Variable "${t}" conflicts with a data root, a loop variable or a reserved name.`,r,i)}function X(t,e,n,r){if(!t)return null;let i=Tt(t.initial,e,n,r);return(t.filters||[]).forEach(s=>{i=Gn(s,i,e,n,r)}),i}function Tt(t,e,n,r){const i=[...(t==null?void 0:t.postfix)||[]],s=i.map(o=>D(o,e,n,r));return i.length===1?s[0]:i.some(o=>A.TypeGuards.isOperatorToken(o))?Me:null}function D(t,e,n,r){return t?A.TypeGuards.isPropertyAccessToken(t)?qn(t,e,n,r):A.TypeGuards.isRangeToken(t)?(D(t.lhs,e,n,r),D(t.rhs,e,n,r),{item:L,type:"list"}):A.TypeGuards.isNumberToken(t)?L:A.TypeGuards.isQuotedToken(t)?Xe:t.initial?X(t,e,n,r):null:null}function qn(t,e,n,r){const[i,...s]=t.props||[],o=i==null?void 0:i.content;if(typeof o!="string"||!A.TypeGuards.isWordToken(i))return null;let a;if(e.has(o))a=e.get(o);else if(n.assigned.has(o))a=n.assigned.get(o);else if(n.roots)if(Object.hasOwn(n.roots,o))n.requiredRoots.add(o),a=n.roots[o];else return S(n,b.ROOT_UNKNOWN,`"${o}" is not a data root of this context (${Object.keys(n.roots).join(", ")}) or a template variable.`,t,r),null;else return o!==V&&n.requiredRoots.add(o),null;for(const c of s){if(!a)return null;if(A.TypeGuards.isPropertyAccessToken(c)||c.initial){if(D(c,e,n,r),a.type==="list"){a=a.item||null;continue}return a.type==="object"?null:se(n,t,r,"only a list or an object can be indexed.")}if(A.TypeGuards.isNumberToken(c)){if(a.type!=="list")return se(n,t,r,"only a list can be indexed.");a=a.item||null;continue}const l=c.content;if(a.type==="list")if(l==="size")a=L;else if(l==="first"||l==="last")a=a.item||null;else return se(n,t,r,`a list has no field "${l}" (use size, first, last or a loop).`);else if(a.type==="string"&&l==="size")a=L;else if(a.type==="object"&&a.fields&&Object.hasOwn(a.fields,l))a=a.fields[l];else return a.type==="object"&&!Un.has(o)?null:se(n,t,r,`field "${l}" does not exist.`)}return a}function se(t,e,n,r){return S(t,b.PATH_UNKNOWN,`"${be(t,e)}": ${r}`,e,n),null}function Gn(t,e,n,r,i){var O;const{name:s,args:o=[]}=t;if(!s)return S(r,b.SYNTAX_ERROR,'A filter name is missing after "|".',t.token,i),null;const a=o.filter(m=>!Array.isArray(m)),c=o.filter(m=>Array.isArray(m));a.forEach(m=>D(m,n,r,i)),c.forEach(([,m])=>D(m,n,r,i));const l=ft.get(s),f=l||((O=r.functionsByName)==null?void 0:O.get(s));if(!f)return(r.functionsByName||!s.startsWith("__"))&&S(r,b.UNKNOWN_FUNCTION,`Filter "${s}" is not available.`,t.token,i),null;if(!l&&r.allowedFunctionNames&&!r.allowedFunctionNames.has(s))return S(r,b.FUNCTION_NOT_ALLOWED,`Filter "${s}" is not allowed in this data context.`,t.token,i),null;const u=(f.signature||[]).slice(1),d=u.filter(m=>!m.optional&&!m.variadic).length,E=u.some(m=>m.variadic);if(c.length||a.length<d||!E&&a.length>u.length){const m=E?`at least ${d}`:d===u.length?d:`${d}-${u.length}`;return S(r,b.FUNCTION_ARGUMENTS_INVALID,`Filter "${s}" expects ${m} argument(s)${c.length?" and no named arguments":""}, got ${a.length}.`,t.token,i),null}return l?Yn(s,e,a,n,r,i):null}function Yn(t,e,n,r,i,s){const o=(e==null?void 0:e.type)==="list"?e.item:null,a=l=>!o||o.type!=="object"||typeof l!="string"?null:o.fields&&Object.hasOwn(o.fields,l)?o.fields[l]:null,c=l=>l&&A.TypeGuards.isQuotedToken(l)?l.content:null;if(t==="where")return a(c(n[0])),e;if(t==="where_exp")return Hn(c(n[0]),n[1],o,r,i,s),e;if(kn.has(t))return e;if(t==="map"){const l=a(c(n[0]));return(e==null?void 0:e.type)==="list"?{item:l,type:"list"}:null}return t==="first"?o:t==="default"?e:zn.has(t)?L:Vn.has(t)?Xe:null}function Hn(t,e,n,r,i,s){if(!t||!e||!A.TypeGuards.isQuotedToken(e))return;let o;try{o=new A.Tokenizer(e.content).readExpression()}catch(c){S(i,b.SYNTAX_ERROR,`where_exp expression: ${c.message}`,e,s);return}const a={...i,text:e.content};a.issues=[],Tt(o,new Map([...r,[t,n]]),a,s),a.issues.forEach(c=>i.issues.push({...c,...i.locate(e.begin)}))}function be(t,e){return t.text&&e?t.text.slice(e.begin,e.end):""}function S(t,e,n,r,i){t.issues.push(C({code:e,message:n,...t.locate((r==null?void 0:r.begin)??0),...i?{source:i}:{}}))}const Wn=/\{\{|\{%/,ve=Object.freeze({DEPRECATED:"DEPRECATED",DRAFT:"DRAFT",PUBLISHED:"PUBLISHED"});function Xn({template:t,kind:e,context:n,functions:r,blocks:i,allowedDeprecatedBlockRefs:s,layouts:o=[]}={}){var h;const a=typeof(t==null?void 0:t.toObject)=="function"?t.toObject():t||{},c=e||((h=t==null?void 0:t.constructor)==null?void 0:h.kind)||We(a.templateKindCode),l=[],f=new Set,u=new Set;if(!c)throw new TypeError("checkTemplate requires a template kind.");const d=a.templateSyntaxVersion??Oe;if(!$e.includes(d))return l.push(C({code:b.SYNTAX_VERSION_UNSUPPORTED,message:`Template syntax version ${d} is not supported.`})),{blockRefs:[],issues:l,layoutCodes:[],valid:!1};const E=yt({allowedDeprecatedBlockRefs:s,blocks:i,context:n,functions:r}),O=a.partContent||{},m=new Set(c.partDefinitions.map(({partCode:p})=>p));return c.partDefinitions.forEach(({partCode:p,required:T})=>{const y=O[p];if(typeof y!="string"||!y.trim()){T&&l.push(C({code:b.PART_REQUIRED,message:`Part "${p}" is required.`,partCode:p}));return}const R=ye(y,{allowBlocks:!0,env:E,partCode:p});l.push(...R.issues),R.blockRefs.forEach(I=>f.add(I)),Ae(y).forEach(I=>{u.has(I)||l.push(...Qn(I,{env:E,layouts:o,partCode:p})),u.add(I)})}),Object.keys(O).forEach(p=>{m.has(p)||l.push(C({code:b.PART_UNKNOWN,message:`Part "${p}" is not declared by template kind ${c.templateKindCode}.`,partCode:p}))}),xn(c,a).forEach(({fieldPath:p,content:T,expressionAllowed:y})=>{if(!y){Wn.test(T)&&l.push(C({code:b.FIELD_EXPRESSION_NOT_ALLOWED,message:`Field "${p}" must be a fixed value.`,partCode:p}));return}l.push(...ye(T,{allowBlocks:!1,env:E,partCode:p}).issues)}),{blockRefs:[...f],issues:l,layoutCodes:[...u],valid:!z(l)}}function Qn(t,{env:e,layouts:n,partCode:r}){const i=Fe({layoutCode:t,layouts:n});if(!i)return[C({code:b.LAYOUT_NOT_FOUND,layoutCode:t,message:`Layout ${t} has no published version.`,partCode:r})];const s=`${i.layoutCode}@${i.version}`;return[...ye(i.html||"",{allowBlocks:!1,env:e,partCode:r}).issues,...Ke(i.html)].map(o=>({...o,layoutRef:s,message:`${s}: ${o.message}`,partCode:r}))}function Jn({content:t,partCode:e,allowBlocks:n=!0,context:r,functions:i,blocks:s,allowedDeprecatedBlockRefs:o}={}){const a=yt({allowedDeprecatedBlockRefs:o,blocks:s,context:r,functions:i}),c=ye(t,{allowBlocks:n,env:a,partCode:e});return{...c,valid:!z(c.issues)}}function ht({fragment:t,params:e,functions:n,context:r}={}){const{definitions:i,errors:s}=G(e),o=s.map(c=>C({code:b.BLOCK_PARAMS_INVALID,message:c})),a=bt(t,{allowAssign:!0,context:r,functions:n,paramsRoot:He(i)});return o.push(...a.issues),{issues:o,requiredRoots:a.requiredRoots,valid:!z(o)}}function Et({html:t,functions:e}={}){const n=bt(t||"",{allowAssign:!1,functions:e,paramsRoot:He([])}),r=[...n.issues.map(i=>({...i,partCode:"layout"})),...Ke(t)];return{issues:r,requiredRoots:n.requiredRoots,valid:!z(r)}}function bt(t,{allowAssign:e,context:n,functions:r,paramsRoot:i}){const s=ee(n),o=H(t,{allowBlocks:!1}),a=r||(s?te():null),c=Ne(o.templates,{allowAssign:e,allowedFunctionNames:s?new Set(s.functionNames||[]):null,functionsByName:a?new Map(a.map(l=>[l.name,l])):null,locate:o.locate,roots:(s==null?void 0:s.roots)||null,text:o.text,variables:new Map([[V,i]])});return{issues:[...o.issues,...c.issues],requiredRoots:c.requiredRoots}}function yt({allowedDeprecatedBlockRefs:t=[],blocks:e=[],context:n,functions:r}){const i=ee(n);if(!i||!i.roots)throw new TypeError("Template checks require a data context.");const s=r||te();return{allowedDeprecatedBlockRefs:new Set(t),allowedFunctionNames:new Set(i.functionNames||[]),blocksByRef:new Map(e.map(o=>{const a=typeof o.describe=="function"?o.describe():o;return[`${a.blockCode}@${a.version}`,a]})),contextCode:i.contextCode,functionsByName:new Map(s.map(o=>[o.name,o])),roots:i.roots}}function ye(t,{allowBlocks:e,env:n,partCode:r}){const i=H(t,{allowBlocks:e,partCode:r}),s=[...i.issues];return s.push(...Ne(i.templates,{allowedFunctionNames:n.allowedFunctionNames,functionsByName:n.functionsByName,locate:i.locate,roots:n.roots,text:i.text}).issues),i.blocks.forEach(o=>Zn(o,n,s)),{blockRefs:i.blockRefs,issues:s}}function Zn(t,e,n){const{blockRef:r,location:i}=t,s=(u,d,E)=>n.push(C({blockRef:r,code:u,message:d,severity:E,...i})),o=e.blocksByRef.get(r);if(!o){s(b.UNKNOWN_BLOCK,`Block ${r} does not exist.`);return}const a=o.stateCode||ve.PUBLISHED;if(a===ve.DRAFT){s(b.BLOCK_NOT_PUBLISHED,`Block ${r} is not published.`);return}if(a===ve.DEPRECATED){const u=e.allowedDeprecatedBlockRefs.has(r);s(b.BLOCK_DEPRECATED,u?`Block ${r} is deprecated; consider a newer version.`:`Block ${r} is deprecated and cannot be added.`,u?K.WARNING:K.ERROR)}if(o.contextCode!==e.contextCode){s(b.BLOCK_CONTEXT_MISMATCH,`Block ${r} is for data context ${o.contextCode||"(none)"}, not ${e.contextCode}.`);return}const c=(o.requiredRoots||[]).filter(u=>!Object.hasOwn(e.roots,u));c.length&&s(b.BLOCK_ROOT_NOT_IN_CONTEXT,`Block ${r} requires data roots not in this context: ${c.join(", ")}.`);const{definitions:l}=G(o.params),{errors:f}=Ye(l,t.params);if(f.forEach(u=>s(b.BLOCK_PARAMS_INVALID,`${r}: ${u}`)),typeof o.fragment=="string"&&!c.length){const u=H(o.fragment,{allowBlocks:!1}),d=Ne(u.templates,{allowAssign:!0,allowedFunctionNames:e.allowedFunctionNames,functionsByName:e.functionsByName,locate:u.locate,roots:e.roots,text:u.text,variables:new Map([[V,He(l)]])});[...u.issues,...d.issues].forEach(E=>n.push(C({...i,blockRef:r,code:E.code,message:`${r}: ${E.message}`,severity:E.severity})))}}const er=["active","created","creator","deleted","modified","owner","revision"],tr=["blockCode","category","contextCode","description","fragment","name","tenantCode","version"],nt=["category","contextCode","description","fragment","name","params"],nr=/^[A-Z][A-Z0-9_]*$/,rr=Object.freeze({DEPRECATED:"TEMPLATE_BLOCK_DEPRECATED",PUBLISHED:"TEMPLATE_BLOCK_PUBLISHED"});class _t extends g.TrackedEntity{constructor(e={}){e=e||{},super(e),this._type=e._type||"TemplateBlock",this.blockCode=e.blockCode,this.category=e.category||"",this.contextCode=e.contextCode||"",this.description=e.description||"",this.fragment=typeof e.fragment=="string"?e.fragment:"",this.lifecycle=e.lifecycle?Ee.init(e.lifecycle):null,this.name=e.name||"",this.params=G(e.params).definitions,this.requiredRoots=Array.isArray(e.requiredRoots)?[...e.requiredRoots]:[],this.tenantCode=e.tenantCode||void 0,this.version=Number(e.version)}static get _classname(){return"TemplateBlock"}static get _superclass(){return"TemplateBlock"}static create({actionRevision:e=1,modified:n=Date.now(),...r}={}){return this.init({...r,lifecycle:Ee.create({actionRevision:e,modified:n}).toObject(),meta:{...r.meta,revision:e}})}get isValid(){var e;return super.isValid&&nr.test(this.blockCode||"")&&!!this.contextCode&&Number.isInteger(this.version)&&this.version>=1&&!!((e=this.lifecycle)!=null&&e.isValid)}get blockRef(){return`${this.blockCode}@${this.version}`}get stateCode(){var e,n;return((n=(e=this.lifecycle)==null?void 0:e.getState("publication"))==null?void 0:n.stateCode)||null}get isDraft(){return this.stateCode===k.DRAFT}getCode(){return this.blockRef}getId(){return this.id}check({context:e,functions:n}={}){var r;if(e&&((r=ee(e))==null?void 0:r.contextCode)!==this.contextCode)throw new TypeError(`TemplateBlock ${this.blockRef} belongs to data context ${this.contextCode}.`);return ht({context:e,fragment:this.fragment,functions:n,params:this.params})}update(e={}){if(nt.some(r=>Object.hasOwn(e,r))&&!this.isDraft)throw new Error(`TemplateBlock ${this.blockRef} is ${this.stateCode}; publish changes as a new version.`);return nt.forEach(r=>{Object.hasOwn(e,r)&&(this[r]=r==="params"?G(e.params).definitions:e[r]??"")}),super.update(e)}publish({actionRevision:e=this.revision+1,context:n,modified:r=Date.now(),functions:i}={}){const s=this.check({context:n,functions:i});if(!s.valid)throw new Y(s.issues.map(o=>({...o,blockRef:this.blockRef})));return this.lifecycle.transition("publication",{actionRevision:e,modified:r,stateCode:k.PUBLISHED}),this.requiredRoots=s.requiredRoots,this.meta.revision=e,this.setModified()}deprecate({actionRevision:e=this.revision+1,modified:n=Date.now()}={}){return this.lifecycle.transition("publication",{actionRevision:e,modified:n,stateCode:k.DEPRECATED}),this.meta.revision=e,this.setModified()}createEntityAction({actionCode:e,actor:n,previousStateCode:r,timestamp:i=Date.now(),...s}={}){return g.EntityAction.init({...s,actionCode:e,actor:n,entityCode:this.blockRef,entityId:this.getId(),entityRevision:this.revision,entityType:this._type,lifecycleChange:{publication:{from:r,to:this.stateCode}},...this.tenantCode?{tenantCode:this.tenantCode}:{},timestamp:i})}describe(){return{blockCode:this.blockCode,blockRef:this.blockRef,category:this.category,contextCode:this.contextCode,description:this.description,fragment:this.fragment,name:this.name,params:g.copySerializableValue(this.params),requiredRoots:[...this.requiredRoots],stateCode:this.stateCode,...this.tenantCode?{tenantCode:this.tenantCode}:{},version:this.version}}toJSON(){return this.toObject()}toObject(){const e={_type:this._type,...this.lifecycle?{lifecycle:this.lifecycle.toObject()}:{},meta:g.copySerializableProperties(this.meta,er),params:g.copySerializableValue(this.params),requiredRoots:[...this.requiredRoots],...g.copySerializableProperties(this,tr)};return typeof this.id<"u"&&(e.id=this.id),e}}const oe=["email","name"],ir=["bcc","cc","from","replyTo"];class Ot extends mt{constructor(e={}){if(e=e||{},Array.isArray(e.to)?e.to.length:e.to)throw new TypeError('TemplateEmail does not accept "to"; recipients come from the sending job.');super(e),this._type=e._type||"TemplateEmail",this.bcc=je(e.bcc),this.cc=je(e.cc),this.from=le(e.from),this.replyTo=le(e.replyTo)}static get _classname(){return"TemplateEmail"}static get kind(){return Re}update(e={}){if(Array.isArray(e.to)?e.to.length:e.to)throw new TypeError('TemplateEmail does not accept "to"; recipients come from the sending job.');return ir.forEach(n=>{Object.hasOwn(e,n)&&(this[n]=n==="cc"||n==="bcc"?je(e[n]):le(e[n]))}),super.update(e)}toObject(){return{...super.toObject(),bcc:this.bcc.map(e=>g.copySerializableProperties(e,oe)),cc:this.cc.map(e=>g.copySerializableProperties(e,oe)),from:this.from?g.copySerializableProperties(this.from,oe):null,replyTo:this.replyTo?g.copySerializableProperties(this.replyTo,oe):null}}}function le(t){return t?typeof t=="string"?t.trim()?{email:t.trim()}:null:typeof t!="object"||!t.email?null:{email:String(t.email).trim(),...t.name?{name:String(t.name)}:{}}:null}function je(t){return(Array.isArray(t)?t:[]).map(le).filter(Boolean)}const ce=k;class xe extends Ee{static get _classname(){return"LifecycleTemplateLayout"}static get entityType(){return"TemplateLayout"}}const sr=["active","created","creator","deleted","modified","owner","revision"],or=["description","eventShortCode","html","layoutCode","name","templateKindCode","tenantCode","version"],rt=["description","html","name"],ar=/^[A-Z][A-Z0-9_]*$/,lr=Object.freeze({DEPRECATED:"TEMPLATE_LAYOUT_DEPRECATED",PUBLISHED:"TEMPLATE_LAYOUT_PUBLISHED"});class cr extends g.TrackedEntity{constructor(e={}){e=e||{},super(e),this._type=e._type||"TemplateLayout",this.description=e.description||"",this.eventShortCode=e.eventShortCode||void 0,this.html=typeof e.html=="string"?e.html:"",this.layoutCode=e.layoutCode,this.lifecycle=e.lifecycle?xe.init(e.lifecycle):null,this.name=e.name||"",this.requiredRoots=Array.isArray(e.requiredRoots)?[...e.requiredRoots]:[],this.templateKindCode=e.templateKindCode||Ce.EMAIL,this.tenantCode=e.tenantCode||void 0,this.version=Number(e.version)}static get _classname(){return"TemplateLayout"}static get _superclass(){return"TemplateLayout"}static create({actionRevision:e=1,modified:n=Date.now(),...r}={}){return this.init({...r,lifecycle:xe.create({actionRevision:e,modified:n}).toObject(),meta:{...r.meta,revision:e}})}get isValid(){var e;return super.isValid&&ar.test(this.layoutCode||"")&&Number.isInteger(this.version)&&this.version>=1&&!!((e=this.lifecycle)!=null&&e.isValid)}get layoutRef(){return`${this.layoutCode}@${this.version}`}get stateCode(){var e,n;return((n=(e=this.lifecycle)==null?void 0:e.getState("publication"))==null?void 0:n.stateCode)||null}get isDraft(){return this.stateCode===ce.DRAFT}getCode(){return this.layoutRef}getId(){return this.id}check({functions:e}={}){return Et({functions:e,html:this.html})}update(e={}){if(rt.some(r=>Object.hasOwn(e,r))&&!this.isDraft)throw new Error(`TemplateLayout ${this.layoutRef} is ${this.stateCode}; publish changes as a new version.`);return rt.forEach(r=>{Object.hasOwn(e,r)&&(this[r]=e[r]??"")}),super.update(e)}publish({actionRevision:e=this.revision+1,modified:n=Date.now(),functions:r}={}){const i=this.check({functions:r});if(!i.valid)throw new Y(i.issues.map(s=>({...s,layoutRef:this.layoutRef})));return this.lifecycle.transition("publication",{actionRevision:e,modified:n,stateCode:ce.PUBLISHED}),this.requiredRoots=i.requiredRoots,this.meta.revision=e,this.setModified()}deprecate({actionRevision:e=this.revision+1,modified:n=Date.now()}={}){return this.lifecycle.transition("publication",{actionRevision:e,modified:n,stateCode:ce.DEPRECATED}),this.meta.revision=e,this.setModified()}createEntityAction({actionCode:e,actor:n,previousStateCode:r,timestamp:i=Date.now(),...s}={}){return g.EntityAction.init({...s,actionCode:e,actor:n,entityCode:this.layoutRef,entityId:this.getId(),entityRevision:this.revision,entityType:this._type,lifecycleChange:{publication:{from:r,to:this.stateCode}},...this.tenantCode?{tenantCode:this.tenantCode}:{},timestamp:i})}describe(){return{description:this.description,...this.eventShortCode?{eventShortCode:this.eventShortCode}:{},html:this.html,layoutCode:this.layoutCode,layoutRef:this.layoutRef,name:this.name,requiredRoots:[...this.requiredRoots],stateCode:this.stateCode,templateKindCode:this.templateKindCode,...this.tenantCode?{tenantCode:this.tenantCode}:{},version:this.version}}toJSON(){return this.toObject()}toObject(){const e={_type:this._type,...this.lifecycle?{lifecycle:this.lifecycle.toObject()}:{},meta:g.copySerializableProperties(this.meta,sr),requiredRoots:[...this.requiredRoots],...g.copySerializableProperties(this,or)};return typeof this.id<"u"&&(e.id=this.id),e}}const gt=Object.freeze({memoryLimit:1e7,parseLimit:1024*1024,renderLimit:1e3}),At="qw_block";let Q=null;const ur={parse(t){if(this.block=Q==null?void 0:Q[Number(t.args)],!this.block)throw new Error(`Unknown block instance ${t.args}.`)},*render(t,e){const n=t.spawn({...t.environments,[V]:this.block.params});yield this.liquid.renderer.renderTemplates(this.block.templates,n,e)}};function Ct({maxCacheEntries:t=500,limits:e={}}={}){const n=new Map,r=Object.freeze({...gt,...e});let i=null;const s=()=>{const{filters:u,version:d}=an();if((i==null?void 0:i.version)===d)return i;n.clear();const E=O=>{const m=ut({escape:O,limits:r,tags:[...qe,...me]});return u.forEach(({name:h,handler:p,raw:T})=>m.registerFilter(h,{handler:p,raw:O&&T})),m.registerTag(At,ur),m};return i={html:E(!0),text:E(!1),version:d},i},o=({content:u,contentType:d,partCode:E,allowedFunctions:O,blocks:m,allowBlocks:h,cacheKey:p})=>{s();const T=p?`${p}\0${E}\0${d}\0${O.join(",")}`:null;if(T&&n.has(T)){const R=n.get(T);return n.delete(T),n.set(T,R),R}const y=fr({allowBlocks:h,allowedFunctions:O,blocks:m,content:u,contentType:d,engines:s(),partCode:E});return T&&(n.set(T,y),n.size>t&&n.delete(n.keys().next().value)),y},a=({content:u,contentType:d=M.TEXT_HTML,partCode:E,data:O,context:m,blocks:h,cacheKey:p,allowBlocks:T=!0}={})=>{const y=ee(m);if(!y)throw new TypeError("Template rendering requires a data context.");return o({allowBlocks:T,allowedFunctions:[...y.functionNames||[]].sort(),blocks:mr(h),cacheKey:p,content:u??"",contentType:d,partCode:E}).render(O||{})};return Object.freeze({clearCache:()=>n.clear(),renderBlock:({block:u,params:d={},data:E,context:O}={})=>{const m=typeof(u==null?void 0:u.describe)=="function"?u.describe():u,h=`${m.blockCode}@${m.version}`,p=JSON.stringify(d).replace(/&/g,"&amp;").replace(/'/g,"&#39;");return a({blocks:[{...m,stateCode:"PUBLISHED"}],content:`<div data-qw-block="${h}" data-qw-params='${p}'></div>`,context:O,data:E,partCode:"block"})},renderContent:a,renderTemplate:({template:u,kind:d,data:E,context:O,blocks:m,cacheKey:h,draft:p=!1,layouts:T=[]}={})=>{var Qe;const y=typeof(u==null?void 0:u.toObject)=="function"?u.toObject():u||{},R=d||((Qe=u==null?void 0:u.constructor)==null?void 0:Qe.kind)||We(y.templateKindCode);if(!R)throw new TypeError("renderTemplate requires a template kind.");pr(y.templateSyntaxVersion);const I=p?null:h??dr(y),Pe={};return R.partDefinitions.forEach(({partCode:F,contentType:Ie})=>{var Je;const ie=(Je=y.partContent)==null?void 0:Je[F];if(typeof ie!="string"||!ie)return;if(Ie!==M.TEXT_HTML){Pe[F]=a({blocks:m,cacheKey:I,content:ie,context:O,contentType:Ie,data:E,partCode:F});return}const W=at({html:ie,layouts:T});if(W.missingLayoutCodes.length)throw new w({message:`Layout ${W.missingLayoutCodes.join(", ")} has no published version.`,partCode:F});const Yt=I&&W.layoutRefs.length?`${I}\0${W.layoutRefs.join(",")}`:I;Pe[F]=a({blocks:m,cacheKey:Yt,content:W.html,context:O,contentType:Ie,data:E,partCode:F})}),{partContent:Pe}}})}function pr(t=Oe){if(!$e.includes(t))throw new Y([C({code:b.SYNTAX_VERSION_UNSUPPORTED,message:`Template syntax version ${t} is not supported.`})])}function dr(t){const{templateCode:e,tenantCode:n,meta:r}=t;return!e||!(r!=null&&r.revision)?null:`${n||""}\0${e}\0${r.revision}`}function mr(t=[]){return new Map((t||[]).map(e=>{const n=typeof e.describe=="function"?e.describe():e;return[`${n.blockCode}@${n.version}`,n]}))}function fr({content:t,contentType:e,partCode:n,allowedFunctions:r,blocks:i,allowBlocks:s,engines:o}){const a=new Map(te().map(p=>[p.name,p])),c=new Set(r),l=H(t,{allowBlocks:s,partCode:n}),f=(p,T)=>Ne(p.templates,{allowedFunctionNames:c,functionsByName:a,locate:p.locate,text:p.text,...T}).issues,u=[...l.issues,...f(l,{})];if(z(u))throw new Y(u);const d=e===M.TEXT_PLAIN?o.text:o.html,E=l.blocks.map(p=>Tr(p,{blocks:i,engine:d,partCode:n,policy:f}));let O="",m=0;l.blocks.forEach(({start:p,end:T},y)=>{O+=`${l.text.slice(m,p)}{% ${At} ${y} %}`,m=T}),O+=l.text.slice(m);const h=Rt(d,O,E);return Object.freeze({render(p){try{return d.renderSync(h,{...p})}catch(T){const y=(T==null?void 0:T.originalError)||T;if(y instanceof w)throw y;const R=String((y==null?void 0:y.message)||T.message).replace(/, line:\d+, col:\d+$/,"");throw new w({cause:T,message:`Failed to render ${n||"content"}: ${R}`,partCode:n})}}})}function Tr(t,{blocks:e,engine:n,partCode:r,policy:i}){const{blockRef:s}=t,o=e.get(s);if(!o||typeof o.fragment!="string")throw new w({message:`Block ${s} is not available for rendering.`,partCode:r,source:s});if(o.stateCode==="DRAFT")throw new w({message:`Block ${s} is not published.`,partCode:r,source:s});const{definitions:a,errors:c}=G(o.params),{errors:l,values:f}=Ye(a,t.params);if(c.length||l.length)throw new w({message:`Block ${s} params are invalid: ${[...c,...l].join(" ")}`,partCode:r,source:s});const u=H(o.fragment,{allowBlocks:!1}),d=[...u.issues,...i(u,{allowAssign:!0,variables:new Map([[V,null]])})];if(z(d))throw new Y(d.map(E=>({...E,blockRef:s})));return{params:Object.freeze(vn(a,f)),templates:Rt(n,u.text,[])}}function Rt(t,e,n){Q=n;try{return t.parse(e)}finally{Q=null}}const hr=/^[^\s@<>()[\]\\,;:"]+@[^\s"(),:;<>@[\\\]][^\s"(),.:;<>@[\\\]]*\.[^\s"(),:;<>@[\\\]]+$/,Er=/cid:([^\s"'<>)]+)/g,br=Ct();async function yr({template:t,data:e,context:n,blocks:r,layouts:i,renderer:s=br,resolveInlineImage:o,juiceOptions:a,draft:c=!1}={}){const l=typeof(t==null?void 0:t.toObject)=="function"?t.toObject():t||{},{partContent:f}=s.renderTemplate({blocks:r,context:n,data:e,draft:c,kind:Re,layouts:i,template:l}),u=(h,p)=>s.renderContent({allowBlocks:!1,content:h,context:n,contentType:M.TEXT_PLAIN,data:e,partCode:p}).trim(),d=(h,p,{fixedEmail:T=!1}={})=>{if(!(h!=null&&h.email))return null;if(T&&/\{\{|\{%/.test(h.email))throw new w({message:`${p}.email must be a fixed address.`,partCode:`${p}.email`});const y=T?h.email.trim():u(h.email,`${p}.email`);if(!y)return null;if(!hr.test(y))throw new w({message:`${p}.email "${y}" is not a valid email address.`,partCode:`${p}.email`});const R=h.name?u(h.name,`${p}.name`):"";return{email:y,...R?{name:R}:{}}},E=(h,p)=>(Array.isArray(h)?h:[]).map((T,y)=>d(typeof T=="string"?{email:T}:T,`${p}[${y}]`)).filter(Boolean);let O=f.html?Xt.default(f.html,{preserveImportant:!0,preserveMediaQueries:!0,...a}):"";const m=[...new Set([...O.matchAll(Er)].map(h=>h[1]))];if(o&&m.length){const h=await Promise.all(m.map(p=>o({contentId:p})));m.forEach((p,T)=>{h[T]&&(O=O.split(`cid:${p}`).join(h[T]))})}return{bcc:E(l.bcc,"bcc"),cc:E(l.cc,"cc"),from:d(l.from,"from",{fixedEmail:!0}),html:O,inlineAttachments:m.map(h=>({contentId:h})),replyTo:d(l.replyTo,"replyTo"),subject:(f.subject||"").replace(/\s+/g," ").trim(),text:f.text??null}}const Nt=Object.freeze({blockCode:"INVOICE_LINES_TABLE",category:"Invoice",contextCode:"RECEIPT",fragment:`<table width="100%" cellpadding="4" cellspacing="0" role="presentation">
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@questwork/q-utilities"),A=require("liquidjs"),Jt=require("juice/client"),Zt=t=>t&&t.__esModule?t:{default:t},en=Zt(Jt),ge=2,Ue=Object.freeze([2]),y=Object.freeze({BLOCK_CONTEXT_MISMATCH:"BLOCK_CONTEXT_MISMATCH",BLOCK_DEPRECATED:"BLOCK_DEPRECATED",BLOCK_ELEMENT_INVALID:"BLOCK_ELEMENT_INVALID",BLOCK_NOT_ALLOWED:"BLOCK_NOT_ALLOWED",BLOCK_NOT_PUBLISHED:"BLOCK_NOT_PUBLISHED",BLOCK_PARAMS_INVALID:"BLOCK_PARAMS_INVALID",BLOCK_ROOT_NOT_IN_CONTEXT:"BLOCK_ROOT_NOT_IN_CONTEXT",FIELD_EXPRESSION_NOT_ALLOWED:"FIELD_EXPRESSION_NOT_ALLOWED",FUNCTION_ARGUMENTS_INVALID:"FUNCTION_ARGUMENTS_INVALID",FUNCTION_NOT_ALLOWED:"FUNCTION_NOT_ALLOWED",LAYOUT_EMPTY:"LAYOUT_EMPTY",LAYOUT_NOT_ALLOWED:"LAYOUT_NOT_ALLOWED",LAYOUT_NOT_FOUND:"LAYOUT_NOT_FOUND",LOOP_SOURCE_NOT_LIST:"LOOP_SOURCE_NOT_LIST",OUTPUT_NOT_SCALAR:"OUTPUT_NOT_SCALAR",PART_REQUIRED:"PART_REQUIRED",PART_UNKNOWN:"PART_UNKNOWN",PATH_UNKNOWN:"PATH_UNKNOWN",ROOT_UNKNOWN:"ROOT_UNKNOWN",SYNTAX_ERROR:"SYNTAX_ERROR",SYNTAX_VERSION_UNSUPPORTED:"SYNTAX_VERSION_UNSUPPORTED",TAG_NOT_ALLOWED:"TAG_NOT_ALLOWED",UNKNOWN_BLOCK:"UNKNOWN_BLOCK",UNKNOWN_FUNCTION:"UNKNOWN_FUNCTION",VARIABLE_INVALID:"VARIABLE_INVALID"}),K=Object.freeze({ERROR:"ERROR",WARNING:"WARNING"}),ke=Object.freeze(["blank","empty","false","forloop","nil","null","params","true"]),z="params",te=/^[A-Z_]\w*$/i,I=Object.freeze({BOOLEAN:"boolean",DATE:"date",LIST:"list",NUMBER:"number",OBJECT:"object",STRING:"string"}),tn=new Set([I.BOOLEAN,I.DATE,I.NUMBER,I.STRING]),le=Symbol("templateProjectionNode"),nn=10;class ze{constructor({projectionCode:e,label:n,description:r,fields:i}={}){if(!e||typeof e!="string")throw new TypeError("TemplateProjection requires a projectionCode.");Object.defineProperty(this,le,{enumerable:!1,value:de({description:r,fields:i,label:n,type:I.OBJECT},e)}),this.projectionCode=e,Object.freeze(this)}describe(){return pe(this[le])}project(e){return me(this[le],e)}}function j(t){return new ze(t)}function Ae(t,{label:e,description:n,value:r}={}){return{description:n,item:t,label:e,type:I.LIST,value:r}}function tt(t,e="root"){return de(t,e)}function rn(t){return pe(t)}function sn(t,e){return me(t,e)}function de(t,e){if(t instanceof ze)return t[le];if(!t||typeof t!="object")throw new TypeError(`Template field "${e}" must be an object definition.`);const{description:n,label:r,type:i,value:s}=t;if(s!==void 0&&typeof s!="function")throw new TypeError(`Template field "${e}" value must be a function.`);const o={description:n,label:r,type:i,value:s};if(i===I.OBJECT)o.fields=Object.entries(t.fields||{}).reduce((a,[c,l])=>(on(c,e),a[c]=de(l,`${e}.${c}`),a),{});else if(i===I.LIST)o.item=de(t.item,`${e}[]`);else if(!tn.has(i))throw new TypeError(`Template field "${e}" has unsupported type "${i}".`);return Object.freeze(o)}function on(t,e){if(!te.test(t)||t.startsWith("__")||ke.includes(t))throw new TypeError(`Template field name "${e}.${t}" is not allowed.`)}function pe(t){const e={type:t.type};return t.label&&(e.label=t.label),t.description&&(e.description=t.description),t.fields&&(e.fields=Object.entries(t.fields).reduce((n,[r,i])=>(n[r]=pe(i),n),{})),t.item&&(e.item=pe(t.item)),e}function me(t,e){if(t.type===I.OBJECT){if(e===null||typeof e!="object")return null;const n=xe(e,0,new WeakSet)||{};return Object.entries(t.fields).reduce((r,[i,s])=>(r[i]=me(s,s.value?s.value(e):e[i]),r),n)}return t.type===I.LIST?Array.isArray(e)?e.map(n=>me(t.item,n)):[]:e instanceof Date?Number.isNaN(e.getTime())?null:e.getTime():["string","number","boolean"].includes(typeof e)?typeof e=="number"&&!Number.isFinite(e)?null:e:null}function xe(t,e,n){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.getTime();if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(typeof t!="object"||e>=nn||n.has(t))return null;n.add(t);try{if(Array.isArray(t))return t.map(i=>i===void 0||typeof i=="function"||typeof i=="symbol"?null:xe(i,e+1,n));const r=typeof t.toObject=="function"?t.toObject():t;return Object.entries(r).reduce((i,[s,o])=>(o!==void 0&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="bigint"&&(i[s]=xe(o,e+1,n)),i),{})}finally{n.delete(t)}}class ct{constructor({contextCode:e,name:n,subjectType:r,roots:i,recipientRules:s=[],functionNames:o=[],includeTemplateDocumentReference:a=!1,loadData:c,sampleData:l}={}){if(!e||typeof e!="string")throw new TypeError("DataContext requires a contextCode.");if(c!==void 0&&typeof c!="function")throw new TypeError(`DataContext ${e} loadData must be a function.`);const m=Object.entries(i||{}).reduce((u,[d,f])=>{if(!te.test(d)||d.startsWith("__")||ke.includes(d))throw new TypeError(`DataContext ${e} root name "${d}" is not allowed.`);return u[d]=tt(f,d),u},{});if(a){if(Object.hasOwn(m,"template"))throw new TypeError(`DataContext ${e} already declares a template root.`);m.template=tt({fields:{documentReference:{label:"Document reference",type:"string"}},label:"Template",type:"object"},"template")}if(!Object.keys(m).length)throw new TypeError(`DataContext ${e} requires at least one data root.`);Object.defineProperties(this,{_loadData:{enumerable:!1,value:c},_rootNodes:{enumerable:!1,value:Object.freeze(m)},_sampleData:{enumerable:!1,value:l}}),this.contextCode=e,this.functionNames=Object.freeze([...new Set(o)]),this.includeTemplateDocumentReference=!!a,this.name=n||e,this.recipientRules=Object.freeze(s.map(({recipientType:u,name:d,description:f})=>{if(!u)throw new TypeError(`DataContext ${e} recipient rules require recipientType.`);return Object.freeze({description:f,name:d||u,recipientType:u})})),this.subjectType=r,Object.freeze(this)}get rootNames(){return Object.keys(this._rootNodes)}describe(){return{contextCode:this.contextCode,functionNames:[...this.functionNames],...this.includeTemplateDocumentReference?{includeTemplateDocumentReference:!0}:{},name:this.name,recipientRules:this.recipientRules.map(e=>({...e})),roots:Object.entries(this._rootNodes).reduce((e,[n,r])=>(e[n]=rn(r),e),{}),subjectType:this.subjectType}}project(e={}){return Object.entries(this._rootNodes).reduce((n,[r,i])=>(this.includeTemplateDocumentReference&&r==="template"||(n[r]=sn(i,e[r])),n),{})}async load({subjectRef:e,recipientType:n,...r}={}){if(!this._loadData)throw new Error(`DataContext ${this.contextCode} has no loadData.`);if(this.recipientRules.length&&!this.recipientRules.some(s=>s.recipientType===n))throw new RangeError(`DataContext ${this.contextCode} does not support recipientType "${n}".`);const i=await this._loadData({recipientType:n,subjectRef:e,...r});if(!Array.isArray(i))throw new TypeError(`DataContext ${this.contextCode} loadData must return an array.`);return i.map(({recipientRef:s,roots:o})=>({data:this.project(o),...s!==void 0?{recipientRef:s}:{}}))}getSampleData(){return this._sampleData?structuredClone(this._sampleData):null}}function ne(t){return new ct(t)}function q(t){return t?typeof t.describe=="function"?t.describe():t:null}const $=Object.freeze({ANY:"any",ARRAY:"array",BOOLEAN:"boolean",NUMBER:"number",OBJECT:"object",STRING:"string"}),an=new Set(Object.values($)),cn=/^__[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/,G=new Map;let Ve=0;function lt({name:t,fn:e,signature:n=[],trustedHtml:r=!1,label:i,description:s}={}){if(!cn.test(t||""))throw new TypeError(`Template function name "${t}" must be "__" followed by snake_case letters and digits.`);if(typeof e!="function")throw new TypeError(`Template function ${t} requires fn.`);if(G.has(t))throw new Error(`Template function ${t} is already registered.`);if(!n.length)throw new TypeError(`Template function ${t} requires a signature with at least the piped value.`);const o=n.map((a,c)=>{const l=(a==null?void 0:a.types)||[];if(!l.length||l.some(m=>!an.has(m)))throw new TypeError(`Template function ${t} argument #${c+1} has invalid types.`);return Object.freeze({...a.optional?{optional:!0}:{},types:Object.freeze([...l]),...a.variadic?{variadic:!0}:{}})});G.set(t,Object.freeze({descriptor:Object.freeze({...s?{description:s}:{},...i?{label:i}:{},name:t,signature:Object.freeze(o),trustedHtml:!!r}),filter:pn(t,e,o)})),Ve+=1}function re(){return[...G.values()].map(({descriptor:t})=>({...t,signature:t.signature.map(e=>({...e,types:[...e.types]}))}))}function ln(t){var e;return((e=G.get(t))==null?void 0:e.descriptor)||null}function un(){return{filters:[...G.values()].map(({descriptor:t,filter:e})=>({handler:e,name:t.name,raw:t.trustedHtml})),version:Ve}}function dn(){G.clear(),Ve+=1}function pn(t,e,n){return(...r)=>{const i=r.map(o=>o===void 0?null:o);i.forEach((o,a)=>{const c=n[Math.min(a,n.length-1)];if(o!==null&&c&&!c.types.some(l=>mn(o,l)))throw new TypeError(`${t} argument #${a+1} must be ${c.types.join(" or ")}.`)});const s=e(...i);return s===void 0?null:s}}function mn(t,e){switch(e){case $.ANY:return!0;case $.ARRAY:return Array.isArray(t);case $.OBJECT:return typeof t=="object"&&!Array.isArray(t);case $.BOOLEAN:return typeof t=="boolean";case $.NUMBER:return typeof t=="number";default:return typeof t=="string"}}function C({code:t,message:e,severity:n=K.ERROR,...r}={}){const i={code:t,message:e,severity:n};return["partCode","offset","line","column","source","blockRef","detail"].forEach(s=>{typeof r[s]<"u"&&(i[s]=r[s])}),i}function V(t=[]){return t.some(e=>e.severity===K.ERROR)}class H extends Error{constructor(e=[],n){const r=e.filter(i=>i.severity===K.ERROR);super(n||fn(r)),this.name="TemplateSyntaxError",this.code="TEMPLATE_SYNTAX_INVALID",this.issues=e}}class D extends Error{constructor({message:e,partCode:n,source:r,cause:i}={}){super(e||"Template rendering failed.",i?{cause:i}:void 0),this.name="TemplateRenderError",this.code="TEMPLATE_RENDER_FAILED",this.partCode=n,this.source=r}}function fn(t){if(!t.length)return"Template is invalid.";const[e]=t,n=e.partCode?` (${e.partCode}${e.line?`:${e.line}:${e.column}`:""})`:"",r=t.length>1?` and ${t.length-1} more issue(s)`:"";return`${e.code}: ${e.message}${n}${r}`}const Fe="data-qw-layout",Tn=`<([a-z][a-z0-9-]*)\\b[^>]*\\s${Fe}\\s*=\\s*"([^"]*)"[^>]*>\\s*</\\1\\s*>`,hn="PUBLISHED",ut=()=>new RegExp(Tn,"gi"),En=t=>typeof(t==null?void 0:t.describe)=="function"?t.describe():t;function bn(t){return`<div ${Fe}="${t}"></div>`}function Ce(t){return[...new Set([...String(t||"").matchAll(ut())].map(([,,e])=>e))]}function Ke({layouts:t=[],layoutCode:e}={}){return e&&t.map(En).filter(n=>(n==null?void 0:n.layoutCode)===e&&n.stateCode===hn).sort((n,r)=>r.version-n.version)[0]||null}function dt({html:t,layouts:e=[]}={}){const n=new Set,r=new Set;return{html:String(t||"").replace(ut(),(s,o,a)=>{const c=Ke({layoutCode:a,layouts:e});return c?(n.add(`${c.layoutCode}@${c.version}`),c.html||""):(r.add(a),s)}),layoutRefs:[...n],missingLayoutCodes:[...r]}}function qe(t){return String(t||"").trim()?Ce(t).map(e=>C({code:y.LAYOUT_NOT_ALLOWED,layoutCode:e,message:`Layout ${e} cannot be placed inside another layout.`,partCode:"layout"})):[C({code:y.LAYOUT_EMPTY,message:"The layout is empty.",partCode:"layout"})]}const Ge=Object.freeze(["#","case","comment","for","if","unless"]),fe=Object.freeze(["assign","capture"]),De=(t=!1)=>({...t?{optional:t}:{},types:["any"]}),_=(t,e=!1)=>({...e?{optional:e}:{},types:t}),Ye=Object.freeze([{description:'Format a timestamp (milliseconds) or date text, e.g. date: "%Y-%m-%d". Dates are UTC unless a time zone is given.',label:"date",name:"date",signature:[_(["number","string"]),_(["string"],!0),_(["number","string"],!0)]},{description:"The argument when the value is nil, false or empty.",name:"default",signature:[De(),De()]},{description:"Join list items with a separator.",label:"joined",name:"join",signature:[_(["array"]),_(["string"],!0)]},{description:"The given field of every list item.",name:"map",signature:[_(["array"]),_(["string"])]},{description:"List items whose field is truthy or equals a value.",name:"where",signature:[_(["array"]),_(["string"]),De(!0)]},{description:'List items for which an expression is true, e.g. where_exp: "line", "line.qty > 0".',name:"where_exp",signature:[_(["array"]),_(["string"]),_(["string"])]},{description:"The first list item.",label:"first",name:"first",signature:[_(["array"])]},{description:"Number of list items or characters.",label:"count",name:"size",signature:[_(["array","string"])]},{description:"Text in upper case.",label:"upper case",name:"upcase",signature:[_(["string"])]},{description:"Text in lower case.",label:"lower case",name:"downcase",signature:[_(["string"])]},{description:"Shorten text to a length, ending with an ellipsis.",label:"shortened",name:"truncate",signature:[_(["string"]),_(["number"],!0),_(["string"],!0)]},{description:"Text without HTML tags.",name:"strip_html",signature:[_(["string"])]},{description:"Add a number.",name:"plus",signature:[_(["number"]),_(["number"])]},{description:"Subtract a number.",name:"minus",signature:[_(["number"]),_(["number"])]},{description:"Multiply by a number.",name:"times",signature:[_(["number"]),_(["number"])]},{description:"Divide by a number.",name:"divided_by",signature:[_(["number"]),_(["number"])]},{description:"Round to a number of decimals.",label:"rounded",name:"round",signature:[_(["number"]),_(["number"],!0)]}].map(t=>Object.freeze({...t,builtin:!0,signature:Object.freeze(t.signature.map(Object.freeze))}))),yn=new Set(Ye.map(({name:t})=>t)),pt=Object.freeze({"&#34;":'"',"&#39;":"'","&#60;":"<","&#62;":">","&#x27;":"'","&amp;":"&","&apos;":"'","&gt;":">","&lt;":"<","&nbsp;":" ","&quot;":'"'}),_n=/\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}/g;function mt(t){return String(t??"").replace(_n,e=>e.replace(/&(?:#34|#39|#60|#62|#x27|amp|apos|gt|lt|nbsp|quot);/g,n=>pt[n]).replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/\xA0/g," ").replace(/[\u200B-\u200D\uFEFF]/g,""))}function nt(t){return String(t??"").replace(/&(?:#34|#39|#60|#62|#x27|amp|apos|gt|lt|nbsp|quot);/g,e=>pt[e])}function ft({escape:t=!1,limits:e={},tags:n}={}){const r=new A.Liquid({cache:!1,dynamicPartials:!1,jsTruthy:!1,ownPropertyOnly:!0,strictFilters:!1,strictVariables:!1,timezoneOffset:0,...t?{outputEscape:"escape"}:{},...e});Object.keys(r.filters).forEach(s=>{yn.has(s)||r.unregisterFilter(s)});const i=r.filters.date;if(r.registerFilter("date",function(s,...o){return i.call(this,typeof s=="number"?new Date(s):s,...o)}),n){const s=new Set(n);Object.keys(r.tags).forEach(o=>{s.has(o)||delete r.tags[o]})}return r}const U="data-qw-block",Te="data-qw-params",On=/^([A-Z][A-Z0-9_]*)@([1-9]\d*)$/,gn=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]),An=ft();function W(t,{partCode:e,allowBlocks:n=!0}={}){const r=mt(typeof t=="string"?t:""),i=Pn(r,e),s=[],o=[],a=[];let c=0,l=Ee(r,c);for(;l;)a.push(l),c=l.end,l.issue?s.push(C({...l.issue,...i(l.start)})):n?o.push({...l.node,end:l.end,location:i(l.start),start:l.start}):s.push(C({blockRef:l.node.blockRef,code:y.BLOCK_NOT_ALLOWED,message:"Block instances are not allowed here.",...i(l.start)})),l=Ee(r,c);let m=[];try{m=An.parse(Nn(r,a))}catch(u){s.push(Cn(u,i))}return{blockRefs:[...new Set(o.map(({blockRef:u})=>u))],blocks:o,issues:s,locate:i,templates:m,text:r}}function Tt(t){const e=typeof t=="string"?t:"",n=new Set;let r=Ee(e,0);for(;r;)r.node&&n.add(r.node.blockRef),r=Ee(e,r.end);return[...n]}function Cn(t,e,n=0){var i;if(!(t!=null&&t.token)&&!/^(?:Parse|Tokenization|Liquid)Error$/.test((t==null?void 0:t.name)||""))throw t;const r=String(t.message||"Template syntax error.").replace(/, line:\d+, col:\d+$/,"");return C({code:y.SYNTAX_ERROR,message:r,...e?e(n+(((i=t.token)==null?void 0:i.begin)??0)):{}})}function ht(t){const e=On.exec(typeof t=="string"?t.trim():"");return e?{blockCode:e[1],version:Number(e[2])}:null}function he({blockCode:t,version:e}={}){return`${t}@${e}`}function Rn({blockCode:t,version:e,params:n={},tagName:r="div"}={}){const i=JSON.stringify(n||{}).replace(/&/g,"&amp;").replace(/'/g,"&#39;");return`<${r} ${U}="${he({blockCode:t,version:e})}" ${Te}='${i}'></${r}>`}function Nn(t,e){if(!e.length)return t;let n="",r=0;return e.forEach(({start:i,end:s})=>{n+=t.slice(r,i)+t.slice(i,s).replace(/[^\n]/g," "),r=s}),n+t.slice(r)}function Ee(t,e){let n=e;for(;n<t.length;){const r=t.indexOf(U,n);if(r===-1)return null;const i=t.lastIndexOf("<",r),s=i>=e?Sn(t,i):null;if(!s||s.end<=r||!Object.hasOwn(s.attributes,U)){n=r+U.length;continue}const o=s.selfClosing||gn.has(s.name)?s.end:Ln(t,s.name,s.end);if(o===-1)return{end:t.length,issue:{code:y.BLOCK_ELEMENT_INVALID,message:`Block element <${s.name}> is not closed.`},start:i};const a=ht(nt(s.attributes[U]));if(!a)return{end:o,issue:{code:y.BLOCK_ELEMENT_INVALID,message:`Block reference "${s.attributes[U]}" must look like BLOCK_CODE@1.`},start:i};let c={};const l=s.attributes[Te];if(l){try{c=JSON.parse(nt(l))}catch{c=null}if(!c||typeof c!="object"||Array.isArray(c))return{end:o,issue:{blockRef:he(a),code:y.BLOCK_PARAMS_INVALID,message:`${Te} must be a JSON object.`},start:i}}return{end:o,node:{blockCode:a.blockCode,blockRef:he(a),params:c,type:"Block",version:a.version},start:i}}return null}function Sn(t,e){const n=/^<([A-Z][\w-]*)/i.exec(t.slice(e));if(!n)return null;const r={};let i=e+n[0].length;for(;i<t.length;){const s=t.slice(i),o=/^\s*(\/?)>/.exec(s);if(o)return{attributes:r,end:i+o[0].length,name:n[1].toLowerCase(),selfClosing:o[1]==="/"};const a=/^\s+([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/.exec(s);if(!a)return null;r[a[1].toLowerCase()]=a[2]??a[3]??a[4]??"",i+=a[0].length}return null}function Ln(t,e,n){const r=new RegExp(`<(/?)${e}(?=[\\s/>])[^>]*>`,"gi");r.lastIndex=n;let i=1,s=r.exec(t);for(;s;){if(s[1]){if(i-=1,i===0)return s.index+s[0].length}else s[0].endsWith("/>")||(i+=1);s=r.exec(t)}return-1}function Pn(t,e){const n=[0];for(let r=0;r<t.length;r+=1)t[r]===`
2
+ `&&n.push(r+1);return r=>{let i=0;for(;i+1<n.length&&n[i+1]<=r;)i+=1;return{column:r-n[i]+1,line:i+1,offset:r,...e?{partCode:e}:{}}}}const In=["active","created","creator","deleted","modified","owner","revision"],wn=["contextCode","documentReference","name","templateCode","templateRevision","templateSyntaxVersion"],Dn=["contextCode","name","templateSyntaxVersion"];class Et extends g.TenantAwareEntity{constructor(e={}){var n;e=e||{},super(e),this._type=e._type||"Template",this.contextCode=e.contextCode,this.documentReference=rt(e.documentReference),this.name=e.name,this.partContent=it(e.partContent),this.templateCode=e.templateCode,this.templateRevision=Number(e.templateRevision||((n=e.meta)==null?void 0:n.revision)||1),this.templateSyntaxVersion=Number(e.templateSyntaxVersion||ge)}static get _classname(){return"Template"}static get _superclass(){return"Template"}static get kind(){return null}static get partDefinitions(){var e;return((e=this.kind)==null?void 0:e.partDefinitions)||[]}get isValid(){return super.isValid&&!!this.templateCode&&!!this.contextCode&&Number.isInteger(this.templateRevision)&&this.templateRevision>0&&(this.documentReference==null||typeof this.documentReference=="string"&&this.documentReference.length<=120&&!/[\r\n]/.test(this.documentReference))}getCode(){return this.templateCode}getId(){return this.id}getContentParts(){return this.constructor.partDefinitions.map(e=>({...e,content:this.partContent[e.partCode]??""}))}getPartContent(e){return this.partContent[e]??""}getBlockRefs(){const e=new Set;return this.getContentParts().forEach(({content:n})=>{Tt(n).forEach(r=>e.add(r))}),[...e]}getLayoutCodes(){return[...new Set(this.getContentParts().flatMap(({content:e})=>Ce(e)))]}setPartContent(e,n){if(!this.constructor.partDefinitions.some(r=>r.partCode===e))throw new RangeError(`${this.constructor._classname} has no part "${e}".`);return n===null?delete this.partContent[e]:this.partContent[e]=String(n),this}update(e={}){return Object.hasOwn(e,"documentReference")&&(this.documentReference=rt(e.documentReference)),Dn.forEach(n=>{Object.hasOwn(e,n)&&(this[n]=n==="templateSyntaxVersion"?Number(e[n]):e[n])}),e.partContent&&typeof e.partContent=="object"&&Object.entries(e.partContent).forEach(([n,r])=>{this.setPartContent(n,r)}),super.update(e)}toJSON(){return this.toObject()}toObject(){const e={_type:this._type,meta:g.copySerializableProperties(this.meta,In),metadata:g.copySerializableKeyValueObjects(this.metadata),partContent:it(this.partContent),remarks:g.copySerializableKeyValueObjects(this.remarks),tenantCode:this.tenantCode,...g.copySerializableProperties(this,wn)};return typeof this.id<"u"&&(e.id=this.id),e}}function rt(t){return typeof t=="string"?t.trim()||null:t}function it(t){return!t||typeof t!="object"?{}:Object.entries(t).reduce((e,[n,r])=>(typeof r=="string"&&(e[n]=r),e),{})}const k=Object.freeze({DEPRECATED:"DEPRECATED",DRAFT:"DRAFT",PUBLISHED:"PUBLISHED"}),vn=new Set(Object.values(k)),jn=Object.freeze({DEPRECATED:new Set,DRAFT:new Set(["PUBLISHED"]),PUBLISHED:new Set(["DEPRECATED"])});class be extends g.Lifecycle{constructor(e={}){super(e),this._setPublicationState(e.publication)}static get _classname(){return"LifecycleTemplateBlock"}static get entityType(){return"TemplateBlock"}static create({actionRevision:e,modified:n=Date.now()}={}){return this.init({publication:{actionRevision:e,modified:n,stateCode:k.DRAFT}})}canTransition(e,n){var i,s;const r=(i=this.getState(e))==null?void 0:i.stateCode;return e==="publication"&&!!((s=jn[r])!=null&&s.has(n))}transition(e,{actionRevision:n,modified:r=Date.now(),stateCode:i}={}){var s;if(!this.canTransition(e,i))throw new Error(`Invalid ${this.constructor.entityType} lifecycle transition: ${e} ${((s=this.getState(e))==null?void 0:s.stateCode)||"UNKNOWN"} -> ${i||"UNKNOWN"}`);return this._setPublicationState({actionRevision:n,modified:r,stateCode:i})}_setPublicationState(e){if(!vn.has(e==null?void 0:e.stateCode))throw new TypeError(`Invalid ${this.constructor.entityType} lifecycle state for publication.`);return this._setState("publication",e)}}const N=Object.freeze({BOOLEAN:"boolean",MULTI_SELECT:"multiSelect",SELECT:"select",TEXT:"text"}),Bn=new Set(Object.values(N)),st=new Set([N.MULTI_SELECT,N.SELECT]);function Y(t=[]){const e=[],n=new Set;return{definitions:(Array.isArray(t)?t:[]).map((i,s)=>{const{paramCode:o,type:a,label:c,description:l,required:m=!1,options:u=[]}=i||{};return!te.test(o||"")||o.startsWith("__")?e.push(`Param #${s+1} has an invalid paramCode "${o}".`):n.has(o)&&e.push(`Param "${o}" is declared twice.`),n.add(o),Bn.has(a)||e.push(`Param "${o}" has unsupported type "${a}".`),st.has(a)&&(!Array.isArray(u)||!u.length?e.push(`Param "${o}" requires options.`):u.some(d=>!te.test(String((d==null?void 0:d.value)??"")))&&e.push(`Param "${o}" option values must match [A-Za-z_]\\w*.`)),{...l?{description:l}:{},..."default"in(i||{})?{default:i.default}:{},label:c||o,...st.has(a)?{options:u.map(({value:d,label:f})=>({label:f||d,value:d}))}:{},paramCode:o,required:!!m,type:a}}),errors:e}}function He(t=[],e={}){const n=[],r=e&&typeof e=="object"?e:{},i=new Set(t.map(({paramCode:o})=>o));Object.keys(r).forEach(o=>{i.has(o)||n.push(`Unknown param "${o}".`)});const s=t.reduce((o,a)=>{const{paramCode:c,type:l,required:m}=a,u=Object.hasOwn(r,c)?r[c]:a.default;if(u==null||u==="")return m&&n.push(`Param "${c}" is required.`),o[c]=l===N.MULTI_SELECT?[]:l===N.BOOLEAN?!1:null,o;const d=Mn(a,u);return d&&n.push(d),o[c]=u,o},{});return{errors:n,values:s}}function xn(t=[],e={}){return t.reduce((n,{paramCode:r,type:i})=>(i===N.MULTI_SELECT?n[r]=(Array.isArray(e[r])?e[r]:[]).reduce((s,o)=>(s[o]=!0,s),{}):n[r]=e[r]??null,n),{})}function We(t=[]){return{fields:t.reduce((e,{paramCode:n,type:r,label:i,options:s})=>(r===N.MULTI_SELECT?e[n]={fields:s.reduce((o,a)=>(o[a.value]={label:a.label,type:"boolean"},o),{}),label:i,type:"object"}:e[n]={label:i,type:r===N.BOOLEAN?"boolean":"string"},e),{}),type:"object"}}function Mn({paramCode:t,type:e,options:n=[]},r){const i=new Set(n.map(s=>s.value));switch(e){case N.BOOLEAN:return typeof r=="boolean"?null:`Param "${t}" must be a boolean.`;case N.TEXT:return typeof r=="string"?null:`Param "${t}" must be text.`;case N.SELECT:return i.has(r)?null:`Param "${t}" must be one of ${[...i].join(", ")}.`;case N.MULTI_SELECT:return Array.isArray(r)&&r.every(s=>i.has(s))?null:`Param "${t}" must be a list of ${[...i].join(", ")}.`;default:return null}}const Re=Object.freeze({EMAIL:"EMAIL"}),x=Object.freeze({TEXT_HTML:"text/html",TEXT_PLAIN:"text/plain"}),w=Object.freeze({MAILBOX:"mailbox",MAILBOX_LIST:"mailboxList",TEXT:"text"}),Ne=Object.freeze({fieldDefinitions:Object.freeze([Object.freeze({fieldCode:"documentReference",label:"Document reference",literal:!0,type:w.TEXT}),Object.freeze({emailExpression:!1,fieldCode:"to",label:"To",nameExpression:!0,type:w.MAILBOX}),Object.freeze({emailExpression:!1,fieldCode:"from",label:"From",nameExpression:!0,type:w.MAILBOX}),Object.freeze({emailExpression:!0,fieldCode:"replyTo",label:"Reply to",nameExpression:!0,type:w.MAILBOX}),Object.freeze({emailExpression:!0,fieldCode:"cc",label:"CC",nameExpression:!0,type:w.MAILBOX_LIST}),Object.freeze({emailExpression:!0,fieldCode:"bcc",label:"BCC",nameExpression:!0,type:w.MAILBOX_LIST})]),label:"Email",partDefinitions:Object.freeze([Object.freeze({contentType:x.TEXT_PLAIN,label:"Subject",partCode:"subject",required:!0}),Object.freeze({contentType:x.TEXT_HTML,label:"HTML",partCode:"html",required:!0}),Object.freeze({contentType:x.TEXT_PLAIN,label:"Plain text",partCode:"text",required:!1})]),previewModes:Object.freeze([Object.freeze({label:"Desktop",previewModeCode:"DESKTOP",width:1024}),Object.freeze({label:"Tablet",previewModeCode:"TABLET",width:768}),Object.freeze({label:"Mobile",previewModeCode:"MOBILE",width:375})]),previewViews:Object.freeze([Object.freeze({label:"Inbox",previewViewCode:"INBOX"}),Object.freeze({label:"HTML",previewViewCode:"HTML"}),Object.freeze({label:"Plain text",previewViewCode:"TEXT"})]),templateKindCode:Re.EMAIL}),$n=Object.freeze({[Re.EMAIL]:Ne});function Xe(t){return $n[t]||null}function Un(t){return structuredClone({fieldDefinitions:t.fieldDefinitions||[],label:t.label,partDefinitions:t.partDefinitions||[],previewModes:t.previewModes||[],previewViews:t.previewViews||[],templateKindCode:t.templateKindCode})}function kn(t,e={}){return(t.fieldDefinitions||[]).flatMap(({fieldCode:n,type:r,emailExpression:i,nameExpression:s,literal:o,expressionAllowed:a=!1})=>{if(o)return[];const c=e[n];return r===w.TEXT?typeof c=="string"&&c?[{content:c,expressionAllowed:!!a,fieldPath:n}]:[]:(r===w.MAILBOX_LIST?Array.isArray(c)?c:[]:c?[c]:[]).flatMap((m,u)=>{const d=r===w.MAILBOX_LIST?`${n}[${u}]`:n;return[{content:(m==null?void 0:m.email)||"",expressionAllowed:i,fieldPath:`${d}.email`},{content:(m==null?void 0:m.name)||"",expressionAllowed:s,fieldPath:`${d}.name`}].filter(({content:f})=>f)})})}const bt=new Map(Ye.map(t=>[t.name,t])),P=Object.freeze({type:"number"}),Qe=Object.freeze({type:"string"}),Me=Object.freeze({type:"boolean"}),zn=Object.freeze({fields:Object.freeze({first:Me,index:P,index0:P,last:Me,length:P,rindex:P,rindex0:P}),label:"Loop",type:"object"}),Vn=new Set([z,"forloop"]),Fn=new Set(["where","where_exp"]),Kn=new Set(["date","downcase","join","strip_html","truncate","upcase"]),qn=new Set(["divided_by","minus","plus","round","size","times"]);function Se(t,{locate:e,text:n,roots:r=null,variables:i=new Map,functionsByName:s=null,allowedFunctionNames:o=null,allowAssign:a=!1}={}){const c={allowAssign:a,allowedFunctionNames:o,assigned:new Map,functionsByName:s,issues:[],locate:e,requiredRoots:new Set,roots:r,text:n};return B(t,i,c),{issues:c.issues,requiredRoots:[...c.requiredRoots].sort()}}function Gn(t,e){return bt.get(t)||(e==null?void 0:e.get(t))||null}function B(t,e,n){(t||[]).forEach(r=>{const{token:i}=r;if(A.TypeGuards.isOutputToken(i)){const s=ye(n,i),o=Z(r.value,e,n,s);o&&(o.type==="list"||o.type==="object")&&S(n,y.OUTPUT_NOT_SCALAR,`"${s}" outputs a ${o.type}; output a field of it or use a filter such as join or size.`,i,s);return}A.TypeGuards.isTagToken(i)&&Yn(r,e,n)})}function Yn(t,e,n){var o;const{name:r,token:i}=t,s=ye(n,i);if(!Ge.includes(r)&&!(n.allowAssign&&fe.includes(r))){const a=fe.includes(r)?" outside block fragments":"";S(n,y.TAG_NOT_ALLOWED,`Tag "${r}" is not allowed${a}.`,i,s);return}switch(r){case"if":case"unless":t.branches.forEach(a=>{Z(a.value,e,n,s),B(a.templates,e,n)}),B(t.elseTemplates,e,n);break;case"case":Z(t.value,e,n,s),t.branches.forEach(a=>{a.values.forEach(c=>v(c,e,n,s)),B(a.templates,e,n)}),B(t.elseTemplates,e,n);break;case"for":{const{variable:a}=t;ve(a,e,n,i,s);const c=v(t.collection,e,n,s);let l=null;A.TypeGuards.isRangeToken(t.collection)?l=P:c&&c.type!=="list"?S(n,y.LOOP_SOURCE_NOT_LIST,`"${ye(n,t.collection)}" is not a list.`,t.collection,s):c&&(l=c.item||null),Object.values(((o=t.hash)==null?void 0:o.hash)||{}).forEach(m=>{m&&v(m,e,n,s)}),B(t.templates,new Map([...e,[a,l],["forloop",zn]]),n),B(t.elseTemplates,e,n);break}case"assign":{ve(t.key,e,n,i,s),n.assigned.set(t.key,Z(t.value,e,n,s));break}case"capture":ve(t.variable,e,n,i,s),B(t.templates,e,n),n.assigned.set(t.variable,Qe);break}}function ve(t,e,n,r,i){!te.test(t||"")||t.startsWith("__")?S(n,y.VARIABLE_INVALID,`Variable "${t}" must match [A-Za-z_]\\w* and must not start with "__".`,r,i):(ke.includes(t)||e.has(t)||n.roots&&Object.hasOwn(n.roots,t))&&S(n,y.VARIABLE_INVALID,`Variable "${t}" conflicts with a data root, a loop variable or a reserved name.`,r,i)}function Z(t,e,n,r){if(!t)return null;let i=yt(t.initial,e,n,r);return(t.filters||[]).forEach(s=>{i=Wn(s,i,e,n,r)}),i}function yt(t,e,n,r){const i=[...(t==null?void 0:t.postfix)||[]],s=i.map(o=>v(o,e,n,r));return i.length===1?s[0]:i.some(o=>A.TypeGuards.isOperatorToken(o))?Me:null}function v(t,e,n,r){return t?A.TypeGuards.isPropertyAccessToken(t)?Hn(t,e,n,r):A.TypeGuards.isRangeToken(t)?(v(t.lhs,e,n,r),v(t.rhs,e,n,r),{item:P,type:"list"}):A.TypeGuards.isNumberToken(t)?P:A.TypeGuards.isQuotedToken(t)?Qe:t.initial?Z(t,e,n,r):null:null}function Hn(t,e,n,r){const[i,...s]=t.props||[],o=i==null?void 0:i.content;if(typeof o!="string"||!A.TypeGuards.isWordToken(i))return null;let a;if(e.has(o))a=e.get(o);else if(n.assigned.has(o))a=n.assigned.get(o);else if(n.roots)if(Object.hasOwn(n.roots,o))n.requiredRoots.add(o),a=n.roots[o];else return S(n,y.ROOT_UNKNOWN,`"${o}" is not a data root of this context (${Object.keys(n.roots).join(", ")}) or a template variable.`,t,r),null;else return o!==z&&n.requiredRoots.add(o),null;for(const c of s){if(!a)return null;if(A.TypeGuards.isPropertyAccessToken(c)||c.initial){if(v(c,e,n,r),a.type==="list"){a=a.item||null;continue}return a.type==="object"?null:ce(n,t,r,"only a list or an object can be indexed.")}if(A.TypeGuards.isNumberToken(c)){if(a.type!=="list")return ce(n,t,r,"only a list can be indexed.");a=a.item||null;continue}const l=c.content;if(a.type==="list")if(l==="size")a=P;else if(l==="first"||l==="last")a=a.item||null;else return ce(n,t,r,`a list has no field "${l}" (use size, first, last or a loop).`);else if(a.type==="string"&&l==="size")a=P;else if(a.type==="object"&&a.fields&&Object.hasOwn(a.fields,l))a=a.fields[l];else return a.type==="object"&&!Vn.has(o)?null:ce(n,t,r,`field "${l}" does not exist.`)}return a}function ce(t,e,n,r){return S(t,y.PATH_UNKNOWN,`"${ye(t,e)}": ${r}`,e,n),null}function Wn(t,e,n,r,i){var O;const{name:s,args:o=[]}=t;if(!s)return S(r,y.SYNTAX_ERROR,'A filter name is missing after "|".',t.token,i),null;const a=o.filter(T=>!Array.isArray(T)),c=o.filter(T=>Array.isArray(T));a.forEach(T=>v(T,n,r,i)),c.forEach(([,T])=>v(T,n,r,i));const l=bt.get(s),m=l||((O=r.functionsByName)==null?void 0:O.get(s));if(!m)return(r.functionsByName||!s.startsWith("__"))&&S(r,y.UNKNOWN_FUNCTION,`Filter "${s}" is not available.`,t.token,i),null;if(!l&&r.allowedFunctionNames&&!r.allowedFunctionNames.has(s))return S(r,y.FUNCTION_NOT_ALLOWED,`Filter "${s}" is not allowed in this data context.`,t.token,i),null;const u=(m.signature||[]).slice(1),d=u.filter(T=>!T.optional&&!T.variadic).length,f=u.some(T=>T.variadic);if(c.length||a.length<d||!f&&a.length>u.length){const T=f?`at least ${d}`:d===u.length?d:`${d}-${u.length}`;return S(r,y.FUNCTION_ARGUMENTS_INVALID,`Filter "${s}" expects ${T} argument(s)${c.length?" and no named arguments":""}, got ${a.length}.`,t.token,i),null}return l?Xn(s,e,a,n,r,i):null}function Xn(t,e,n,r,i,s){const o=(e==null?void 0:e.type)==="list"?e.item:null,a=l=>!o||o.type!=="object"||typeof l!="string"?null:o.fields&&Object.hasOwn(o.fields,l)?o.fields[l]:null,c=l=>l&&A.TypeGuards.isQuotedToken(l)?l.content:null;if(t==="where")return a(c(n[0])),e;if(t==="where_exp")return Qn(c(n[0]),n[1],o,r,i,s),e;if(Fn.has(t))return e;if(t==="map"){const l=a(c(n[0]));return(e==null?void 0:e.type)==="list"?{item:l,type:"list"}:null}return t==="first"?o:t==="default"?e:qn.has(t)?P:Kn.has(t)?Qe:null}function Qn(t,e,n,r,i,s){if(!t||!e||!A.TypeGuards.isQuotedToken(e))return;let o;try{o=new A.Tokenizer(e.content).readExpression()}catch(c){S(i,y.SYNTAX_ERROR,`where_exp expression: ${c.message}`,e,s);return}const a={...i,text:e.content};a.issues=[],yt(o,new Map([...r,[t,n]]),a,s),a.issues.forEach(c=>i.issues.push({...c,...i.locate(e.begin)}))}function ye(t,e){return t.text&&e?t.text.slice(e.begin,e.end):""}function S(t,e,n,r,i){t.issues.push(C({code:e,message:n,...t.locate((r==null?void 0:r.begin)??0),...i?{source:i}:{}}))}const Jn=/\{\{|\{%/,je=Object.freeze({DEPRECATED:"DEPRECATED",DRAFT:"DRAFT",PUBLISHED:"PUBLISHED"});function Zn({template:t,kind:e,context:n,functions:r,blocks:i,allowedDeprecatedBlockRefs:s,layouts:o=[]}={}){var E;const a=typeof(t==null?void 0:t.toObject)=="function"?t.toObject():t||{},c=e||((E=t==null?void 0:t.constructor)==null?void 0:E.kind)||Xe(a.templateKindCode),l=[],m=new Set,u=new Set;if(!c)throw new TypeError("checkTemplate requires a template kind.");const d=a.templateSyntaxVersion??ge;if(!Ue.includes(d))return l.push(C({code:y.SYNTAX_VERSION_UNSUPPORTED,message:`Template syntax version ${d} is not supported.`})),{blockRefs:[],issues:l,layoutCodes:[],valid:!1};const f=At({allowedDeprecatedBlockRefs:s,blocks:i,context:n,functions:r}),O=a.partContent||{},T=new Set(c.partDefinitions.map(({partCode:p})=>p));return c.partDefinitions.forEach(({partCode:p,required:h})=>{const b=O[p];if(typeof b!="string"||!b.trim()){h&&l.push(C({code:y.PART_REQUIRED,message:`Part "${p}" is required.`,partCode:p}));return}const R=_e(b,{allowBlocks:!0,env:f,partCode:p});l.push(...R.issues),R.blockRefs.forEach(L=>m.add(L)),Ce(b).forEach(L=>{u.has(L)||l.push(...er(L,{env:f,layouts:o,partCode:p})),u.add(L)})}),Object.keys(O).forEach(p=>{T.has(p)||l.push(C({code:y.PART_UNKNOWN,message:`Part "${p}" is not declared by template kind ${c.templateKindCode}.`,partCode:p}))}),kn(c,a).forEach(({fieldPath:p,content:h,expressionAllowed:b})=>{if(!b){Jn.test(h)&&l.push(C({code:y.FIELD_EXPRESSION_NOT_ALLOWED,message:`Field "${p}" must be a fixed value.`,partCode:p}));return}l.push(..._e(h,{allowBlocks:!1,env:f,partCode:p}).issues)}),{blockRefs:[...m],issues:l,layoutCodes:[...u],valid:!V(l)}}function er(t,{env:e,layouts:n,partCode:r}){const i=Ke({layoutCode:t,layouts:n});if(!i)return[C({code:y.LAYOUT_NOT_FOUND,layoutCode:t,message:`Layout ${t} has no published version.`,partCode:r})];const s=`${i.layoutCode}@${i.version}`;return[..._e(i.html||"",{allowBlocks:!1,env:e,partCode:r}).issues,...qe(i.html)].map(o=>({...o,layoutRef:s,message:`${s}: ${o.message}`,partCode:r}))}function tr({content:t,partCode:e,allowBlocks:n=!0,context:r,functions:i,blocks:s,allowedDeprecatedBlockRefs:o}={}){const a=At({allowedDeprecatedBlockRefs:o,blocks:s,context:r,functions:i}),c=_e(t,{allowBlocks:n,env:a,partCode:e});return{...c,valid:!V(c.issues)}}function _t({fragment:t,params:e,functions:n,context:r}={}){const{definitions:i,errors:s}=Y(e),o=s.map(c=>C({code:y.BLOCK_PARAMS_INVALID,message:c})),a=gt(t,{allowAssign:!0,context:r,functions:n,paramsRoot:We(i)});return o.push(...a.issues),{issues:o,requiredRoots:a.requiredRoots,valid:!V(o)}}function Ot({html:t,functions:e}={}){const n=gt(t||"",{allowAssign:!1,functions:e,paramsRoot:We([])}),r=[...n.issues.map(i=>({...i,partCode:"layout"})),...qe(t)];return{issues:r,requiredRoots:n.requiredRoots,valid:!V(r)}}function gt(t,{allowAssign:e,context:n,functions:r,paramsRoot:i}){const s=q(n),o=W(t,{allowBlocks:!1}),a=r||(s?re():null),c=Se(o.templates,{allowAssign:e,allowedFunctionNames:s?new Set(s.functionNames||[]):null,functionsByName:a?new Map(a.map(l=>[l.name,l])):null,locate:o.locate,roots:(s==null?void 0:s.roots)||null,text:o.text,variables:new Map([[z,i]])});return{issues:[...o.issues,...c.issues],requiredRoots:c.requiredRoots}}function At({allowedDeprecatedBlockRefs:t=[],blocks:e=[],context:n,functions:r}){const i=q(n);if(!i||!i.roots)throw new TypeError("Template checks require a data context.");const s=r||re();return{allowedDeprecatedBlockRefs:new Set(t),allowedFunctionNames:new Set(i.functionNames||[]),blocksByRef:new Map(e.map(o=>{const a=typeof o.describe=="function"?o.describe():o;return[`${a.blockCode}@${a.version}`,a]})),contextCode:i.contextCode,functionsByName:new Map(s.map(o=>[o.name,o])),roots:i.roots}}function _e(t,{allowBlocks:e,env:n,partCode:r}){const i=W(t,{allowBlocks:e,partCode:r}),s=[...i.issues];return s.push(...Se(i.templates,{allowedFunctionNames:n.allowedFunctionNames,functionsByName:n.functionsByName,locate:i.locate,roots:n.roots,text:i.text}).issues),i.blocks.forEach(o=>nr(o,n,s)),{blockRefs:i.blockRefs,issues:s}}function nr(t,e,n){const{blockRef:r,location:i}=t,s=(u,d,f)=>n.push(C({blockRef:r,code:u,message:d,severity:f,...i})),o=e.blocksByRef.get(r);if(!o){s(y.UNKNOWN_BLOCK,`Block ${r} does not exist.`);return}const a=o.stateCode||je.PUBLISHED;if(a===je.DRAFT){s(y.BLOCK_NOT_PUBLISHED,`Block ${r} is not published.`);return}if(a===je.DEPRECATED){const u=e.allowedDeprecatedBlockRefs.has(r);s(y.BLOCK_DEPRECATED,u?`Block ${r} is deprecated; consider a newer version.`:`Block ${r} is deprecated and cannot be added.`,u?K.WARNING:K.ERROR)}if(o.contextCode!==e.contextCode){s(y.BLOCK_CONTEXT_MISMATCH,`Block ${r} is for data context ${o.contextCode||"(none)"}, not ${e.contextCode}.`);return}const c=(o.requiredRoots||[]).filter(u=>!Object.hasOwn(e.roots,u));c.length&&s(y.BLOCK_ROOT_NOT_IN_CONTEXT,`Block ${r} requires data roots not in this context: ${c.join(", ")}.`);const{definitions:l}=Y(o.params),{errors:m}=He(l,t.params);if(m.forEach(u=>s(y.BLOCK_PARAMS_INVALID,`${r}: ${u}`)),typeof o.fragment=="string"&&!c.length){const u=W(o.fragment,{allowBlocks:!1}),d=Se(u.templates,{allowAssign:!0,allowedFunctionNames:e.allowedFunctionNames,functionsByName:e.functionsByName,locate:u.locate,roots:e.roots,text:u.text,variables:new Map([[z,We(l)]])});[...u.issues,...d.issues].forEach(f=>n.push(C({...i,blockRef:r,code:f.code,message:`${r}: ${f.message}`,severity:f.severity})))}}const rr=["active","created","creator","deleted","modified","owner","revision"],ir=["blockCode","category","contextCode","description","fragment","name","tenantCode","version"],ot=["category","contextCode","description","fragment","name","params"],sr=/^[A-Z][A-Z0-9_]*$/,or=Object.freeze({DEPRECATED:"TEMPLATE_BLOCK_DEPRECATED",PUBLISHED:"TEMPLATE_BLOCK_PUBLISHED"});class Ct extends g.TrackedEntity{constructor(e={}){e=e||{},super(e),this._type=e._type||"TemplateBlock",this.blockCode=e.blockCode,this.category=e.category||"",this.contextCode=e.contextCode||"",this.description=e.description||"",this.fragment=typeof e.fragment=="string"?e.fragment:"",this.lifecycle=e.lifecycle?be.init(e.lifecycle):null,this.name=e.name||"",this.params=Y(e.params).definitions,this.requiredRoots=Array.isArray(e.requiredRoots)?[...e.requiredRoots]:[],this.tenantCode=e.tenantCode||void 0,this.version=Number(e.version)}static get _classname(){return"TemplateBlock"}static get _superclass(){return"TemplateBlock"}static create({actionRevision:e=1,modified:n=Date.now(),...r}={}){return this.init({...r,lifecycle:be.create({actionRevision:e,modified:n}).toObject(),meta:{...r.meta,revision:e}})}get isValid(){var e;return super.isValid&&sr.test(this.blockCode||"")&&!!this.contextCode&&Number.isInteger(this.version)&&this.version>=1&&!!((e=this.lifecycle)!=null&&e.isValid)}get blockRef(){return`${this.blockCode}@${this.version}`}get stateCode(){var e,n;return((n=(e=this.lifecycle)==null?void 0:e.getState("publication"))==null?void 0:n.stateCode)||null}get isDraft(){return this.stateCode===k.DRAFT}getCode(){return this.blockRef}getId(){return this.id}check({context:e,functions:n}={}){var r;if(e&&((r=q(e))==null?void 0:r.contextCode)!==this.contextCode)throw new TypeError(`TemplateBlock ${this.blockRef} belongs to data context ${this.contextCode}.`);return _t({context:e,fragment:this.fragment,functions:n,params:this.params})}update(e={}){if(ot.some(r=>Object.hasOwn(e,r))&&!this.isDraft)throw new Error(`TemplateBlock ${this.blockRef} is ${this.stateCode}; publish changes as a new version.`);return ot.forEach(r=>{Object.hasOwn(e,r)&&(this[r]=r==="params"?Y(e.params).definitions:e[r]??"")}),super.update(e)}publish({actionRevision:e=this.revision+1,context:n,modified:r=Date.now(),functions:i}={}){const s=this.check({context:n,functions:i});if(!s.valid)throw new H(s.issues.map(o=>({...o,blockRef:this.blockRef})));return this.lifecycle.transition("publication",{actionRevision:e,modified:r,stateCode:k.PUBLISHED}),this.requiredRoots=s.requiredRoots,this.meta.revision=e,this.setModified()}deprecate({actionRevision:e=this.revision+1,modified:n=Date.now()}={}){return this.lifecycle.transition("publication",{actionRevision:e,modified:n,stateCode:k.DEPRECATED}),this.meta.revision=e,this.setModified()}createEntityAction({actionCode:e,actor:n,previousStateCode:r,timestamp:i=Date.now(),...s}={}){return g.EntityAction.init({...s,actionCode:e,actor:n,entityCode:this.blockRef,entityId:this.getId(),entityRevision:this.revision,entityType:this._type,lifecycleChange:{publication:{from:r,to:this.stateCode}},...this.tenantCode?{tenantCode:this.tenantCode}:{},timestamp:i})}describe(){return{blockCode:this.blockCode,blockRef:this.blockRef,category:this.category,contextCode:this.contextCode,description:this.description,fragment:this.fragment,name:this.name,params:g.copySerializableValue(this.params),requiredRoots:[...this.requiredRoots],stateCode:this.stateCode,...this.tenantCode?{tenantCode:this.tenantCode}:{},version:this.version}}toJSON(){return this.toObject()}toObject(){const e={_type:this._type,...this.lifecycle?{lifecycle:this.lifecycle.toObject()}:{},meta:g.copySerializableProperties(this.meta,rr),params:g.copySerializableValue(this.params),requiredRoots:[...this.requiredRoots],...g.copySerializableProperties(this,ir)};return typeof this.id<"u"&&(e.id=this.id),e}}const Q=["email","name"],ar=["bcc","cc","from","replyTo","to"];class Rt extends Et{constructor(e={}){e=e||{},super(e),this._type=e._type||"TemplateEmail",this.bcc=Be(e.bcc),this.cc=Be(e.cc),this.from=J(e.from),this.replyTo=J(e.replyTo),this.to=J(e.to)}static get _classname(){return"TemplateEmail"}static get kind(){return Ne}update(e={}){return ar.forEach(n=>{Object.hasOwn(e,n)&&(this[n]=n==="cc"||n==="bcc"?Be(e[n]):J(e[n]))}),super.update(e)}toObject(){return{...super.toObject(),bcc:this.bcc.map(e=>g.copySerializableProperties(e,Q)),cc:this.cc.map(e=>g.copySerializableProperties(e,Q)),from:this.from?g.copySerializableProperties(this.from,Q):null,replyTo:this.replyTo?g.copySerializableProperties(this.replyTo,Q):null,to:this.to?g.copySerializableProperties(this.to,Q):null}}}function J(t){return t?typeof t=="string"?t.trim()?{email:t.trim()}:null:typeof t!="object"||!t.email?null:{email:String(t.email).trim(),...t.name?{name:String(t.name)}:{}}:null}function Be(t){return(Array.isArray(t)?t:[]).map(J).filter(Boolean)}const ue=k;class $e extends be{static get _classname(){return"LifecycleTemplateLayout"}static get entityType(){return"TemplateLayout"}}const cr=["active","created","creator","deleted","modified","owner","revision"],lr=["description","eventShortCode","html","layoutCode","name","templateKindCode","tenantCode","version"],at=["description","html","name"],ur=/^[A-Z][A-Z0-9_]*$/,dr=Object.freeze({DEPRECATED:"TEMPLATE_LAYOUT_DEPRECATED",PUBLISHED:"TEMPLATE_LAYOUT_PUBLISHED"});class pr extends g.TrackedEntity{constructor(e={}){e=e||{},super(e),this._type=e._type||"TemplateLayout",this.description=e.description||"",this.eventShortCode=e.eventShortCode||void 0,this.html=typeof e.html=="string"?e.html:"",this.layoutCode=e.layoutCode,this.lifecycle=e.lifecycle?$e.init(e.lifecycle):null,this.name=e.name||"",this.requiredRoots=Array.isArray(e.requiredRoots)?[...e.requiredRoots]:[],this.templateKindCode=e.templateKindCode||Re.EMAIL,this.tenantCode=e.tenantCode||void 0,this.version=Number(e.version)}static get _classname(){return"TemplateLayout"}static get _superclass(){return"TemplateLayout"}static create({actionRevision:e=1,modified:n=Date.now(),...r}={}){return this.init({...r,lifecycle:$e.create({actionRevision:e,modified:n}).toObject(),meta:{...r.meta,revision:e}})}get isValid(){var e;return super.isValid&&ur.test(this.layoutCode||"")&&Number.isInteger(this.version)&&this.version>=1&&!!((e=this.lifecycle)!=null&&e.isValid)}get layoutRef(){return`${this.layoutCode}@${this.version}`}get stateCode(){var e,n;return((n=(e=this.lifecycle)==null?void 0:e.getState("publication"))==null?void 0:n.stateCode)||null}get isDraft(){return this.stateCode===ue.DRAFT}getCode(){return this.layoutRef}getId(){return this.id}check({functions:e}={}){return Ot({functions:e,html:this.html})}update(e={}){if(at.some(r=>Object.hasOwn(e,r))&&!this.isDraft)throw new Error(`TemplateLayout ${this.layoutRef} is ${this.stateCode}; publish changes as a new version.`);return at.forEach(r=>{Object.hasOwn(e,r)&&(this[r]=e[r]??"")}),super.update(e)}publish({actionRevision:e=this.revision+1,modified:n=Date.now(),functions:r}={}){const i=this.check({functions:r});if(!i.valid)throw new H(i.issues.map(s=>({...s,layoutRef:this.layoutRef})));return this.lifecycle.transition("publication",{actionRevision:e,modified:n,stateCode:ue.PUBLISHED}),this.requiredRoots=i.requiredRoots,this.meta.revision=e,this.setModified()}deprecate({actionRevision:e=this.revision+1,modified:n=Date.now()}={}){return this.lifecycle.transition("publication",{actionRevision:e,modified:n,stateCode:ue.DEPRECATED}),this.meta.revision=e,this.setModified()}createEntityAction({actionCode:e,actor:n,previousStateCode:r,timestamp:i=Date.now(),...s}={}){return g.EntityAction.init({...s,actionCode:e,actor:n,entityCode:this.layoutRef,entityId:this.getId(),entityRevision:this.revision,entityType:this._type,lifecycleChange:{publication:{from:r,to:this.stateCode}},...this.tenantCode?{tenantCode:this.tenantCode}:{},timestamp:i})}describe(){return{description:this.description,...this.eventShortCode?{eventShortCode:this.eventShortCode}:{},html:this.html,layoutCode:this.layoutCode,layoutRef:this.layoutRef,name:this.name,requiredRoots:[...this.requiredRoots],stateCode:this.stateCode,templateKindCode:this.templateKindCode,...this.tenantCode?{tenantCode:this.tenantCode}:{},version:this.version}}toJSON(){return this.toObject()}toObject(){const e={_type:this._type,...this.lifecycle?{lifecycle:this.lifecycle.toObject()}:{},meta:g.copySerializableProperties(this.meta,cr),requiredRoots:[...this.requiredRoots],...g.copySerializableProperties(this,lr)};return typeof this.id<"u"&&(e.id=this.id),e}}const Nt=Object.freeze({memoryLimit:1e7,parseLimit:1024*1024,renderLimit:1e3}),St="qw_block";let ee=null;const mr={parse(t){if(this.block=ee==null?void 0:ee[Number(t.args)],!this.block)throw new Error(`Unknown block instance ${t.args}.`)},*render(t,e){const n=t.spawn({...t.environments,[z]:this.block.params});yield this.liquid.renderer.renderTemplates(this.block.templates,n,e)}};function Lt({maxCacheEntries:t=500,limits:e={}}={}){const n=new Map,r=Object.freeze({...Nt,...e});let i=null;const s=()=>{const{filters:u,version:d}=un();if((i==null?void 0:i.version)===d)return i;n.clear();const f=O=>{const T=ft({escape:O,limits:r,tags:[...Ge,...fe]});return u.forEach(({name:E,handler:p,raw:h})=>T.registerFilter(E,{handler:p,raw:O&&h})),T.registerTag(St,mr),T};return i={html:f(!0),text:f(!1),version:d},i},o=({content:u,contentType:d,partCode:f,allowedFunctions:O,blocks:T,allowBlocks:E,cacheKey:p})=>{s();const h=p?`${p}\0${f}\0${d}\0${O.join(",")}`:null;if(h&&n.has(h)){const R=n.get(h);return n.delete(h),n.set(h,R),R}const b=Er({allowBlocks:E,allowedFunctions:O,blocks:T,content:u,contentType:d,engines:s(),partCode:f});return h&&(n.set(h,b),n.size>t&&n.delete(n.keys().next().value)),b},a=({content:u,contentType:d=x.TEXT_HTML,partCode:f,data:O,context:T,blocks:E,cacheKey:p,allowBlocks:h=!0}={})=>{const b=q(T);if(!b)throw new TypeError("Template rendering requires a data context.");return o({allowBlocks:h,allowedFunctions:[...b.functionNames||[]].sort(),blocks:hr(E),cacheKey:p,content:u??"",contentType:d,partCode:f}).render(O||{})};return Object.freeze({clearCache:()=>n.clear(),renderBlock:({block:u,params:d={},data:f,context:O}={})=>{const T=typeof(u==null?void 0:u.describe)=="function"?u.describe():u,E=`${T.blockCode}@${T.version}`,p=JSON.stringify(d).replace(/&/g,"&amp;").replace(/'/g,"&#39;");return a({blocks:[{...T,stateCode:"PUBLISHED"}],content:`<div data-qw-block="${E}" data-qw-params='${p}'></div>`,context:O,data:f,partCode:"block"})},renderContent:a,renderTemplate:({template:u,kind:d,data:f,context:O,blocks:T,cacheKey:E,draft:p=!1,layouts:h=[]}={})=>{var Ze;const b=typeof(u==null?void 0:u.toObject)=="function"?u.toObject():u||{},R=d||((Ze=u==null?void 0:u.constructor)==null?void 0:Ze.kind)||Xe(b.templateKindCode);if(!R)throw new TypeError("renderTemplate requires a template kind.");fr(b.templateSyntaxVersion);const L=q(O),Je=L!=null&&L.includeTemplateDocumentReference?{...f,template:{documentReference:b.documentReference??""}}:f,oe=p?null:E??Tr(b),Ie={};return R.partDefinitions.forEach(({partCode:F,contentType:we})=>{var et;const ae=(et=b.partContent)==null?void 0:et[F];if(typeof ae!="string"||!ae)return;if(we!==x.TEXT_HTML){Ie[F]=a({blocks:T,cacheKey:oe,content:ae,context:L,contentType:we,data:Je,partCode:F});return}const X=dt({html:ae,layouts:h});if(X.missingLayoutCodes.length)throw new D({message:`Layout ${X.missingLayoutCodes.join(", ")} has no published version.`,partCode:F});const Qt=oe&&X.layoutRefs.length?`${oe}\0${X.layoutRefs.join(",")}`:oe;Ie[F]=a({blocks:T,cacheKey:Qt,content:X.html,context:L,contentType:we,data:Je,partCode:F})}),{partContent:Ie}}})}function fr(t=ge){if(!Ue.includes(t))throw new H([C({code:y.SYNTAX_VERSION_UNSUPPORTED,message:`Template syntax version ${t} is not supported.`})])}function Tr(t){const{templateCode:e,tenantCode:n,meta:r}=t;return!e||!(r!=null&&r.revision)?null:`${n||""}\0${e}\0${r.revision}`}function hr(t=[]){return new Map((t||[]).map(e=>{const n=typeof e.describe=="function"?e.describe():e;return[`${n.blockCode}@${n.version}`,n]}))}function Er({content:t,contentType:e,partCode:n,allowedFunctions:r,blocks:i,allowBlocks:s,engines:o}){const a=new Map(re().map(p=>[p.name,p])),c=new Set(r),l=W(t,{allowBlocks:s,partCode:n}),m=(p,h)=>Se(p.templates,{allowedFunctionNames:c,functionsByName:a,locate:p.locate,text:p.text,...h}).issues,u=[...l.issues,...m(l,{})];if(V(u))throw new H(u);const d=e===x.TEXT_PLAIN?o.text:o.html,f=l.blocks.map(p=>br(p,{blocks:i,engine:d,partCode:n,policy:m}));let O="",T=0;l.blocks.forEach(({start:p,end:h},b)=>{O+=`${l.text.slice(T,p)}{% ${St} ${b} %}`,T=h}),O+=l.text.slice(T);const E=Pt(d,O,f);return Object.freeze({render(p){try{return d.renderSync(E,{...p})}catch(h){const b=(h==null?void 0:h.originalError)||h;if(b instanceof D)throw b;const R=String((b==null?void 0:b.message)||h.message).replace(/, line:\d+, col:\d+$/,"");throw new D({cause:h,message:`Failed to render ${n||"content"}: ${R}`,partCode:n})}}})}function br(t,{blocks:e,engine:n,partCode:r,policy:i}){const{blockRef:s}=t,o=e.get(s);if(!o||typeof o.fragment!="string")throw new D({message:`Block ${s} is not available for rendering.`,partCode:r,source:s});if(o.stateCode==="DRAFT")throw new D({message:`Block ${s} is not published.`,partCode:r,source:s});const{definitions:a,errors:c}=Y(o.params),{errors:l,values:m}=He(a,t.params);if(c.length||l.length)throw new D({message:`Block ${s} params are invalid: ${[...c,...l].join(" ")}`,partCode:r,source:s});const u=W(o.fragment,{allowBlocks:!1}),d=[...u.issues,...i(u,{allowAssign:!0,variables:new Map([[z,null]])})];if(V(d))throw new H(d.map(f=>({...f,blockRef:s})));return{params:Object.freeze(xn(a,m)),templates:Pt(n,u.text,[])}}function Pt(t,e,n){ee=n;try{return t.parse(e)}finally{ee=null}}const yr=/^[^\s@<>()[\]\\,;:"]+@[^\s"(),:;<>@[\\\]][^\s"(),.:;<>@[\\\]]*\.[^\s"(),:;<>@[\\\]]+$/,_r=/cid:([^\s"'<>)]+)/g,Or=Lt();async function gr({template:t,data:e,context:n,blocks:r,layouts:i,renderer:s=Or,resolveInlineImage:o,juiceOptions:a,draft:c=!1}={}){const l=typeof(t==null?void 0:t.toObject)=="function"?t.toObject():t||{},{partContent:m}=s.renderTemplate({blocks:r,context:n,data:e,draft:c,kind:Ne,layouts:i,template:l}),u=(E,p)=>s.renderContent({allowBlocks:!1,content:E,context:n,contentType:x.TEXT_PLAIN,data:e,partCode:p}).trim(),d=(E,p,{fixedEmail:h=!1}={})=>{if(!(E!=null&&E.email))return null;if(h&&/\{\{|\{%/.test(E.email))throw new D({message:`${p}.email must be a fixed address.`,partCode:`${p}.email`});const b=h?E.email.trim():u(E.email,`${p}.email`);if(!b)return null;if(!yr.test(b))throw new D({message:`${p}.email "${b}" is not a valid email address.`,partCode:`${p}.email`});const R=E.name?u(E.name,`${p}.name`):"";return{email:b,...R?{name:R}:{}}},f=(E,p)=>(Array.isArray(E)?E:[]).map((h,b)=>d(typeof h=="string"?{email:h}:h,`${p}[${b}]`)).filter(Boolean);let O=m.html?en.default(m.html,{preserveImportant:!0,preserveMediaQueries:!0,...a}):"";const T=[...new Set([...O.matchAll(_r)].map(E=>E[1]))];if(o&&T.length){const E=await Promise.all(T.map(p=>o({contentId:p})));T.forEach((p,h)=>{E[h]&&(O=O.split(`cid:${p}`).join(E[h]))})}return{bcc:f(l.bcc,"bcc"),cc:f(l.cc,"cc"),from:d(l.from,"from",{fixedEmail:!0}),html:O,inlineAttachments:T.map(E=>({contentId:E})),replyTo:d(l.replyTo,"replyTo"),subject:(m.subject||"").replace(/\s+/g," ").trim(),text:m.text??null,to:d(l.to,"to",{fixedEmail:!0})}}const It=Object.freeze({blockCode:"INVOICE_LINES_TABLE",category:"Invoice",contextCode:"RECEIPT",fragment:`<table width="100%" cellpadding="4" cellspacing="0" role="presentation">
3
3
  {% for line in invoice.lines %}
4
4
  <tr>
5
5
  <td>{{ line.name }}</td>
@@ -7,7 +7,7 @@
7
7
  <td align="right">{{ line.amount | __format_money: invoice.currencyCode }}</td>
8
8
  </tr>
9
9
  {% endfor %}
10
- </table>`,name:"Invoice lines (fixed)",params:[],version:1}),St=Object.freeze({blockCode:"INVOICE_LINES_TABLE",category:"Invoice",contextCode:"RECEIPT",description:"Invoice lines with selectable columns and an optional total row.",fragment:`{% assign lines = invoice.lines %}
10
+ </table>`,name:"Invoice lines (fixed)",params:[],version:1}),wt=Object.freeze({blockCode:"INVOICE_LINES_TABLE",category:"Invoice",contextCode:"RECEIPT",description:"Invoice lines with selectable columns and an optional total row.",fragment:`{% assign lines = invoice.lines %}
11
11
  {% if params.onlyPositiveQty %}{% assign lines = invoice.lines | where_exp: "line", "line.qty > 0" %}{% endif %}
12
12
  <table class="invoice-lines" width="100%" cellpadding="4" cellspacing="0" role="presentation">
13
13
  <thead>
@@ -35,14 +35,14 @@
35
35
  </tr>
36
36
  </tfoot>
37
37
  {% endif %}
38
- </table>`,name:"Invoice lines",params:[{default:["name","qty","amount"],label:"Columns",options:[{label:"Item",value:"name"},{label:"Unit price",value:"unitPrice"},{label:"Quantity",value:"qty"},{label:"Amount",value:"amount"}],paramCode:"columns",type:"multiSelect"},{default:!0,label:"Only lines with quantity > 0",paramCode:"onlyPositiveQty",type:"boolean"},{default:!0,label:"Show total",paramCode:"showTotal",type:"boolean"}],version:2}),Lt=Object.freeze({blockCode:"AUTHOR_LIST",category:"Abstract",contextCode:"ABSTRACT",fragment:`{% if params.heading %}
38
+ </table>`,name:"Invoice lines",params:[{default:["name","qty","amount"],label:"Columns",options:[{label:"Item",value:"name"},{label:"Unit price",value:"unitPrice"},{label:"Quantity",value:"qty"},{label:"Amount",value:"amount"}],paramCode:"columns",type:"multiSelect"},{default:!0,label:"Only lines with quantity > 0",paramCode:"onlyPositiveQty",type:"boolean"},{default:!0,label:"Show total",paramCode:"showTotal",type:"boolean"}],version:2}),Dt=Object.freeze({blockCode:"AUTHOR_LIST",category:"Abstract",contextCode:"ABSTRACT",fragment:`{% if params.heading %}
39
39
  <p><strong>{{ params.heading }}</strong></p>
40
40
  {% endif %}
41
41
  <ul>
42
42
  {% for author in abstract.authors %}
43
43
  <li>{{ author.displayName }}{% if params.showAffiliation and author.affiliation %}, {{ author.affiliation }}{% endif %}{% if author.isPresenter %} (presenter){% endif %}</li>
44
44
  {% endfor %}
45
- </ul>`,name:"Author list",params:[{label:"Heading",paramCode:"heading",type:"text"},{default:!0,label:"Show affiliation",paramCode:"showAffiliation",type:"boolean"}],version:1}),Pt=Object.freeze({blockCode:"AUTHOR_LIST",category:"Abstract",contextCode:"ABSTRACT",description:"Authors in a table, with optional affiliation, presentation topic and capacity.",fragment:`<table cellpadding="2" cellspacing="0" role="presentation" style="border: 0;">
45
+ </ul>`,name:"Author list",params:[{label:"Heading",paramCode:"heading",type:"text"},{default:!0,label:"Show affiliation",paramCode:"showAffiliation",type:"boolean"}],version:1}),vt=Object.freeze({blockCode:"AUTHOR_LIST",category:"Abstract",contextCode:"ABSTRACT",description:"Authors in a table, with optional affiliation, presentation topic and capacity.",fragment:`<table cellpadding="2" cellspacing="0" role="presentation" style="border: 0;">
46
46
  <tbody>
47
47
  {% for author in abstract.authors %}
48
48
  <tr>
@@ -57,11 +57,11 @@
57
57
  </tr>
58
58
  {% endfor %}
59
59
  </tbody>
60
- </table>`,name:"Author table",params:[{default:["presentationTopic","capacity"],label:"Details",options:[{label:"Affiliation",value:"affiliation"},{label:"Presentation topic",value:"presentationTopic"},{label:"Capacity",value:"capacity"},{label:"Mark the presenter",value:"presenter"}],paramCode:"details",type:"multiSelect"}],version:2});function _r({modified:t=Date.UTC(2027,0,1)}={}){const e=n=>_t.create({...n,modified:t}).publish({modified:t});return[e(Nt).deprecate({modified:t}),e(St),e(Lt),e(Pt)]}const ne=v({fields:{code:{description:"The recipient's event registration code.",label:"Registration code",type:"string"},displayName:{description:"Prefix, first name and last name, for greetings.",label:"Display name",type:"string",value:t=>[t.prefix,t.firstName,t.lastName].filter(Boolean).join(" ")},email:{description:"The recipient's email address.",label:"Email",type:"string"},firstName:{description:"The recipient's first name.",label:"First name",type:"string"},lastName:{description:"The recipient's last name.",label:"Last name",type:"string"},prefix:{description:"Title before the name, such as Dr or Prof.",label:"Prefix",type:"string"}},description:"Current email recipient values.",label:"Recipient",projectionCode:"PERSON"}),re=v({fields:{badge:{fields:{barcodeFormat:{description:"Barcode format printed on badges, such as QR_CODE.",label:"Barcode format",type:"string"}},description:"Badge settings of the event.",label:"Badge",type:"object"},displayDate:{description:"Event dates as shown to participants.",label:"Display date",type:"string"},isOnline:{description:"Whether the event is held online.",label:"Online event",type:"boolean"},location:{description:"Venue of the event.",label:"Location",type:"string"},name:{description:"Full name of the event.",label:"Event name",type:"string"},websiteUrl:{description:"Address of the event website.",label:"Website",type:"string"}},description:"Current congress or event display information.",label:"Event",projectionCode:"EVENT"}),It=v({fields:{amount:{description:"Amount of the line: quantity times unit price.",label:"Amount",type:"number"},name:{description:"Name of the item bought.",label:"Item",type:"string",value:t=>{var e;return(e=t.merchandise)==null?void 0:e.name}},qty:{description:"Number of items.",label:"Quantity",type:"number"},unitPrice:{description:"Price of one item.",label:"Unit price",type:"number"}},description:"One line of an invoice.",label:"Invoice line",projectionCode:"INVOICE_LINE"}),wt=v({fields:{created:{description:"Date the invoice was issued.",label:"Invoice date",type:"date"},currencyCode:{description:"Currency code of the invoice, such as AUD.",label:"Currency",type:"string"},invoiceNumber:{description:"Number printed on the invoice.",label:"Invoice number",type:"string"},lines:ge(It,{description:"Items bought on the invoice.",label:"Lines"}),revisionNumber:{description:"Revision of the invoice; 0 for the first issue.",label:"Revision",type:"number"},total:{description:"Sum of all invoice lines.",label:"Total",type:"number",value:t=>(t.lines||[]).reduce((e,n)=>e+(n.amount||0),0)}},description:"Invoice header and number values.",label:"Invoice",projectionCode:"INVOICE"}),Dt=v({fields:{paidAmount:{description:"Amount paid in this payment.",label:"Paid amount",type:"number"},paymentDate:{description:"Date the payment was made.",label:"Payment date",type:"date"},paymentMethod:{description:"How the payment was made, such as credit card.",label:"Payment method",type:"string"},paymentRemark:{description:"Remark recorded with the payment.",label:"Payment remark",type:"string"},receivedAmount:{description:"Amount received after fees.",label:"Received amount",type:"number"}},description:"Payment result, paid amount and payment details.",label:"Payment result",projectionCode:"PAYMENT_RESULT"}),vt=v({fields:{affiliation:{description:"The author's institution.",label:"Affiliation",type:"string"},capacity:{description:"The author's role on the abstract, such as co-author.",label:"Capacity",type:"string"},displayName:{description:"First name and last name of the author.",label:"Display name",type:"string",value:t=>[t.firstName,t.lastName].filter(Boolean).join(" ")},isPresenter:{description:"Whether the author presents the abstract.",label:"Presenter",type:"boolean"},presentationTopic:{description:"Topic the author presents.",label:"Presentation topic",type:"string"}},description:"One author of an abstract.",label:"Author",projectionCode:"AUTHOR"}),jt=v({fields:{abstractCode:{description:"Reference ID of the submitted abstract.",label:"Abstract code",type:"string"},authors:ge(vt,{description:"Authors attached to the abstract.",label:"Authors"}),conclusions:{description:"Conclusions section of the abstract.",label:"Conclusions",type:"string"},keywords:{description:"Keywords given by the submitter.",label:"Keywords",type:"string"},methods:{description:"Methods section of the abstract.",label:"Methods",type:"string"},presentationType:{description:"Requested presentation type, such as oral or poster.",label:"Presentation type",type:"string"},purpose:{description:"Purpose section of the abstract.",label:"Purpose",type:"string"},results:{description:"Results section of the abstract.",label:"Results",type:"string"},subspecialty:{description:"Subspecialty the abstract is submitted to.",label:"Subspecialty",type:"string"},summary:{description:"Summary of the abstract without formatting.",label:"Summary (plain text)",type:"string"},title:{description:"Title of the abstract.",label:"Title",type:"string"}},description:"Abstract submission values.",label:"Abstract",projectionCode:"ABSTRACT"}),Bt=v({fields:{eventRegistrationCode:{description:"Code of the event registration.",label:"Registration code",type:"string"},hasBadge:{description:"Whether the registration includes a badge.",label:"Has badge",type:"boolean"},roleCodes:ge({label:"Role",type:"string"},{description:"Role codes of the registration.",label:"Roles"})},description:"Event registration profile values.",label:"Event registration",projectionCode:"EVENT_REGISTRATION"}),Se=Object.freeze({badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Example Convention Centre",name:"Example Congress 2027",websiteUrl:"https://congress.example.org"}),Le=Object.freeze({"ER-1001":{code:"ER-1001",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"},"ER-1002":{code:"ER-1002",email:"sam.wong@example.org",firstName:"Sam",lastName:"Wong",prefix:"Prof"},"ER-1003":{code:"ER-1003",email:"kim.lee@example.org",firstName:"Kim",lastName:"Lee",prefix:""}}),Mt=Object.freeze({"INV-2027-0001":{created:Date.UTC(2027,2,14),currencyCode:"HKD",invoiceNumber:"INV-2027-0001",lines:[{amount:2e3,merchandise:{name:"Delegate registration"},qty:1,unitPrice:2e3},{amount:1200,merchandise:{name:"Gala dinner"},qty:2,unitPrice:600},{amount:0,merchandise:{name:"Workshop waitlist"},qty:0,unitPrice:300}],payerCode:"ER-1001",paymentResult:{paidAmount:3200,paymentDate:Date.UTC(2027,2,15),paymentMethod:"Credit card",paymentRemark:"Paid online",receivedAmount:3200},revisionNumber:1}}),xt=Object.freeze({"ABS-0042":{abstractCode:"ABS-0042",authors:[{affiliation:"Example University",capacity:"Presenting author",firstName:"Alex",lastName:"Chan",isPresenter:!0,presentationTopic:"Study design",registrationCode:"ER-1001"},{affiliation:"Example Hospital",capacity:"Co-author",firstName:"Sam",lastName:"Wong",isPresenter:!1,registrationCode:"ER-1002"}],conclusions:"The example approach was feasible.",keywords:"example, study",methods:"A retrospective review of example cases.",presentationType:"Oral",purpose:"To describe outcomes of an example study.",results:"Outcomes improved in most cases.",subspecialty:"Retina",submitterCode:"ER-1003",summary:`Background
60
+ </table>`,name:"Author table",params:[{default:["presentationTopic","capacity"],label:"Details",options:[{label:"Affiliation",value:"affiliation"},{label:"Presentation topic",value:"presentationTopic"},{label:"Capacity",value:"capacity"},{label:"Mark the presenter",value:"presenter"}],paramCode:"details",type:"multiSelect"}],version:2});function Ar({modified:t=Date.UTC(2027,0,1)}={}){const e=n=>Ct.create({...n,modified:t}).publish({modified:t});return[e(It).deprecate({modified:t}),e(wt),e(Dt),e(vt)]}const ie=j({fields:{code:{description:"The recipient's event registration code.",label:"Registration code",type:"string"},displayName:{description:"Prefix, first name and last name, for greetings.",label:"Display name",type:"string",value:t=>[t.prefix,t.firstName,t.lastName].filter(Boolean).join(" ")},email:{description:"The recipient's email address.",label:"Email",type:"string"},firstName:{description:"The recipient's first name.",label:"First name",type:"string"},lastName:{description:"The recipient's last name.",label:"Last name",type:"string"},prefix:{description:"Title before the name, such as Dr or Prof.",label:"Prefix",type:"string"}},description:"Current email recipient values.",label:"Recipient",projectionCode:"PERSON"}),se=j({fields:{badge:{fields:{barcodeFormat:{description:"Barcode format printed on badges, such as QR_CODE.",label:"Barcode format",type:"string"}},description:"Badge settings of the event.",label:"Badge",type:"object"},displayDate:{description:"Event dates as shown to participants.",label:"Display date",type:"string"},isOnline:{description:"Whether the event is held online.",label:"Online event",type:"boolean"},location:{description:"Venue of the event.",label:"Location",type:"string"},name:{description:"Full name of the event.",label:"Event name",type:"string"},websiteUrl:{description:"Address of the event website.",label:"Website",type:"string"}},description:"Current congress or event display information.",label:"Event",projectionCode:"EVENT"}),jt=j({fields:{amount:{description:"Amount of the line: quantity times unit price.",label:"Amount",type:"number"},name:{description:"Name of the item bought.",label:"Item",type:"string",value:t=>{var e;return(e=t.merchandise)==null?void 0:e.name}},qty:{description:"Number of items.",label:"Quantity",type:"number"},unitPrice:{description:"Price of one item.",label:"Unit price",type:"number"}},description:"One line of an invoice.",label:"Invoice line",projectionCode:"INVOICE_LINE"}),Bt=j({fields:{created:{description:"Date the invoice was issued.",label:"Invoice date",type:"date"},currencyCode:{description:"Currency code of the invoice, such as AUD.",label:"Currency",type:"string"},invoiceNumber:{description:"Number printed on the invoice.",label:"Invoice number",type:"string"},lines:Ae(jt,{description:"Items bought on the invoice.",label:"Lines"}),revisionNumber:{description:"Revision of the invoice; 0 for the first issue.",label:"Revision",type:"number"},total:{description:"Sum of all invoice lines.",label:"Total",type:"number",value:t=>(t.lines||[]).reduce((e,n)=>e+(n.amount||0),0)}},description:"Invoice header and number values.",label:"Invoice",projectionCode:"INVOICE"}),xt=j({fields:{paidAmount:{description:"Amount paid in this payment.",label:"Paid amount",type:"number"},paymentDate:{description:"Date the payment was made.",label:"Payment date",type:"date"},paymentMethod:{description:"How the payment was made, such as credit card.",label:"Payment method",type:"string"},paymentRemark:{description:"Remark recorded with the payment.",label:"Payment remark",type:"string"},receivedAmount:{description:"Amount received after fees.",label:"Received amount",type:"number"}},description:"Payment result, paid amount and payment details.",label:"Payment result",projectionCode:"PAYMENT_RESULT"}),Mt=j({fields:{affiliation:{description:"The author's institution.",label:"Affiliation",type:"string"},capacity:{description:"The author's role on the abstract, such as co-author.",label:"Capacity",type:"string"},displayName:{description:"First name and last name of the author.",label:"Display name",type:"string",value:t=>[t.firstName,t.lastName].filter(Boolean).join(" ")},isPresenter:{description:"Whether the author presents the abstract.",label:"Presenter",type:"boolean"},presentationTopic:{description:"Topic the author presents.",label:"Presentation topic",type:"string"}},description:"One author of an abstract.",label:"Author",projectionCode:"AUTHOR"}),$t=j({fields:{abstractCode:{description:"Reference ID of the submitted abstract.",label:"Abstract code",type:"string"},authors:Ae(Mt,{description:"Authors attached to the abstract.",label:"Authors"}),conclusions:{description:"Conclusions section of the abstract.",label:"Conclusions",type:"string"},keywords:{description:"Keywords given by the submitter.",label:"Keywords",type:"string"},methods:{description:"Methods section of the abstract.",label:"Methods",type:"string"},presentationType:{description:"Requested presentation type, such as oral or poster.",label:"Presentation type",type:"string"},purpose:{description:"Purpose section of the abstract.",label:"Purpose",type:"string"},results:{description:"Results section of the abstract.",label:"Results",type:"string"},subspecialty:{description:"Subspecialty the abstract is submitted to.",label:"Subspecialty",type:"string"},summary:{description:"Summary of the abstract without formatting.",label:"Summary (plain text)",type:"string"},title:{description:"Title of the abstract.",label:"Title",type:"string"}},description:"Abstract submission values.",label:"Abstract",projectionCode:"ABSTRACT"}),Ut=j({fields:{eventRegistrationCode:{description:"Code of the event registration.",label:"Registration code",type:"string"},hasBadge:{description:"Whether the registration includes a badge.",label:"Has badge",type:"boolean"},roleCodes:Ae({label:"Role",type:"string"},{description:"Role codes of the registration.",label:"Roles"})},description:"Event registration profile values.",label:"Event registration",projectionCode:"EVENT_REGISTRATION"}),Le=Object.freeze({badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Example Convention Centre",name:"Example Congress 2027",websiteUrl:"https://congress.example.org"}),Pe=Object.freeze({"ER-1001":{code:"ER-1001",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"},"ER-1002":{code:"ER-1002",email:"sam.wong@example.org",firstName:"Sam",lastName:"Wong",prefix:"Prof"},"ER-1003":{code:"ER-1003",email:"kim.lee@example.org",firstName:"Kim",lastName:"Lee",prefix:""}}),kt=Object.freeze({"INV-2027-0001":{created:Date.UTC(2027,2,14),currencyCode:"HKD",invoiceNumber:"INV-2027-0001",lines:[{amount:2e3,merchandise:{name:"Delegate registration"},qty:1,unitPrice:2e3},{amount:1200,merchandise:{name:"Gala dinner"},qty:2,unitPrice:600},{amount:0,merchandise:{name:"Workshop waitlist"},qty:0,unitPrice:300}],payerCode:"ER-1001",paymentResult:{paidAmount:3200,paymentDate:Date.UTC(2027,2,15),paymentMethod:"Credit card",paymentRemark:"Paid online",receivedAmount:3200},revisionNumber:1}}),zt=Object.freeze({"ABS-0042":{abstractCode:"ABS-0042",authors:[{affiliation:"Example University",capacity:"Presenting author",firstName:"Alex",lastName:"Chan",isPresenter:!0,presentationTopic:"Study design",registrationCode:"ER-1001"},{affiliation:"Example Hospital",capacity:"Co-author",firstName:"Sam",lastName:"Wong",isPresenter:!1,registrationCode:"ER-1002"}],conclusions:"The example approach was feasible.",keywords:"example, study",methods:"A retrospective review of example cases.",presentationType:"Oral",purpose:"To describe outcomes of an example study.",results:"Outcomes improved in most cases.",subspecialty:"Retina",submitterCode:"ER-1003",summary:`Background
61
61
  Methods
62
- Results`,title:"Outcomes of an example study"}}),$t=Object.freeze({"ER-1001":{eventRegistrationCode:"ER-1001",hasBadge:!0,roleCodes:["REGISTRANT","DELEGATE"]}}),x=Object.freeze({ALL_AUTHORS:"ALL_AUTHORS",PRESENTER:"PRESENTER",SUBMITTER:"SUBMITTER"}),Ut=Z({contextCode:"ABSTRACT",functionNames:["__format_date","__multiline"],loadData:async({subjectRef:t,recipientType:e})=>{const n=xt[t];return n?{[x.ALL_AUTHORS]:n.authors.map(i=>i.registrationCode),[x.PRESENTER]:n.authors.filter(i=>i.isPresenter).map(i=>i.registrationCode),[x.SUBMITTER]:[n.submitterCode]}[e].map(i=>({recipientRef:i,roots:{abstract:n,event:Se,recipient:Le[i]}})):[]},name:"Abstract",recipientRules:[{name:"Submitter",recipientType:x.SUBMITTER},{name:"Presenting author",recipientType:x.PRESENTER},{name:"All authors",recipientType:x.ALL_AUTHORS}],roots:{abstract:jt,event:re,recipient:ne},sampleData:{abstract:{abstractCode:"ABS-0001",authors:[{affiliation:"Sample University",capacity:"Presenting author",displayName:"Alex Chan",isPresenter:!0,presentationTopic:"Sample topic"},{affiliation:"Sample Hospital",capacity:"Co-author",displayName:"Sam Wong",isPresenter:!1,presentationTopic:""}],conclusions:"Sample conclusions.",keywords:"sample, keywords",methods:"Sample methods.",presentationType:"Poster",purpose:"Sample purpose.",results:"Sample results.",subspecialty:"Retina",summary:`Line one
63
- Line two`,title:"Sample abstract title"},event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}},subjectType:"Abstract"}),kt=Z({contextCode:"EVENT_REGISTRATION",functionNames:["__barcode","__format_date"],loadData:async({subjectRef:t})=>{const e=$t[t];return e?[{recipientRef:t,roots:{event:Se,eventRegistration:e,recipient:Le[t]}}]:[]},name:"Event registration",recipientRules:[{name:"Registrant",recipientType:"REGISTRANT"}],roots:{event:re,eventRegistration:Bt,recipient:ne},sampleData:{event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},eventRegistration:{eventRegistrationCode:"ER-0001",hasBadge:!0,roleCodes:["REGISTRANT"]},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}},subjectType:"EventRegistration"}),Vt=Z({contextCode:"RECEIPT",functionNames:["__format_date","__format_money"],loadData:async({subjectRef:t})=>{const e=Mt[t];return e?[{recipientRef:e.payerCode,roots:{event:Se,invoice:e,paymentResult:e.paymentResult,recipient:Le[e.payerCode]}}]:[]},name:"Receipt",recipientRules:[{name:"Payer",recipientType:"PAYER"}],roots:{event:re,invoice:wt,paymentResult:Dt,recipient:ne},sampleData:{event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},invoice:{created:Date.UTC(2027,0,5),currencyCode:"HKD",invoiceNumber:"INV-0001",lines:[{amount:2e3,name:"Delegate registration",qty:1,unitPrice:2e3},{amount:1200,name:"Gala dinner",qty:2,unitPrice:600}],revisionNumber:1,total:3200},paymentResult:{paidAmount:3200,paymentDate:Date.UTC(2027,0,6),paymentMethod:"Credit card",paymentRemark:"Paid online",receivedAmount:3200},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}},subjectType:"Invoice"}),Or=Z({contextCode:"LAYOUT",functionNames:["__format_date"],name:"Layout (every email)",roots:{event:re,recipient:ne},sampleData:{event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}}}),zt=Object.freeze({ABSTRACT:Ut,EVENT_REGISTRATION:kt,RECEIPT:Vt}),gr=Object.freeze({ABSTRACT:"ABSTRACT",EVENT_REGISTRATION:"EVENT_REGISTRATION",RECEIPT:"RECEIPT",STORE:"RECEIPT"});function _e(t){return gr[t]||null}function Ar(t){return zt[_e(t)]||null}const Ft=Object.freeze([{description:"Format an amount with a currency code, e.g. HKD 1,200.00.",fn:(t,e)=>{if(t===null)return"";const n=Number(t).toLocaleString("en-US",{maximumFractionDigits:2,minimumFractionDigits:2});return e?`${e} ${n}`:n},label:"money",name:"__format_money",signature:[{types:["number"]},{optional:!0,types:["string"]}]},{description:"Format a timestamp as YYYY-MM-DD (UTC).",fn:t=>t===null?"":new Date(t).toISOString().slice(0,10),label:"date",name:"__format_date",signature:[{types:["number"]}]},{description:"Inline barcode image reference (cid:) for the given value and format.",fn:(t,e)=>t===null?"":`cid:barcode.${e||"QR_CODE"}.${encodeURIComponent(t)}`,label:"barcode",name:"__barcode",signature:[{types:["string"]},{optional:!0,types:["string"]}]},{description:"Escape plain text and keep its line breaks as <br>.",fn:t=>t===null?"":String(t).replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`).replace(/\r?\n/g,"<br>"),label:"lines",name:"__multiline",signature:[{types:["string"]}],trustedHtml:!0}]);function Cr(){const t=new Set(te().map(({name:e})=>e));Ft.forEach(e=>{t.has(e.name)||st(e)})}const Kt=Object.freeze({description:"Event banner across the top of the email.",eventShortCode:"EXAMPLE2027",html:'<img src="https://congress.2026.apvrs.org/userfile/apvrs/img/apvrs2026/banner.png" alt="{{ event.name }}" width="600" style="display: block; width: 100%; height: auto; border: 0;">',layoutCode:"APVRS_HEADER",name:"APVRS header",tenantCode:"example",version:1}),qt=Object.freeze({description:"Event name, dates and website below the content.",eventShortCode:"EXAMPLE2027",html:'<p style="margin: 24px 0 0; padding-top: 12px; border-top: 1px solid #dddddd; font-size: 16px; color: #666666;">{{ event.name }} · {{ event.displayDate }} · <a href="{{ event.websiteUrl }}">{{ event.websiteUrl }}</a></p>',layoutCode:"CONGRESS_FOOTER",name:"Congress footer",tenantCode:"example",version:1}),Gt=Object.freeze({description:"APVRS 2026 venue and copyright lines for the footer row of the email frame.",eventShortCode:"EXAMPLE2027",html:'<p style="margin: 0; font-size: 12px; line-height: 1.5; color: #888888;">APVRS 2026 Gold Coast · Gold Coast Convention &amp; Exhibition Centre, Queensland, Australia<br>© 2026 Asia-Pacific Vitreo-Retina Society. All rights reserved.</p>',layoutCode:"APVRS_FOOTER",name:"APVRS footer",tenantCode:"example",version:1}),Rr=Object.freeze([Kt,qt,Gt]),Nr=["mobileWalletBadgePass","subTemplateGroupName","templateGroupName"];class Sr extends Ot{constructor(e={}){e=e||{},super({...e,contextCode:_e(e.templateGroupName)||e.contextCode}),this._type=e._type||"TemplateEmailCongress",this.eventShortCode=e.eventShortCode,this.mobileWalletBadgePass=!!e.mobileWalletBadgePass,this.subTemplateGroupName=e.subTemplateGroupName||null,this.templateGroupName=e.templateGroupName}static get _classname(){return"TemplateEmailCongress"}get isValid(){return super.isValid&&!!this.eventShortCode&&!!this.templateGroupName}update(e={}){return Nr.forEach(n=>{Object.hasOwn(e,n)&&(this[n]=n==="mobileWalletBadgePass"?!!e[n]:e[n])}),Object.hasOwn(e,"templateGroupName")&&(this.contextCode=_e(e.templateGroupName)),super.update(e)}toObject(){return{...super.toObject(),eventShortCode:this.eventShortCode,mobileWalletBadgePass:this.mobileWalletBadgePass,subTemplateGroupName:this.subTemplateGroupName,templateGroupName:this.templateGroupName}}}const Lr=Object.freeze({bcc:[{email:"finance@congress.example.org"}],eventShortCode:"EXAMPLE2027",from:{email:"secretariat@congress.example.org",name:"{{ event.name }} Secretariat"},meta:{revision:3},name:"Payment completed",partContent:{html:["<style>.receipt h2 { color: #1f4e79; } .invoice-lines th { background: #cedeea; }</style>",'<div class="receipt">',"<p>Dear {{ recipient.displayName }},</p>","<p>Thank you for your payment for {{ event.name }}.</p>","<h2>Invoice {{ invoice.invoiceNumber }}.{{ invoice.revisionNumber }}</h2>","<p>Invoice date: {{ invoice.created | __format_date }}</p>",`<div data-qw-block="INVOICE_LINES_TABLE@2" data-qw-params='{"columns":["name","qty","amount"]}'></div>`,"<p>Paid {{ paymentResult.paidAmount | __format_money: invoice.currencyCode }} by {{ paymentResult.paymentMethod }} on {{ paymentResult.paymentDate | __format_date }}.</p>","</div>"].join(`
64
- `),subject:"Payment completed - {{ invoice.invoiceNumber }}",text:"Dear {{ recipient.displayName }}, thank you for your payment of {{ paymentResult.paidAmount | __format_money: invoice.currencyCode }} for {{ event.name }}."},replyTo:{email:"secretariat@congress.example.org"},subTemplateGroupName:"EVENT",templateCode:"RECEIPT.EVENT.paymentCompleted",templateGroupName:"RECEIPT",tenantCode:"example"}),Pr=Object.freeze({eventShortCode:"EXAMPLE2027",meta:{revision:1},name:"Submission acknowledgement",partContent:{html:["<p>Dear {{ recipient.displayName }},</p>",'<p>We have received abstract {{ abstract.abstractCode }} "{{ abstract.title }}" ({{ abstract.presentationType }}).</p>',`<div data-qw-block="AUTHOR_LIST@1" data-qw-params='{"heading":"Authors"}'></div>`,"<p>{{ abstract.summary | __multiline }}</p>","{% if event.isOnline %}<p>The congress is held online.</p>{% else %}<p>Venue: {{ event.location }}</p>{% endif %}"].join(`
65
- `),subject:"Abstract {{ abstract.abstractCode }} received"},subTemplateGroupName:null,templateCode:"ABSTRACT.submissionAcknowledgement",templateGroupName:"ABSTRACT",tenantCode:"example"}),Ir=Object.freeze({eventShortCode:"EXAMPLE2027",meta:{revision:1},mobileWalletBadgePass:!0,name:"Registration confirmation",partContent:{html:["<p>Dear {{ recipient.displayName }},</p>","<p>Your registration code is {{ recipient.code }}.</p>",'{% if event.badge.barcodeFormat == "QR_CODE" %}',` <img alt="Badge" src="{{ recipient.code | __barcode: 'QR_CODE' }}">`,"{% else %}",` <img alt="Badge" src="{{ recipient.code | __barcode: 'PDF417' }}">`,"{% endif %}"].join(`
66
- `),subject:"Registration confirmed - {{ event.name }}"},subTemplateGroupName:"CONFIRMATION",templateCode:"EVENT_REGISTRATION.CONFIRMATION.registration",templateGroupName:"EVENT_REGISTRATION",tenantCode:"example"});exports.ABSTRACT_ACKNOWLEDGEMENT_TEMPLATE=Pr;exports.ABSTRACT_RECIPIENT_TYPE=x;exports.APVRS_FOOTER_V1=Gt;exports.APVRS_HEADER_V1=Kt;exports.AUTHOR_LIST_V1=Lt;exports.AUTHOR_LIST_V2=Pt;exports.BLOCK_ATTRIBUTE=U;exports.BLOCK_PARAMS_ATTRIBUTE=fe;exports.BLOCK_PARAMS_ROOT=V;exports.CONGRESS_CONTEXTS=zt;exports.CONGRESS_FOOTER_V1=qt;exports.CONGRESS_LAYOUTS=Rr;exports.CONGRESS_TEMPLATE_FUNCTIONS=Ft;exports.DataContext=it;exports.INVOICE_LINES_TABLE_V1=Nt;exports.INVOICE_LINES_TABLE_V2=St;exports.LAYOUT_ATTRIBUTE=ze;exports.LifecycleTemplateBlock=Ee;exports.LifecycleTemplateLayout=xe;exports.RECEIPT_TEMPLATE=Lr;exports.REGISTRATION_CONFIRMATION_TEMPLATE=Ir;exports.SAMPLE_ABSTRACTS=xt;exports.SAMPLE_EVENT=Se;exports.SAMPLE_INVOICES=Mt;exports.SAMPLE_PEOPLE=Le;exports.SAMPLE_REGISTRATIONS=$t;exports.SUPPORTED_TEMPLATE_SYNTAX_VERSIONS=$e;exports.TEMPLATE_BLOCK_ACTION_CODE=rr;exports.TEMPLATE_BLOCK_PARAM_TYPE=N;exports.TEMPLATE_BLOCK_STATE_CODE=k;exports.TEMPLATE_BUILTIN_FILTERS=Ge;exports.TEMPLATE_CONTENT_TYPE=M;exports.TEMPLATE_EMAIL_KIND=Re;exports.TEMPLATE_EVALUATION_LIMITS=gt;exports.TEMPLATE_FIELD_KIND=B;exports.TEMPLATE_FIELD_TYPE=P;exports.TEMPLATE_FRAGMENT_TAGS=me;exports.TEMPLATE_FUNCTION_ARG_TYPE=$;exports.TEMPLATE_ISSUE_CODE=b;exports.TEMPLATE_ISSUE_SEVERITY=K;exports.TEMPLATE_KIND_CODE=Ce;exports.TEMPLATE_LAYOUT_ACTION_CODE=lr;exports.TEMPLATE_LAYOUT_STATE_CODE=ce;exports.TEMPLATE_SYNTAX_VERSION=Oe;exports.TEMPLATE_TAGS=qe;exports.Template=mt;exports.TemplateBlock=_t;exports.TemplateEmail=Ot;exports.TemplateEmailCongress=Sr;exports.TemplateLayout=cr;exports.TemplateProjection=ke;exports.TemplateRenderError=w;exports.TemplateSyntaxError=Y;exports.abstractContext=Ut;exports.abstractProjection=jt;exports.authorProjection=vt;exports.checkBlockFragment=ht;exports.checkTemplate=Xn;exports.checkTemplateContent=Jn;exports.checkTemplateLayoutContent=Et;exports.clearCustomFunctions=ln;exports.contextCodeForTemplateGroup=_e;exports.contextForTemplateGroup=Ar;exports.createBlockElement=gn;exports.createCongressBlocks=_r;exports.createTemplateRenderer=Ct;exports.defineDataContext=Z;exports.defineTemplateProjection=v;exports.describeTemplateFilter=Fn;exports.describeTemplateFunctions=te;exports.describeTemplateKind=Mn;exports.eventProjection=re;exports.eventRegistrationContext=kt;exports.eventRegistrationProjection=Bt;exports.expandTemplateLayouts=at;exports.findBlockRefs=pt;exports.findLayoutCodes=Ae;exports.formatBlockRef=Te;exports.getTemplateFunctionDescriptor=on;exports.getTemplateKind=We;exports.hasTemplateErrors=z;exports.invoiceLineProjection=It;exports.invoiceProjection=wt;exports.layoutContext=Or;exports.layoutElementHtml=Tn;exports.layoutHtmlIssues=Ke;exports.listOf=ge;exports.normalizeBlockParamDefinitions=G;exports.normalizeTemplateMarkup=ct;exports.parseBlockRef=dt;exports.parseTemplateContent=H;exports.paymentResultProjection=Dt;exports.personProjection=ne;exports.receiptContext=Vt;exports.registerCongressTemplateFunctions=Cr;exports.registerTemplateFunction=st;exports.renderTemplateEmail=yr;exports.resolveBlockParams=Ye;exports.resolveTemplateLayout=Fe;exports.toDataContextDescriptor=ee;
62
+ Results`,title:"Outcomes of an example study"}}),Vt=Object.freeze({"ER-1001":{eventRegistrationCode:"ER-1001",hasBadge:!0,roleCodes:["REGISTRANT","DELEGATE"]}}),M=Object.freeze({ALL_AUTHORS:"ALL_AUTHORS",PRESENTER:"PRESENTER",SUBMITTER:"SUBMITTER"}),Ft=ne({contextCode:"ABSTRACT",functionNames:["__format_date","__multiline"],loadData:async({subjectRef:t,recipientType:e})=>{const n=zt[t];return n?{[M.ALL_AUTHORS]:n.authors.map(i=>i.registrationCode),[M.PRESENTER]:n.authors.filter(i=>i.isPresenter).map(i=>i.registrationCode),[M.SUBMITTER]:[n.submitterCode]}[e].map(i=>({recipientRef:i,roots:{abstract:n,event:Le,recipient:Pe[i]}})):[]},name:"Abstract",recipientRules:[{name:"Submitter",recipientType:M.SUBMITTER},{name:"Presenting author",recipientType:M.PRESENTER},{name:"All authors",recipientType:M.ALL_AUTHORS}],roots:{abstract:$t,event:se,recipient:ie},sampleData:{abstract:{abstractCode:"ABS-0001",authors:[{affiliation:"Sample University",capacity:"Presenting author",displayName:"Alex Chan",isPresenter:!0,presentationTopic:"Sample topic"},{affiliation:"Sample Hospital",capacity:"Co-author",displayName:"Sam Wong",isPresenter:!1,presentationTopic:""}],conclusions:"Sample conclusions.",keywords:"sample, keywords",methods:"Sample methods.",presentationType:"Poster",purpose:"Sample purpose.",results:"Sample results.",subspecialty:"Retina",summary:`Line one
63
+ Line two`,title:"Sample abstract title"},event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}},subjectType:"Abstract"}),Kt=ne({contextCode:"EVENT_REGISTRATION",functionNames:["__barcode","__format_date"],loadData:async({subjectRef:t})=>{const e=Vt[t];return e?[{recipientRef:t,roots:{event:Le,eventRegistration:e,recipient:Pe[t]}}]:[]},name:"Event registration",recipientRules:[{name:"Registrant",recipientType:"REGISTRANT"}],roots:{event:se,eventRegistration:Ut,recipient:ie},sampleData:{event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},eventRegistration:{eventRegistrationCode:"ER-0001",hasBadge:!0,roleCodes:["REGISTRANT"]},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}},subjectType:"EventRegistration"}),qt=ne({contextCode:"RECEIPT",functionNames:["__format_date","__format_money"],loadData:async({subjectRef:t})=>{const e=kt[t];return e?[{recipientRef:e.payerCode,roots:{event:Le,invoice:e,paymentResult:e.paymentResult,recipient:Pe[e.payerCode]}}]:[]},name:"Receipt",recipientRules:[{name:"Payer",recipientType:"PAYER"}],roots:{event:se,invoice:Bt,paymentResult:xt,recipient:ie},sampleData:{event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},invoice:{created:Date.UTC(2027,0,5),currencyCode:"HKD",invoiceNumber:"INV-0001",lines:[{amount:2e3,name:"Delegate registration",qty:1,unitPrice:2e3},{amount:1200,name:"Gala dinner",qty:2,unitPrice:600}],revisionNumber:1,total:3200},paymentResult:{paidAmount:3200,paymentDate:Date.UTC(2027,0,6),paymentMethod:"Credit card",paymentRemark:"Paid online",receivedAmount:3200},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}},subjectType:"Invoice"}),Cr=ne({contextCode:"LAYOUT",functionNames:["__format_date"],name:"Layout (every email)",roots:{event:se,recipient:ie},sampleData:{event:{badge:{barcodeFormat:"QR_CODE"},displayDate:"27-30 August 2027",isOnline:!1,location:"Sample Venue",name:"Sample Congress",websiteUrl:"https://congress.example.org"},recipient:{code:"ER-0001",displayName:"Dr Alex Chan",email:"alex.chan@example.org",firstName:"Alex",lastName:"Chan",prefix:"Dr"}}}),Gt=Object.freeze({ABSTRACT:Ft,EVENT_REGISTRATION:Kt,RECEIPT:qt}),Rr=Object.freeze({ABSTRACT:"ABSTRACT",EVENT_REGISTRATION:"EVENT_REGISTRATION",RECEIPT:"RECEIPT",STORE:"RECEIPT"});function Oe(t){return Rr[t]||null}function Nr(t){return Gt[Oe(t)]||null}const Yt=Object.freeze([{description:"Format an amount with a currency code, e.g. HKD 1,200.00.",fn:(t,e)=>{if(t===null)return"";const n=Number(t).toLocaleString("en-US",{maximumFractionDigits:2,minimumFractionDigits:2});return e?`${e} ${n}`:n},label:"money",name:"__format_money",signature:[{types:["number"]},{optional:!0,types:["string"]}]},{description:"Format a timestamp as YYYY-MM-DD (UTC).",fn:t=>t===null?"":new Date(t).toISOString().slice(0,10),label:"date",name:"__format_date",signature:[{types:["number"]}]},{description:"Inline barcode image reference (cid:) for the given value and format.",fn:(t,e)=>t===null?"":`cid:barcode.${e||"QR_CODE"}.${encodeURIComponent(t)}`,label:"barcode",name:"__barcode",signature:[{types:["string"]},{optional:!0,types:["string"]}]},{description:"Escape plain text and keep its line breaks as <br>.",fn:t=>t===null?"":String(t).replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`).replace(/\r?\n/g,"<br>"),label:"lines",name:"__multiline",signature:[{types:["string"]}],trustedHtml:!0}]);function Sr(){const t=new Set(re().map(({name:e})=>e));Yt.forEach(e=>{t.has(e.name)||lt(e)})}const Ht=Object.freeze({description:"Event banner across the top of the email.",eventShortCode:"EXAMPLE2027",html:'<img src="https://congress.2026.apvrs.org/userfile/apvrs/img/apvrs2026/banner.png" alt="{{ event.name }}" width="600" style="display: block; width: 100%; height: auto; border: 0;">',layoutCode:"APVRS_HEADER",name:"APVRS header",tenantCode:"example",version:1}),Wt=Object.freeze({description:"Event name, dates and website below the content.",eventShortCode:"EXAMPLE2027",html:'<p style="margin: 24px 0 0; padding-top: 12px; border-top: 1px solid #dddddd; font-size: 16px; color: #666666;">{{ event.name }} · {{ event.displayDate }} · <a href="{{ event.websiteUrl }}">{{ event.websiteUrl }}</a></p>',layoutCode:"CONGRESS_FOOTER",name:"Congress footer",tenantCode:"example",version:1}),Xt=Object.freeze({description:"APVRS 2026 venue and copyright lines for the footer row of the email frame.",eventShortCode:"EXAMPLE2027",html:'<p style="margin: 0; font-size: 12px; line-height: 1.5; color: #888888;">APVRS 2026 Gold Coast · Gold Coast Convention &amp; Exhibition Centre, Queensland, Australia<br>© 2026 Asia-Pacific Vitreo-Retina Society. All rights reserved.</p>',layoutCode:"APVRS_FOOTER",name:"APVRS footer",tenantCode:"example",version:1}),Lr=Object.freeze([Ht,Wt,Xt]),Pr=["mobileWalletBadgePass","subTemplateGroupName","templateGroupName"];class Ir extends Rt{constructor(e={}){e=e||{},super({...e,contextCode:Oe(e.templateGroupName)||e.contextCode}),this._type=e._type||"TemplateEmailCongress",this.eventShortCode=e.eventShortCode,this.mobileWalletBadgePass=!!e.mobileWalletBadgePass,this.subTemplateGroupName=e.subTemplateGroupName||null,this.templateGroupName=e.templateGroupName}static get _classname(){return"TemplateEmailCongress"}get isValid(){return super.isValid&&!!this.eventShortCode&&!!this.templateGroupName}update(e={}){return Pr.forEach(n=>{Object.hasOwn(e,n)&&(this[n]=n==="mobileWalletBadgePass"?!!e[n]:e[n])}),Object.hasOwn(e,"templateGroupName")&&(this.contextCode=Oe(e.templateGroupName)),super.update(e)}toObject(){return{...super.toObject(),eventShortCode:this.eventShortCode,mobileWalletBadgePass:this.mobileWalletBadgePass,subTemplateGroupName:this.subTemplateGroupName,templateGroupName:this.templateGroupName}}}const wr=Object.freeze({bcc:[{email:"finance@congress.example.org"}],eventShortCode:"EXAMPLE2027",from:{email:"secretariat@congress.example.org",name:"{{ event.name }} Secretariat"},meta:{revision:3},name:"Payment completed",partContent:{html:["<style>.receipt h2 { color: #1f4e79; } .invoice-lines th { background: #cedeea; }</style>",'<div class="receipt">',"<p>Dear {{ recipient.displayName }},</p>","<p>Thank you for your payment for {{ event.name }}.</p>","<h2>Invoice {{ invoice.invoiceNumber }}.{{ invoice.revisionNumber }}</h2>","<p>Invoice date: {{ invoice.created | __format_date }}</p>",`<div data-qw-block="INVOICE_LINES_TABLE@2" data-qw-params='{"columns":["name","qty","amount"]}'></div>`,"<p>Paid {{ paymentResult.paidAmount | __format_money: invoice.currencyCode }} by {{ paymentResult.paymentMethod }} on {{ paymentResult.paymentDate | __format_date }}.</p>","</div>"].join(`
64
+ `),subject:"Payment completed - {{ invoice.invoiceNumber }}",text:"Dear {{ recipient.displayName }}, thank you for your payment of {{ paymentResult.paidAmount | __format_money: invoice.currencyCode }} for {{ event.name }}."},replyTo:{email:"secretariat@congress.example.org"},subTemplateGroupName:"EVENT",templateCode:"RECEIPT.EVENT.paymentCompleted",templateGroupName:"RECEIPT",tenantCode:"example"}),Dr=Object.freeze({eventShortCode:"EXAMPLE2027",meta:{revision:1},name:"Submission acknowledgement",partContent:{html:["<p>Dear {{ recipient.displayName }},</p>",'<p>We have received abstract {{ abstract.abstractCode }} "{{ abstract.title }}" ({{ abstract.presentationType }}).</p>',`<div data-qw-block="AUTHOR_LIST@1" data-qw-params='{"heading":"Authors"}'></div>`,"<p>{{ abstract.summary | __multiline }}</p>","{% if event.isOnline %}<p>The congress is held online.</p>{% else %}<p>Venue: {{ event.location }}</p>{% endif %}"].join(`
65
+ `),subject:"Abstract {{ abstract.abstractCode }} received"},subTemplateGroupName:null,templateCode:"ABSTRACT.submissionAcknowledgement",templateGroupName:"ABSTRACT",tenantCode:"example"}),vr=Object.freeze({eventShortCode:"EXAMPLE2027",meta:{revision:1},mobileWalletBadgePass:!0,name:"Registration confirmation",partContent:{html:["<p>Dear {{ recipient.displayName }},</p>","<p>Your registration code is {{ recipient.code }}.</p>",'{% if event.badge.barcodeFormat == "QR_CODE" %}',` <img alt="Badge" src="{{ recipient.code | __barcode: 'QR_CODE' }}">`,"{% else %}",` <img alt="Badge" src="{{ recipient.code | __barcode: 'PDF417' }}">`,"{% endif %}"].join(`
66
+ `),subject:"Registration confirmed - {{ event.name }}"},subTemplateGroupName:"CONFIRMATION",templateCode:"EVENT_REGISTRATION.CONFIRMATION.registration",templateGroupName:"EVENT_REGISTRATION",tenantCode:"example"});exports.ABSTRACT_ACKNOWLEDGEMENT_TEMPLATE=Dr;exports.ABSTRACT_RECIPIENT_TYPE=M;exports.APVRS_FOOTER_V1=Xt;exports.APVRS_HEADER_V1=Ht;exports.AUTHOR_LIST_V1=Dt;exports.AUTHOR_LIST_V2=vt;exports.BLOCK_ATTRIBUTE=U;exports.BLOCK_PARAMS_ATTRIBUTE=Te;exports.BLOCK_PARAMS_ROOT=z;exports.CONGRESS_CONTEXTS=Gt;exports.CONGRESS_FOOTER_V1=Wt;exports.CONGRESS_LAYOUTS=Lr;exports.CONGRESS_TEMPLATE_FUNCTIONS=Yt;exports.DataContext=ct;exports.INVOICE_LINES_TABLE_V1=It;exports.INVOICE_LINES_TABLE_V2=wt;exports.LAYOUT_ATTRIBUTE=Fe;exports.LifecycleTemplateBlock=be;exports.LifecycleTemplateLayout=$e;exports.RECEIPT_TEMPLATE=wr;exports.REGISTRATION_CONFIRMATION_TEMPLATE=vr;exports.SAMPLE_ABSTRACTS=zt;exports.SAMPLE_EVENT=Le;exports.SAMPLE_INVOICES=kt;exports.SAMPLE_PEOPLE=Pe;exports.SAMPLE_REGISTRATIONS=Vt;exports.SUPPORTED_TEMPLATE_SYNTAX_VERSIONS=Ue;exports.TEMPLATE_BLOCK_ACTION_CODE=or;exports.TEMPLATE_BLOCK_PARAM_TYPE=N;exports.TEMPLATE_BLOCK_STATE_CODE=k;exports.TEMPLATE_BUILTIN_FILTERS=Ye;exports.TEMPLATE_CONTENT_TYPE=x;exports.TEMPLATE_EMAIL_KIND=Ne;exports.TEMPLATE_EVALUATION_LIMITS=Nt;exports.TEMPLATE_FIELD_KIND=w;exports.TEMPLATE_FIELD_TYPE=I;exports.TEMPLATE_FRAGMENT_TAGS=fe;exports.TEMPLATE_FUNCTION_ARG_TYPE=$;exports.TEMPLATE_ISSUE_CODE=y;exports.TEMPLATE_ISSUE_SEVERITY=K;exports.TEMPLATE_KIND_CODE=Re;exports.TEMPLATE_LAYOUT_ACTION_CODE=dr;exports.TEMPLATE_LAYOUT_STATE_CODE=ue;exports.TEMPLATE_SYNTAX_VERSION=ge;exports.TEMPLATE_TAGS=Ge;exports.Template=Et;exports.TemplateBlock=Ct;exports.TemplateEmail=Rt;exports.TemplateEmailCongress=Ir;exports.TemplateLayout=pr;exports.TemplateProjection=ze;exports.TemplateRenderError=D;exports.TemplateSyntaxError=H;exports.abstractContext=Ft;exports.abstractProjection=$t;exports.authorProjection=Mt;exports.checkBlockFragment=_t;exports.checkTemplate=Zn;exports.checkTemplateContent=tr;exports.checkTemplateLayoutContent=Ot;exports.clearCustomFunctions=dn;exports.contextCodeForTemplateGroup=Oe;exports.contextForTemplateGroup=Nr;exports.createBlockElement=Rn;exports.createCongressBlocks=Ar;exports.createTemplateRenderer=Lt;exports.defineDataContext=ne;exports.defineTemplateProjection=j;exports.describeTemplateFilter=Gn;exports.describeTemplateFunctions=re;exports.describeTemplateKind=Un;exports.eventProjection=se;exports.eventRegistrationContext=Kt;exports.eventRegistrationProjection=Ut;exports.expandTemplateLayouts=dt;exports.findBlockRefs=Tt;exports.findLayoutCodes=Ce;exports.formatBlockRef=he;exports.getTemplateFunctionDescriptor=ln;exports.getTemplateKind=Xe;exports.hasTemplateErrors=V;exports.invoiceLineProjection=jt;exports.invoiceProjection=Bt;exports.layoutContext=Cr;exports.layoutElementHtml=bn;exports.layoutHtmlIssues=qe;exports.listOf=Ae;exports.normalizeBlockParamDefinitions=Y;exports.normalizeTemplateMarkup=mt;exports.parseBlockRef=ht;exports.parseTemplateContent=W;exports.paymentResultProjection=xt;exports.personProjection=ie;exports.receiptContext=qt;exports.registerCongressTemplateFunctions=Sr;exports.registerTemplateFunction=lt;exports.renderTemplateEmail=gr;exports.resolveBlockParams=He;exports.resolveTemplateLayout=Ke;exports.toDataContextDescriptor=q;
67
67
  //# sourceMappingURL=p-templates-model.cjs.map