@nova-energy/openamx 0.12.0 → 0.15.0
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 +134 -483
- package/dist/cli.js +5 -5
- package/dist/editor/completion.js +104 -2
- package/dist/editor/highlighting.js +27 -1
- package/dist/editor/refactoring.js +4 -1
- package/dist/editor/sourceRanges.js +2 -1
- package/dist/editor/symbols.js +104 -45
- package/dist/formatter/formatAmx.js +83 -7
- package/dist/parser/parseExpression.js +68 -3
- package/dist/parser/parseStatements.js +147 -0
- package/dist/renderer/diagramBrowserEntry.js +255 -0
- package/dist/renderer/diagramBrowserRuntime.js +2 -0
- package/dist/renderer/diagramHtml.js +47 -0
- package/dist/renderer/narrativeModel.js +36 -11
- package/dist/renderer/renderHtml.js +95 -41
- package/dist/renderer/reportDocx.js +38 -16
- package/dist/renderer/reportPdf.js +122 -35
- package/dist/renderer/reportPreparation.js +97 -23
- package/dist/renderer/reportSequence.js +29 -0
- package/dist/renderer/staticDiagram.js +94 -0
- package/dist/runtime/diagramModel.js +455 -0
- package/dist/runtime/environment.js +6 -0
- package/dist/runtime/evaluateExpression.js +78 -2
- package/dist/runtime/moduleLoader.js +60 -2
- package/dist/runtime/standardLibrary.js +208 -1
- package/dist/runtime/valueSerialization.js +12 -0
- package/dist/typechecker/checkDocument.js +242 -3
- package/package.json +1 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const diagramBrowserRuntime = "(()=>{class w extends Error{code;file;line;column;declarationSource;fieldSource;diagnostics;constructor(e,n){super(e.message);this.name=\"AmxError\",this.code=e.code,this.file=e.file,this.line=e.line,this.column=e.column,this.declarationSource=e.declarationSource,this.fieldSource=e.fieldSource,this.diagnostics=n}}function q(e,n,t={}){return{code:e,message:n,...t}}function B(e){let n=e[0]??q(\"AMX4001\",\"Input validation failed\");throw new w(n,e)}function b(e,n,t,r,i){throw new w({code:e,message:n,file:r,line:t?.line,column:t?.column,declarationSource:i})}function A(e,n,t){throw new w({code:\"AMX1009\",message:e,file:t,line:n?.line,column:n?.column})}function Je(e,n,t){return{code:\"AMX1004\",message:`Undefined identifier '${e}'`,file:t,line:n?.line,column:n?.column}}function ie(e,n,t){let r=Je(e,n,t);throw new w(r)}function oe(e,n){throw new w({code:\"AMX1005\",message:\"Range bounds must be finite integers\",file:n,line:e?.line,column:e?.column})}function Me(e,n){throw new w({code:\"AMX1006\",message:\"For loops require a list or range value\",file:n,line:e?.line,column:e?.column})}function xe(e,n){throw new w({code:\"AMX1007\",message:\"Return is only valid inside an expression-form for loop\",file:n,line:e?.line,column:e?.column})}function D(e,n,t){throw new w({code:\"AMX1008\",message:e,file:t,line:n?.line,column:n?.column})}var ve=new WeakMap;function L(e,n){ve.set(e,n)}function T(e,n){return ve.get(e)??n}class X{store=new Map;recordTypes;enumDeclarations=new Map;enumValues=new Map;functions;bindingTypes=new Map;dimensionRegistry;viewDefinitions=new Map;viewEmissions=[];diagramEmissions=[];immutableValues=new WeakSet;currentDocumentNodeIndex=-1;currentStatementIndex=-1;validationMode=\"aggregate\";constructor(e=new Map,n=new Map,t){this.recordTypes=e,this.functions=n,this.dimensionRegistry=t}createCallFrame(e){let n=new X(this.recordTypes,this.functions,this.dimensionRegistry);n.validationMode=this.validationMode;for(let[t,r]of this.bindingTypes)n.bindingTypes.set(t,r);for(let[t,r]of this.enumDeclarations)n.enumDeclarations.set(t,r);for(let[t,r]of this.enumValues)n.enumValues.set(t,r);for(let[t,r]of Object.entries(e))if(n.set(t,r),this.isImmutable(r))n.markImmutable(r);return n}set(e,n){this.store.set(e,n)}markImmutable(e){let n=(t)=>{if(!t||typeof t!==\"object\"||this.immutableValues.has(t))return;if(this.immutableValues.add(t),Array.isArray(t))t.forEach(n);else Object.values(t).forEach(n)};n(e)}isImmutable(e){return!!e&&typeof e===\"object\"&&this.immutableValues.has(e)}update(e,n,t,r){if(!this.store.has(e))ie(e,t,r);this.store.set(e,n)}delete(e){this.store.delete(e)}get(e,n,t){if(!this.store.has(e))ie(e,n,t);return this.store.get(e)}has(e){return this.store.has(e)}toObject(){let e={};for(let[n,t]of this.store.entries())e[n]=t;return e}clear(){this.store.clear(),this.immutableValues=new WeakSet,this.viewDefinitions.clear(),this.viewEmissions.length=0,this.diagramEmissions.length=0}}function f(e){return!!e&&typeof e===\"object\"&&e.__amxMeasurement===!0&&typeof e.value===\"number\"&&!!e.unit}function Ae(e){return Object.freeze(Object.fromEntries(e))}function ae(e){let n=[...e].filter((i)=>i.exponent!==0).sort((i,o)=>i.identity<o.identity?-1:i.identity>o.identity?1:0),t=n.filter((i)=>i.exponent>0).map((i)=>`${i.name}${i.exponent===1?\"\":` ^ ${i.exponent}`}`),r=n.filter((i)=>i.exponent<0).map((i)=>`${i.name}${i.exponent===-1?\"\":` ^ ${-i.exponent}`}`);return`${t.length?t.join(\" * \"):\"1\"}${r.length?` / ${r.join(\" * \")}`:\"\"}`}function J(e){let n=[{identity:e.identity,name:e.name,exponent:1}];return Object.freeze({scale:e.scale,vector:Ae(e.vector),factors:Object.freeze(n),text:e.name})}function Ke(e,n,t){let r=new Map;for(let i of e.factors)r.set(i.identity,{...i});for(let i of n.factors){let o=r.get(i.identity);r.set(i.identity,{identity:i.identity,name:i.name,exponent:(o?.exponent??0)+i.exponent*t})}return[...r.values()].filter((i)=>i.exponent!==0)}function Qe(e,n,t){let r={...e.vector};for(let[i,o]of Object.entries(n.vector)){let s=(r[i]??0)+o*t;if(s)r[i]=s;else delete r[i]}return r}function Ee(e,n,t=!1){let r=t?-1:1,i=Ke(e,n,r);return Object.freeze({scale:t?e.scale/n.scale:e.scale*n.scale,vector:Object.freeze(Qe(e,n,r)),factors:Object.freeze(i),text:ae(i)})}function se(e,n){let t=e.factors.map((r)=>({...r,exponent:r.exponent*n})).filter((r)=>r.exponent!==0);return Object.freeze({scale:Math.pow(e.scale,n),vector:Object.freeze(Object.fromEntries(Object.entries(e.vector).map(([r,i])=>[r,i*n]).filter(([,r])=>r!==0))),factors:Object.freeze(t),text:ae(t)})}function E(e,n){return Object.freeze({__amxMeasurement:!0,value:e,unit:n})}function Z(e,n){let t=[];for(let[r,i]of[...e].sort(([o],[s])=>o<s?-1:o>s?1:0)){let o=n.baseUnits.get(r);if(!o)throw Error(`No visible canonical base unit for dimension identity ${r}`);t.push({identity:o.identity,name:o.name,exponent:i})}return Object.freeze({scale:1,vector:Ae(e),factors:Object.freeze(t),text:ae(t)})}function Se(e,n){let t=new Map;for(let[u,l]of Object.entries(e.unit.vector)){if(l%2!==0)throw Error(\"sqrt requires integral measurement dimension exponents\");t.set(u,l/2)}let r=e.value*e.unit.scale,i=Math.sqrt(r);if(!Number.isFinite(i))return E(i,Z(t,n));let o=Math.sqrt(e.unit.scale),s=[...n.units.values()].find((u)=>u.scale===o&&u.vector.size===t.size&&[...t].every(([l,c])=>u.vector.get(l)===c));if(s)return E(i/s.scale,J(s));let a=Z(t,n);return E(i,a)}function K(e,n,t,r){if(!Array.isArray(e)){let i=t?` at line ${t.line}`:\"\";throw new w({code:\"AMX2001\",message:`${n} expects a list${i}`,file:r,line:t?.line,column:t?.column})}return e}function N(e,n,t,r){if(typeof e===\"number\")return e;if(typeof e===\"boolean\")return e?1:0;if(typeof e===\"string\"){let o=Number(e);if(!Number.isNaN(o))return o}let i=t?` at line ${t.line}`:\"\";throw new w({code:\"AMX2002\",message:`${n} requires a numeric value${i}`,file:r,line:t?.line,column:t?.column})}function V(e,n,t,r,i){if(e.length!==n){let o=r?` at line ${r.line}`:\"\";throw new w({code:\"AMX2003\",message:`${t} expects ${n} argument(s), got ${e.length}${o}`,file:i,line:r?.line,column:r?.column})}}function en(e,n,t,r,i){if(e.length<n){let o=r?` at line ${r.line}`:\"\";throw new w({code:\"AMX2003\",message:`${t} expects at least ${n} argument(s), got ${e.length}${o}`,file:i,line:r?.line,column:r?.column})}}var Te={sin:{evaluate:Math.sin,accepts:Number.isFinite},cos:{evaluate:Math.cos,accepts:Number.isFinite},tan:{evaluate:Math.tan,accepts:Number.isFinite},asin:{evaluate:Math.asin,accepts:(e)=>Number.isFinite(e)&&e>=-1&&e<=1},acos:{evaluate:Math.acos,accepts:(e)=>Number.isFinite(e)&&e>=-1&&e<=1},atan:{evaluate:Math.atan,accepts:Number.isFinite},sinh:{evaluate:Math.sinh,accepts:Number.isFinite},cosh:{evaluate:Math.cosh,accepts:Number.isFinite},tanh:{evaluate:Math.tanh,accepts:Number.isFinite},asinh:{evaluate:Math.asinh,accepts:Number.isFinite},acosh:{evaluate:Math.acosh,accepts:(e)=>Number.isFinite(e)&&e>=1},atanh:{evaluate:Math.atanh,accepts:(e)=>Number.isFinite(e)&&e>-1&&e<1},ln:{evaluate:Math.log,accepts:(e)=>Number.isFinite(e)&&e>0},log:{evaluate:Math.log10,accepts:(e)=>Number.isFinite(e)&&e>0},exp:{evaluate:Math.exp,accepts:Number.isFinite}};function $e(e){return Object.hasOwn(Te,e)}function De(e,n,t,r){return new w({code:e,message:n,file:r,line:t?.line,column:t?.column})}function k(e,n,t,r){return new w({code:e,message:n,file:r,line:t?.line,column:t?.column})}function ce(e){if(e===null)return\"null\";if(f(e))return\"Measurement\";if(Array.isArray(e))return\"list\";if(typeof e===\"number\")return\"Number\";if(typeof e===\"string\")return\"String\";if(typeof e===\"boolean\")return\"Boolean\";return typeof e}function Q(e,n,t,r,i,o){if(n.length<t||n.length>r)throw k(\"AMX3004\",`Invalid arity for '${e}'`,i,o)}function Ne(e,n,t,r){if(typeof n!==\"string\")throw k(\"AMX3002\",`${e} requires a String, got ${ce(n)}`,t,r);return n}function ke(e){return e>=9&&e<=13||e===32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288}function nn(e){let n=Array.from(e),t=0,r=n.length;while(t<r&&ke(n[t].codePointAt(0)))t++;while(r>t&&ke(n[r-1].codePointAt(0)))r--;return n.slice(t,r).join(\"\")}function tn(e,n,t){if(typeof e!==\"string\")throw k(\"AMXSL004\",\"Incorrect formatting pattern\",n,t);let r=/^([$€£])?(#,##0|0)(?:\\.(0{1,6}))?(%)?$/.exec(e);if(!r)throw k(\"AMXSL004\",\"Incorrect formatting pattern\",n,t);return{currency:r[1]??\"\",grouped:r[2]===\"#,##0\",precision:r[3]?.length??0,percent:r[4]===\"%\"}}function rn(e,n,t){switch(e){case\"en-US\":return{decimal:\".\",group:\",\"};case\"de-DE\":return{decimal:\",\",group:\".\"};case\"fr-FR\":return{decimal:\",\",group:\" \"};default:throw k(\"AMXSL005\",\"Formatting locale is malformed or unsupported\",n,t)}}function on(e,n){let[t,r]=Math.abs(e).toString().toLowerCase().split(\"e\"),i=r===void 0?0:Number(r),[o,s=\"\"]=t.split(\".\"),a=`${o}${s}`.replace(/^0+(?=\\d)/,\"\"),u=BigInt(a||\"0\"),l=n+i-s.length;if(l>=0)return u*10n**BigInt(l);let c=10n**BigInt(-l),m=u/c,d=u%c;return m+(d*2n>=c?1n:0n)}function an(e,n){return e.replace(/\\B(?=(\\d{3})+(?!\\d))/g,n)}function sn(e,n,t){let r=n.percent?e*100:e,i=r<0,o=10n**BigInt(n.precision),s=on(r,n.precision),a=(s/o).toString(),u=n.precision?`${t.decimal}${(s%o).toString().padStart(n.precision,\"0\")}`:\"\",l=n.grouped?an(a,t.group):a;return`${i?\"-\":\"\"}${n.currency}${l}${u}${n.percent?\"%\":\"\"}`}function _(e,n,t,r,i=[]){let o=(a)=>i[a]??t;if(e===\"len\"){Q(e,n,1,1,t,r);let a=n[0];if(typeof a===\"string\")return Array.from(a).length;if(Array.isArray(a))return a.length;throw k(\"AMX3002\",`len requires a String or list, got ${ce(a)}`,o(0),r)}if(e===\"trim\")return Q(e,n,1,1,t,r),nn(Ne(e,n[0],o(0),r));if(e===\"left\"||e===\"right\"){Q(e,n,1,2,t,r);let a=Array.from(Ne(e,n[0],o(0),r)),u=n.length===1?1:n[1];if(typeof u!==\"number\"||!Number.isFinite(u)||!Number.isInteger(u)||u<0)throw k(\"AMXSL003\",\"Invalid text slice count\",o(1),r);let l=Math.min(u,a.length);return e===\"left\"?a.slice(0,l).join(\"\"):a.slice(a.length-l).join(\"\")}if(e===\"format\"){Q(e,n,2,3,t,r);let a=n[0],u=o(0);if(typeof a!==\"number\"&&!f(a))throw k(\"AMX3002\",`format expects a Number or Measurement, got ${ce(a)}`,u,r);let l=f(a)?a.value:a;if(!Number.isFinite(l))throw k(\"AMXSL006\",\"Input is non-finite\",u,r);let c=tn(n[1],o(1),r),m=rn(n.length===3?n[2]:\"en-US\",o(2),r);if(c.percent&&!Number.isFinite(l*100))throw k(\"AMXSL006\",\"Input is non-finite\",u,r);let d=sn(l,c,m);return f(a)?`${d} ${a.unit.text}`:d}let s=Te[e];if(s){if(n.length!==1)throw new w({code:\"AMX3004\",message:`Invalid arity for '${e}'`,file:r,line:t?.line,column:t?.column});let a=n[0];if(typeof a!==\"number\"){let l=a===null?\"null\":Array.isArray(a)?\"list\":typeof a===\"object\"?\"Measurement\":typeof a===\"string\"?\"String\":typeof a===\"boolean\"?\"Boolean\":typeof a;throw new w({code:\"AMX3002\",message:`Expected Number or dimensionless Measurement, got ${l}`,file:r,line:t?.line,column:t?.column})}if(!s.accepts(a))throw De(\"AMXSL001\",\"Invalid input for mathematical function\",t,r);let u=s.evaluate(a);if(!Number.isFinite(u))throw De(\"AMXSL002\",\"Function evaluation results in infinite result\",t,r);return u}switch(e){case\"sum\":return V(n,1,\"sum\",t,r),K(n[0],\"sum\",t,r).reduce((l,c)=>l+N(c,\"sum element\",t,r),0);case\"min\":{V(n,1,\"min\",t,r);let u=K(n[0],\"min\",t,r);if(u.length===0){let l=t?` at line ${t.line}`:\"\";throw new w({code:\"AMX2004\",message:`min of empty list${l}`,file:r,line:t?.line,column:t?.column})}return u.reduce((l,c)=>Math.min(l,N(c,\"min element\",t,r)),Number.POSITIVE_INFINITY)}case\"max\":{V(n,1,\"max\",t,r);let u=K(n[0],\"max\",t,r);if(u.length===0){let l=t?` at line ${t.line}`:\"\";throw new w({code:\"AMX2004\",message:`max of empty list${l}`,file:r,line:t?.line,column:t?.column})}return u.reduce((l,c)=>Math.max(l,N(c,\"max element\",t,r)),Number.NEGATIVE_INFINITY)}case\"mean\":{V(n,1,\"mean\",t,r);let u=K(n[0],\"mean\",t,r);if(u.length===0){let c=t?` at line ${t.line}`:\"\";throw new w({code:\"AMX2004\",message:`mean of empty list${c}`,file:r,line:t?.line,column:t?.column})}return u.reduce((c,m)=>c+N(m,\"mean element\",t,r),0)/u.length}case\"round\":{en(n,1,\"round\",t,r);let u=N(n[0],\"round value\",t,r),l=n.length>1?N(n[1],\"round digits\",t,r):0,c=Math.pow(10,Math.trunc(l));return Math.round(u*c)/c}case\"abs\":{V(n,1,\"abs\",t,r);let u=N(n[0],\"abs value\",t,r);return Math.abs(u)}case\"sqrt\":{V(n,1,\"sqrt\",t,r);let u=N(n[0],\"sqrt value\",t,r);if(u<0){let l=t?` at line ${t.line}`:\"\";throw new w({code:\"AMX2005\",message:`sqrt of negative value${l}`,file:r,line:t?.line,column:t?.column})}return Math.sqrt(u)}case\"pow\":{V(n,2,\"pow\",t,r);let u=N(n[0],\"pow base\",t,r),l=N(n[1],\"pow exponent\",t,r);return Math.pow(u,l)}default:let a=t?` at line ${t.line}`:\"\";throw new w({code:\"AMX2000\",message:`Unknown function '${e}'${a}`,file:r,line:t?.line,column:t?.column})}}function j(e,n,t,r,i,o){let s=[],a=(l,c,m,d,p)=>{let y=q(\"AMX4003\",l,{file:i,line:r?.line,column:r?.column,dataPath:d,expected:ue(c),actual:me(m),fieldSource:p});if(s.push(y),t.validationMode===\"fail-fast\")B([y])},u=(l,c,m,d)=>{if(c.kind===\"null\"){if(l!==null)a(\"Expected null\",c,l,m,d);return}if(c.kind===\"nullable\"){if(l!==null)u(l,c.element,m,d);return}if(c.kind===\"list\"){if(!Array.isArray(l)){a(\"Expected a list value\",c,l,m,d);return}l.forEach((h,S)=>u(h,c.element,`${m}[${S}]`,d));return}if(c.kind===\"measurement\"){if(!f(l)){a(\"Expected a measurement value\",c,l,m,d);return}let h=l.unit.vector;if(Object.keys(h).length!==c.vector.size||[...c.vector].some(([S,R])=>h[S]!==R))a(\"Measurement dimension does not match the declared dimension\",c,l,m,d);if(!Number.isFinite(l.value)||!Number.isFinite(l.value*l.unit.scale))a(\"Measurement value must be finite\",c,l,m,d);return}if(c.kind!==\"named\")return;if(c.name===\"Number\"){if(typeof l!==\"number\"||!Number.isFinite(l))a(\"Expected a finite Number value\",c,l,m,d);return}if(c.name===\"String\"||c.name===\"DateTime\"){if(typeof l!==\"string\")a(`Expected a ${c.name} value`,c,l,m,d);else if(c.name===\"DateTime\"&&!Fe(l))a(\"Invalid RFC 3339 DateTime value\",c,l,m,d);return}if(c.name===\"Boolean\"){if(typeof l!==\"boolean\")a(\"Expected a Boolean value\",c,l,m,d);return}let p=t.recordTypes.get(c.name);if(!p||typeof l!==\"object\"||l===null||Array.isArray(l)){a(`Expected a ${c.name} record`,c,l,m,d);return}let y=l,M=new Set(p.fields.map((h)=>h.name));for(let h of p.fields){let S=T(h,t.dimensionRegistry);if(!Object.prototype.hasOwnProperty.call(y,h.name))a(`Missing computed field '${h.name}'`,P(h.annotation,S),\"missing\",`${m}.${h.name}`,h.source);else u(y[h.name],P(h.annotation,S),`${m}.${h.name}`,h.source)}for(let h of Object.keys(y).filter((S)=>!M.has(S)).sort())a(`Unknown computed field '${h}'`,c,y[h],`${m}.${h}`,d)};if(u(e,n,o),s.length)B(s)}function cn(e,n,t){if(!e.defaultExpression)return null;let r=n.dimensionRegistry;n.dimensionRegistry=T(e,r);try{return g(e.defaultExpression,n,t)}finally{n.dimensionRegistry=r}}function P(e,n){let t=n instanceof X?n.dimensionRegistry:n;if(e.type===\"namedType\"){let i=t?.dimensions.get(e.name);return i?{kind:\"measurement\",vector:i.vector}:{kind:\"named\",name:e.name}}let r=P(e.element,t);return e.type===\"listType\"?{kind:\"list\",element:r}:{kind:\"nullable\",element:r}}function ue(e){if(e.kind===\"named\")return e.name;if(e.kind===\"measurement\")return\"measurement\";if(e.kind===\"null\")return\"null\";return e.kind===\"list\"?`${ue(e.element)}[]`:`${ue(e.element)}?`}function me(e){if(typeof e===\"number\"&&!Number.isFinite(e))return String(e);let n;try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}return n.replace(/[\\x00-\\x1f\\x7f]/g,(t)=>`\\\\u${t.charCodeAt(0).toString(16).padStart(4,\"0\")}`).slice(0,160)}function W(e,n){return Object.keys(e.unit.vector).length===n.size&&[...n].every(([t,r])=>e.unit.vector[t]===r)}function Fe(e){let n=e.match(/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,9})?(Z|[+-]\\d{2}:\\d{2})$/);if(!n)return!1;let[,t,r,i,o,s,a,u]=n,l=new Date(0);return l.setUTCFullYear(+t,+r-1,+i),l.getUTCFullYear()===+t&&l.getUTCMonth()===+r-1&&l.getUTCDate()===+i&&+o<=23&&+s<=59&&+a<=59&&(u===\"Z\"||+u.slice(1,3)<=23&&+u.slice(4)<=59)}function ee(e,n,t,r,i=t.dimensionRegistry){if(n.type===\"nullableType\")return e===null||ee(e,n.element,t,r,i);if(n.type===\"listType\")return Array.isArray(e)&&e.every((l)=>ee(l,n.element,t,r,i));let o=n.name,s=i?.dimensions.get(o);if(s)return f(e)&&W(e,s.vector);if(o===\"Number\")return typeof e===\"number\";if(o===\"String\")return typeof e===\"string\";if(o===\"Boolean\")return typeof e===\"boolean\";if(o===\"DateTime\")return typeof e===\"string\"&&Fe(e);let a=t.enumDeclarations.get(o);if(a){if(typeof e!==\"number\"&&typeof e!==\"string\")return!1;if(!a.resolvedValues)throw Error(`Enum '${o}' has not been resolved`);return a.resolvedValues.includes(e)}let u=t.recordTypes.get(o);if(u){if(typeof e!==\"object\"||e===null||Array.isArray(e)||f(e))return!1;let l=e;return u.fields.every((c)=>{if(!Object.prototype.hasOwnProperty.call(l,c.name))return c.optional;return ee(l[c.name],c.annotation,t,r,T(c,i))})}return b(\"AMX3001\",`Unknown type '${o}'`,n.source,r)}function g(e,n,t){switch(e.type){case\"nullLiteral\":return null;case\"recordConstructor\":{let r=n.recordTypes.get(e.name);if(!r)throw Error(`Unknown record type '${e.name}'`);let i=new Map(e.fields.map((s)=>[s.name,g(s.expression,n,t)])),o={};for(let s of r.fields)o[s.name]=i.has(s.name)?i.get(s.name):s.defaultExpression?cn(s,n,t):null;return j(o,{kind:\"named\",name:e.name},n,e.source,t,`record ${e.name}`),o}case\"fieldAccess\":{if(e.receiver.type===\"identifier\"){let r=n.enumValues.get(e.receiver.name);if(r)return r[e.field]}return g(e.receiver,n,t)[e.field]}case\"listAccess\":return gn(e,n,t);case\"numberLiteral\":return e.value;case\"stringLiteral\":return e.value;case\"stringInterpolation\":return e.parts.map((r)=>{if(typeof r===\"string\")return r;let i=g(r,n,t);if(i===null)return\"null\";if(typeof i===\"string\"||typeof i===\"number\")return String(i);if(typeof i===\"boolean\")return i?\"true\":\"false\";if(f(i))return`${String(i.value)} ${i.unit.text}`;return b(\"AMX3007\",\"Only String, Number, Boolean, measurement, and null values can be interpolated\",r.source,t)}).join(\"\");case\"booleanLiteral\":return e.value;case\"identifier\":if(e.name===\"PI\")return Math.PI;if(e.name===\"E\")return Math.E;return n.get(e.name,e.source,t);case\"measurementAttachment\":{let r=g(e.value,n,t),i=n.dimensionRegistry?.units.get(e.unit);if(!i)return b(\"AMX3008\",`Unknown or invisible unit '${e.unit}'`,e.unitSource??e.source,t);if(typeof r!==\"number\")return b(\"AMX3007\",\"Unit attachment requires a Number expression\",e.source,t);let o=E(r,J(i));if(!Number.isFinite(o.value*o.unit.scale))A(\"Measurement physical value must be finite\",e.source,t);return o}case\"measurementConversion\":{let r=g(e.value,n,t),i=n.dimensionRegistry?.units.get(e.unit);if(!i)return b(\"AMX3008\",`Unknown or invisible unit '${e.unit}'`,e.unitSource??e.source,t);if(!f(r)||!W(r,i.vector))return b(\"AMX3007\",`Cannot convert value to unit '${e.unit}'`,e.source,t);let o=r.value*r.unit.scale/i.scale;if(!Number.isFinite(o))A(\"Converted measurement value must be finite\",e.source,t);return E(o,J(i))}case\"binaryExpression\":return ln(e,n,t);case\"typeTestExpression\":return ee(g(e.value,n,t),e.target,n,t);case\"unaryExpression\":return mn(e,n,t);case\"conditionalExpression\":return dn(e,n,t);case\"bracedIfExpression\":return fn(e,n,t);case\"listLiteral\":return pn(e,n,t);case\"functionCall\":return yn(e,n,t);case\"rangeExpression\":return An(e,n,t);case\"forExpression\":return Sn(e,n,t);case\"matchExpression\":return un(e,n,t);default:throw Error(`Unsupported expression node type: ${e}`)}}function un(e,n,t){let r=g(e.expression,n,t);for(let i of e.cases)if(r===i.value.value)return g(i.expression,n,t);return g(e.defaultExpression,n,t)}function ln(e,n,t){let r=g(e.left,n,t),i=g(e.right,n,t),o=e.operatorSource??e.source;switch(e.operator){case\"+\":case\"-\":{if(f(r)||f(i)){if(!f(r)||!f(i)||!W(r,new Map(Object.entries(i.unit.vector))))return b(\"AMX3007\",\"Addition and subtraction require compatible measurements\",o,t);let u=r.value*r.unit.scale,l=i.value*i.unit.scale,c=e.operator===\"+\"?u+l:u-l,m=c/r.unit.scale;if(!Number.isFinite(m)||!Number.isFinite(c))A(\"Measurement arithmetic result must be finite\",o,t);return E(m,r.unit)}let s=x(r,e.left),a=x(i,e.right);return e.operator===\"+\"?s+a:s-a}case\"*\":case\"/\":{if(f(r)||f(i)){let u={scale:1,vector:{},factors:[],text:\"1\"},l=f(r)?r:void 0,c=f(i)?i:void 0,m=l?l.value:x(r,e.left),d=c?c.value:x(i,e.right),p=l?.unit??u,y=c?.unit??u,M=d*y.scale;if(e.operator===\"/\"&&M===0)A(\"Measurement division by zero\",o,t);let h=Ee(p,y,e.operator===\"/\"),S=e.operator===\"/\"?m*p.scale/M:m*p.scale*d*y.scale;if(h.vector&&Object.keys(h.vector).length===0){if(!Number.isFinite(S))A(\"Measurement arithmetic result must be finite\",o,t);return S}let R=e.operator===\"/\"?m/d:m*d;if(!Number.isFinite(h.scale)||h.scale<=0||!Number.isFinite(R)||!Number.isFinite(S))A(\"Measurement arithmetic result must be finite\",o,t);return E(R,h)}let s=x(r,e.left),a=x(i,e.right);return e.operator===\"*\"?s*a:s/a}case\"%\":{let s=x(r,e.left),a=x(i,e.right);return s%a}case\"^\":{if(f(r)){let u=x(i,e.right);if(!Number.isSafeInteger(u))return b(\"AMX3007\",\"A dimensional power exponent must be an integer literal\",e.right.source,t);if(r.value===0&&u<0)A(\"Zero measurement cannot be raised to a negative power\",o,t);let l=se(r.unit,u),c=Math.pow(r.value,u);if(!Number.isFinite(c)||!Number.isFinite(l.scale))A(\"Measurement power result must be finite\",o,t);if(Object.keys(l.vector).length===0)return c*l.scale;return E(c,l)}let s=x(r,e.left),a=x(i,e.right);return Math.pow(s,a)}case\"==\":if(f(r)&&f(i))return W(r,new Map(Object.entries(i.unit.vector)))&&r.value*r.unit.scale===i.value*i.unit.scale;return r===i;case\"!=\":if(f(r)&&f(i))return!W(r,new Map(Object.entries(i.unit.vector)))||r.value*r.unit.scale!==i.value*i.unit.scale;return r!==i;case\">\":if(f(r)&&f(i))return r.value*r.unit.scale>i.value*i.unit.scale;return x(r,e.left)>x(i,e.right);case\">=\":if(f(r)&&f(i))return r.value*r.unit.scale>=i.value*i.unit.scale;return x(r,e.left)>=x(i,e.right);case\"<\":if(f(r)&&f(i))return r.value*r.unit.scale<i.value*i.unit.scale;return x(r,e.left)<x(i,e.right);case\"<=\":if(f(r)&&f(i))return r.value*r.unit.scale<=i.value*i.unit.scale;return x(r,e.left)<=x(i,e.right);case\"and\":return I(r)&&I(i);case\"or\":return I(r)||I(i);default:throw Error(`Unsupported binary operator: ${e.operator}`)}}function mn(e,n,t){let r=g(e.argument,n,t);if(e.operator===\"-\"){if(f(r))return E(-r.value,r.unit);return-x(r,e.argument)}if(e.operator===\"not\")return!I(r);throw Error(`Unsupported unary operator: ${e.operator}`)}function dn(e,n,t){let r=g(e.test,n,t);return I(r)?g(e.consequent,n,t):g(e.alternate,n,t)}class de{value;constructor(e){this.value=e}}class fe{value;constructor(e){this.value=e}}var Re=new WeakMap,Le=new WeakMap;function Xe(e,n,t){e.set(n,(e.get(n)??0)+1);try{return t()}finally{let r=e.get(n)-1;if(r)e.set(n,r);else e.delete(n)}}function Ve(e,n,t){let r=new Set(Object.keys(n.toObject()));try{je(e,n,t)}finally{for(let i of Object.keys(n.toObject()))if(!r.has(i))n.delete(i)}}function fn(e,n,t){let r=I(g(e.test,n,t))?e.consequent:e.alternate,i=r===e.consequent?e.consequentSource:e.alternateSource;try{Xe(Re,n,()=>Ve(r,n,t))}catch(o){if(o instanceof de)return o.value;throw o}return b(\"AMX3021\",\"Every possible path in an if expression must return a value\",i??e.source,t)}function pn(e,n,t){return e.elements.map((r)=>g(r,n,t))}function gn(e,n,t){let r=g(e.receiver,n,t),i=g(e.index,n,t);if(!Array.isArray(r))D(\"List access requires a list value\",e.source,t);if(typeof i!==\"number\"||!Number.isFinite(i)||!Number.isInteger(i)||i<1)D(`List index must be a positive integer; got ${me(i)}`,e.index.source??e.source,t);if(i>r.length)D(`List index ${i} is out of bounds for length ${r.length}; expected 1..${r.length}`,e.index.source??e.source,t);return r[i-1]}function ne(e,n){if(e.type===\"binaryExpression\")return ne(e.left,n)??e.operatorSource??e.source??n;if(e.type===\"unaryExpression\"){let t=ne(e.argument,n);if(t)return{line:t.line,column:Math.max(1,t.column-(e.operator===\"not\"?3:1))}}if(e.type===\"measurementAttachment\"||e.type===\"measurementConversion\")return ne(e.value,n)??e.source??n;return e.source??n}function yn(e,n,t){let r=e.arguments.map((s)=>g(s,n,t)),i=n.functions.get(e.callee);if(i){let s=T(i,n.dimensionRegistry),a={};i.parameters.forEach((c,m)=>{j(r[m],P(c.annotation,s),n,e.arguments[m]?.source??e.source,t,`function ${e.callee}.${c.name}`),a[c.name]=r[m]});let u=n.createCallFrame(a);u.dimensionRegistry=s,i.parameters.forEach((c)=>{u.bindingTypes.set(c.name,P(c.annotation,s))});let l=g(i.body,u,t);return j(l,P(i.returnType,s),n,e.source,t,`function ${e.callee} return`),l}let o=r[0];if([\"sum\",\"mean\",\"min\",\"max\"].includes(e.callee)&&Array.isArray(o)&&(o.length>0&&f(o[0]))){let s=o,a=s[0];for(let c of s){if(!W(a,new Map(Object.entries(c.unit.vector))))return b(\"AMX3007\",`${e.callee} requires compatible measurement dimensions`,e.source,t);if(Array.isArray(o)&&o.length>0&&typeof o[0]===\"number\"&&[\"sum\",\"mean\",\"min\",\"max\"].includes(e.callee))return _(e.callee,r,e.source,t)}if(e.callee===\"min\"||e.callee===\"max\"){if(!s.length)return _(e.callee,r,e.source,t);return s.reduce((c,m)=>(e.callee===\"min\"?m.value*m.unit.scale<c.value*c.unit.scale:m.value*m.unit.scale>c.value*c.unit.scale)?m:c)}let u=s.reduce((c,m)=>c+m.value*m.unit.scale,0),l=(e.callee===\"mean\"?u/s.length:u)/a.unit.scale;if(!Number.isFinite(l))A(`${e.callee} result must be finite`,e.source,t);return E(l,a.unit)}if(e.callee===\"sum\"&&Array.isArray(o)&&o.length===0&&e.arguments[0]?.type===\"identifier\"){let s=n.bindingTypes.get(e.arguments[0].name);if(s?.kind===\"list\"&&s.element.kind===\"measurement\"&&n.dimensionRegistry)return E(0,Z(s.element.vector,n.dimensionRegistry))}if(f(r[0])){let s=r[0];if($e(e.callee)){if(Object.keys(s.unit.vector).length!==0)return b(\"AMX3007\",`'${e.callee}' requires a Number or dimensionless Measurement`,e.arguments[0]?.source??e.source,t);return _(e.callee,[s.value*s.unit.scale],e.source,t)}switch(e.callee){case\"abs\":return E(Math.abs(s.value),s.unit);case\"round\":{let a=r.length>1?x(r[1],e.arguments[1]):0,u=Math.pow(10,Math.trunc(a)),l=Math.round(s.value*u)/u;if(!Number.isFinite(l))A(\"round result must be finite\",e.source,t);return E(l,s.unit)}case\"sqrt\":{if(s.value*s.unit.scale<0)A(\"sqrt of a negative measurement value\",e.source,t);if(!n.dimensionRegistry)throw Error(\"Measurement registry is unavailable during sqrt evaluation\");try{let u=Se(s,n.dimensionRegistry);if(!Number.isFinite(u.value)||!Number.isFinite(u.unit.scale))A(\"sqrt result must be finite\",e.source,t);if(Object.keys(u.unit.vector).length===0)return u.value*u.unit.scale;return u}catch(u){if(u instanceof Error&&u.message.startsWith(\"sqrt requires\"))return b(\"AMX3007\",u.message,e.source,t);throw u}}case\"pow\":{let a=x(r[1],e.arguments[1]);if(!Number.isSafeInteger(a))return b(\"AMX3007\",\"A dimensional pow exponent must be an integer literal\",e.arguments[1]?.source,t);if(s.value===0&&a<0)A(\"Zero measurement cannot be raised to a negative power\",e.source,t);let u=se(s.unit,a),l=Math.pow(s.value,a);if(!Number.isFinite(l)||!Number.isFinite(u.scale))A(\"pow result must be finite\",e.source,t);if(!Object.keys(u.vector).length)return l*u.scale;return E(l,u)}}}return _(e.callee,r,e.source,t,e.arguments.map((s)=>ne(s,e.source)))}function x(e,n){if(typeof e===\"number\")return e;if(typeof e===\"boolean\")return e?1:0;if(typeof e===\"string\"){let i=Number(e);if(!Number.isNaN(i))return i}let t=n?.source,r=t?` at line ${t.line}`:\"\";throw Error(`Cannot convert value to number${r}`)}function I(e){if(typeof e===\"boolean\")return e;if(typeof e===\"number\")return e!==0;if(typeof e===\"string\")return e.length>0;if(Array.isArray(e))return e.length>0;if(e&&typeof e===\"object\")return!0;return!1}function je(e,n,t){let r=n.currentStatementIndex;try{for(let i=0;i<e.length;i++)n.currentStatementIndex=i,ze(e[i],n,t)}finally{n.currentStatementIndex=r}}function H(e){if(f(e))return`${e.value} ${e.unit.text}`;if(Array.isArray(e))return Object.freeze(e.map(H));if(e&&typeof e===\"object\"){let n={};for(let[t,r]of Object.entries(e))n[t]=H(r);return Object.freeze(n)}return e}function bn(e,n,t,r){let i=n.viewDefinitions.get(e);if(!i)return b(\"AMX3001\",`Unknown visualization '${e}'`,r,t);let o=n.get(i.binding,i.bindingSource,t);if(!Array.isArray(o)){let m=q(\"AMX4003\",`Visualization '${e}' requires a list value`,{file:t,line:i.bindingSource?.line,column:i.bindingSource?.column,dataPath:`visualization ${e}`,expected:\"list\",actual:Array.isArray(o)?\"list\":typeof o});B([m])}let s,a,u,l;if(i.type===\"chartDeclaration\"){let m=i.options.find((p)=>p.type===\"chartFieldOption\"&&p.role===\"labels\");if(m?.type===\"chartFieldOption\"){let p=n.get(m.field,m.fieldSource,t);if(!Array.isArray(p)||!p.every((y)=>typeof y===\"string\")){let y=q(\"AMX4003\",`Chart '${e}' labels must be a String[] value`,{file:t,line:m.source?.line,column:m.source?.column,dataPath:`visualization ${e}.labels`,expected:\"String[]\",actual:Array.isArray(p)?\"invalid list value\":typeof p});B([y])}if(p.length!==o.length){let y=q(\"AMX4003\",`Chart '${e}' has ${o.length} values but ${p.length} labels`,{file:t,line:m.source?.line,column:m.source?.column,dataPath:`visualization ${e}.labels`,expected:`${o.length} labels`,actual:`${p.length} labels`});B([y])}s=H(p)}let d=hn(o,i,e,t);l=d.data,a=d.headings,u=d.measurementDescriptors}else l=H(o);let c={name:e,data:l,documentNodeIndex:n.currentDocumentNodeIndex,statementIndex:n.currentStatementIndex,source:r};return i.type===\"tableDeclaration\"?Object.freeze({kind:\"table\",...c,declaration:i}):Object.freeze({kind:\"chart\",...c,declaration:i,...s?{labels:s}:{},...a?{headings:a}:{},...u?.length?{measurementDescriptors:u}:{}})}function hn(e,n,t,r){let i=n.kind===\"scatter\",o=i?n.options.filter((c)=>c.type===\"chartFieldOption\"&&(c.role===\"x\"||c.role===\"y\")).map((c)=>({role:c.role,field:c.field,label:c.role,source:c.source})):n.options.filter((c)=>c.type===\"chartSeriesOption\").map((c)=>({role:\"series\",field:c.field,label:c.label,source:c.source})),s=o.map((c)=>{let m=c.field,d=e.map((M)=>M!==null&&typeof M===\"object\"&&!Array.isArray(M)&&!f(M)?M[m??\"\"]:m===void 0?M:void 0),p=d.find((M)=>M!==null&&M!==void 0),y=f(p)?p:void 0;for(let M of d){if(M===null||M===void 0)continue;if(y){if(!f(M)||!Oe(M,y))b(\"AMX3007\",`Chart '${t}' contains incompatible measurement dimensions`,c.source,r,n.source)}else if(f(M))b(\"AMX3007\",`Chart '${t}' mixes measurements with non-measurement values`,c.source,r,n.source)}return y}),a=i?[\"x\",\"y\"].map((c,m)=>s[m]?`${c} (${s[m].unit.text})`:c).concat(\"group\"):[\"label\",...o.flatMap((c,m)=>c.role===\"series\"?[s[m]?`${c.label} (${s[m].unit.text})`:c.label]:[])],u=o.flatMap((c,m)=>{let d=s[m]?.unit;if(!d)return[];return[Object.freeze({role:c.role,...c.field===void 0?{}:{field:c.field},label:c.label,unit:Object.freeze({text:d.text,scale:d.scale,vector:Object.freeze({...d.vector}),factors:Object.freeze(d.factors.map((p)=>Object.freeze({...p})))})})]}),l=e.map((c)=>{if(c!==null&&typeof c===\"object\"&&!Array.isArray(c)&&!f(c)){let m={};for(let[d,p]of Object.entries(c)){let y=o.findIndex((M)=>M.field===d);m[d]=y<0?H(p):Ie(p,s[y],t,o[y]?.source,n,r)}return Object.freeze(m)}return Ie(c,s[0],t,o[0]?.source,n,r)});return{data:Object.freeze(l),headings:Object.freeze(a),measurementDescriptors:Object.freeze(u)}}function Ie(e,n,t,r,i,o){if(e===null||e===void 0)return null;if(!n)return H(e);if(!f(e)||!Oe(e,n))b(\"AMX3007\",`Chart '${t}' contains an incompatible measurement value`,r,o,i.source);let s=e.value*e.unit.scale/n.unit.scale;if(!Number.isFinite(s))b(\"AMX3007\",`Chart '${t}' measurement cannot be normalized to its first display unit`,r,o,i.source);return s}function Oe(e,n){let t=Object.entries(e.unit.vector);return t.length===Object.keys(n.unit.vector).length&&t.every(([r,i])=>n.unit.vector[r]===i)}function ze(e,n,t){switch(e.type){case\"importDeclaration\":case\"exportNamesDeclaration\":return;case\"dimensionDeclaration\":case\"unitDeclaration\":return;case\"inputDeclaration\":return;case\"tableDeclaration\":case\"chartDeclaration\":n.viewDefinitions.set(e.name,e);return;case\"diagramDeclaration\":n.diagramEmissions.push({model:Be(e,n,t,n.currentDocumentNodeIndex,n.currentStatementIndex)});return;case\"showStatement\":n.viewEmissions.push(bn(e.name,n,t,e.source));return;case\"typeDeclaration\":n.recordTypes.set(e.name,e);return;case\"enumDeclaration\":{let r=e.resolvedValues??e.members.map((o,s)=>{if(!o.value)return s+1;if(o.value.type===\"numberLiteral\"||o.value.type===\"stringLiteral\")return o.value.value;return b(\"AMX3020\",\"Only constant values can be assigned to enum members\",o.valueSource??o.value.source,t)}),i={};e.members.forEach((o,s)=>{i[o.name]=r[s]}),n.enumDeclarations.set(e.name,e),n.enumValues.set(e.name,i);return}case\"functionDeclaration\":n.functions.set(e.name,e);return;case\"variableDeclaration\":{let r=g(e.expression,n,t),i=n.bindingTypes.get(e.name);if(i)j(r,i,n,e.source,t,e.name);n.set(e.name,r)}return;case\"assignmentStatement\":{let r=g(e.expression,n,t),i=n.bindingTypes.get(e.name);if(i)j(r,i,n,e.source,t,e.name);n.update(e.name,r,e.source,t);return}case\"compoundAssignmentStatement\":{let r=g({type:\"binaryExpression\",operator:\"+\",left:{type:\"identifier\",name:e.name,source:e.source},right:e.expression,source:e.source},n,t),i=n.bindingTypes.get(e.name);if(i)j(r,i,n,e.source,t,e.name);n.update(e.name,r,e.source,t);return}case\"addStatement\":xn(e,n,t);return;case\"removeStatement\":vn(e,n,t);return;case\"forStatement\":En(e,n,t);return;case\"bracedIfStatement\":wn(e,n,t);return;case\"returnStatement\":if(Re.has(n))throw new de(g(e.expression,n,t));if(Le.has(n))throw new fe(g(e.expression,n,t));xe(e.source,t)}}function wn(e,n,t){let r=I(g(e.test,n,t))?e.consequent:e.alternate;if(r)Ve(r,n,t)}function Ce(e,n,t,r){let i=n.get(e,t,r);if(!Array.isArray(i))D(`Mutation target '${e}' is not a list`,t,r);if(n.isImmutable(i))D(`Cannot mutate immutable imported list '${e}'`,t,r);return i}function Mn(e,n){let t=n.bindingTypes.get(e);return t?.kind===\"list\"?t.element:void 0}function le(e,n,t,r){if(typeof e!==\"number\"||!Number.isFinite(e)||!Number.isInteger(e)||e<1)D(`${n} must be a positive integer; got ${me(e)}`,t,r);return e}function xn(e,n,t){let r=Ce(e.name,n,e.source,t),i=g(e.value,n,t),o=Mn(e.name,n);if(o)j(i,o,n,e.value.source??e.source,t,`${e.name} element`);let s=e.index?le(g(e.index,n,t),\"Insertion position\",e.index.source??e.source,t):r.length+1;if(s>r.length+1)D(`Insertion position ${s} is out of bounds for length ${r.length}; expected 1..${r.length+1}`,e.index?.source??e.source,t);r.splice(s-1,0,i)}function vn(e,n,t){let r=Ce(e.name,n,e.source,t),i=le(g(e.count,n,t),\"Removal count\",e.count.source??e.source,t);if(r.length===0)D(\"Cannot remove from an empty list\",e.source,t);if(!e.index){r.pop();return}let o=le(g(e.index,n,t),\"Removal position\",e.index.source??e.source,t);if(o>r.length)D(`Removal position ${o} is out of bounds for length ${r.length}; expected 1..${r.length}`,e.index.source??e.source,t);if(i>r.length-o+1)D(`Removal interval ${o}..${o+i-1} exceeds list length ${r.length}`,e.count.source??e.source,t);r.splice(o-1,i)}function An(e,n,t){let r=g(e.start,n,t),i=g(e.end,n,t);if(typeof r!==\"number\"||!Number.isFinite(r)||!Number.isInteger(r)||typeof i!==\"number\"||!Number.isFinite(i)||!Number.isInteger(i))oe(e.source,t);let o=[],s=r<=i?1:-1;for(let a=r;s>0?a<=i:a>=i;a+=s)if(o.push(a),a+s===a&&a!==i)oe(e.source,t);return o}function En(e,n,t){let r=Ue(e.iterable,n,t);qe(e.variable,r,n,()=>je(e.body,n,t))}function Sn(e,n,t){let r=Ue(e.iterable,n,t),i=[];return Xe(Le,n,()=>qe(e.variable,r,n,()=>{for(let o of e.body)if(o.type===\"returnStatement\")i.push(g(o.expression,n,t));else try{ze(o,n,t)}catch(s){if(s instanceof fe)i.push(s.value);else throw s}})),i}function Ue(e,n,t){let r=g(e,n,t);if(!Array.isArray(r))Me(e.source,t);return r.slice()}function qe(e,n,t,r){let i=t.has(e),o=i?t.get(e):void 0;try{for(let s of n)t.set(e,s),r()}finally{if(i)t.set(e,o);else t.delete(e)}}var pe=new WeakMap;function z(e){if(!Array.isArray(e)||typeof e[0]!==\"string\")throw Error(\"Invalid serialized diagram value.\");switch(e[0]){case\"undefined\":if(e.length!==1)throw Error(\"Invalid serialized undefined diagram value.\");return;case\"null\":if(e.length!==1)throw Error(\"Invalid serialized null diagram value.\");return null;case\"boolean\":if(e.length!==2||typeof e[1]!==\"boolean\")throw Error(\"Invalid serialized boolean diagram value.\");return e[1];case\"number\":if(e.length!==2)throw Error(\"Invalid serialized number diagram value.\");if(e[1]===\"nan\")return NaN;if(e[1]===\"positive-infinity\")return 1/0;if(e[1]===\"negative-infinity\")return-1/0;if(typeof e[1]!==\"number\")throw Error(\"Invalid serialized number diagram value.\");return e[1];case\"string\":if(e.length!==2||typeof e[1]!==\"string\")throw Error(\"Invalid serialized string diagram value.\");return e[1];case\"array\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized array diagram value.\");return e[1].map(z);case\"object\":{if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized object diagram value.\");let n=e[1].map((t)=>{if(!Array.isArray(t)||t.length!==2||typeof t[0]!==\"string\")throw Error(\"Invalid serialized object entry in diagram value.\");return[t[0],z(t[1])]});return Object.fromEntries(n)}case\"map\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized map diagram value.\");return new Map(e[1].map((n)=>{if(!Array.isArray(n)||n.length!==2)throw Error(\"Invalid serialized map entry in diagram value.\");return[z(n[0]),z(n[1])]}));case\"set\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized set diagram value.\");return new Set(e[1].map(z));default:throw Error(\"Unknown serialized diagram value type.\")}}function G(e,n){if(!(e instanceof Map))throw Error(`Invalid serialized diagram context map '${n}'.`);for(let t of e.keys())if(typeof t!==\"string\")throw Error(`Invalid key in serialized diagram context map '${n}'.`);return e}function Pe(e){let n=JSON.parse(e);if(!n||typeof n!==\"object\"||Array.isArray(n)||!(\"version\"in n)||n.version!==1||!(\"model\"in n)||!(\"context\"in n))throw Error(\"Invalid serialized diagram model envelope.\");let t=z(n.model),r=z(n.context);if(!t||typeof t!==\"object\"||Array.isArray(t)||!r||typeof r!==\"object\"||Array.isArray(r))throw Error(\"Invalid serialized diagram model or evaluation context.\");let i=te(t),o=r;if(!o.values||typeof o.values!==\"object\"||Array.isArray(o.values)||!Array.isArray(o.immutableValues)||!o.declarationRegistries||!Array.isArray(o.declarationRegistries.records)||!Array.isArray(o.declarationRegistries.functions)||o.validationMode!==\"aggregate\"&&o.validationMode!==\"fail-fast\")throw Error(\"Invalid serialized diagram evaluation context.\");let s=G(o.recordTypes,\"recordTypes\"),a=G(o.functions,\"functions\"),u=new X(s,a,o.dimensionRegistry);u.validationMode=o.validationMode;for(let[l,c]of Object.entries(o.values))if(u.set(l,c),o.immutableValues.includes(l))u.markImmutable(c);for(let[l,c]of G(o.enumDeclarations,\"enumDeclarations\"))u.enumDeclarations.set(l,c);for(let[l,c]of G(o.enumValues,\"enumValues\"))u.enumValues.set(l,c);for(let[l,c]of G(o.bindingTypes,\"bindingTypes\"))u.bindingTypes.set(l,c);for(let l of o.declarationRegistries.records){let c=s.get(l.name);if(!c||!Array.isArray(l.fields))throw Error(\"Invalid serialized record declaration registry.\");if(l.declaration)L(c,l.declaration);let m=c.declaredFields??c.fields;if(m.length!==l.fields.length)throw Error(\"Serialized record field registry does not match its declaration.\");l.fields.forEach((d,p)=>{if(d)L(m[p],d)})}for(let l of o.declarationRegistries.functions){let c=a.get(l.name);if(!c)throw Error(\"Invalid serialized function declaration registry.\");if(l.declaration)L(c,l.declaration)}return pe.set(i,u),i}function v(e,n=new Map){if(!e||typeof e!==\"object\")return e;let t=n.get(e);if(t)return t;if(Array.isArray(e)){let i=[];n.set(e,i);for(let o of e)i.push(v(o,n));return i}if(e instanceof Map){let i=new Map;n.set(e,i);for(let[o,s]of e)i.set(v(o,n),v(s,n));return i}if(e instanceof Set){let i=new Set;n.set(e,i);for(let o of e)i.add(v(o,n));return i}let r={};n.set(e,r);for(let[i,o]of Object.entries(e))r[i]=v(o,n);return r}function te(e,n=new Set){if(!e||typeof e!==\"object\"||n.has(e))return e;if(n.add(e),Array.isArray(e))e.forEach((t)=>te(t,n));else if(!(e instanceof Map)&&!(e instanceof Set))Object.values(e).forEach((t)=>te(t,n));return Object.freeze(e)}function We(e){let n=v(e.recordTypes),t=v(e.functions),r=e.dimensionRegistry?v(e.dimensionRegistry):void 0,i=new X(n,t,r);i.validationMode=e.validationMode;for(let[o,s]of e.recordTypes){let a=n.get(o),u=T(s,e.dimensionRegistry);if(u)L(a,v(u));let l=s.declaredFields??s.fields,c=a.declaredFields??a.fields;for(let m=0;m<l.length;m++){let d=T(l[m],e.dimensionRegistry);if(d&&c[m])L(c[m],v(d))}}for(let[o,s]of e.functions){let a=T(s,e.dimensionRegistry);if(a)L(t.get(o),v(a))}for(let[o,s]of e.enumDeclarations)i.enumDeclarations.set(o,v(s));for(let[o,s]of e.enumValues)i.enumValues.set(o,v(s));for(let[o,s]of e.bindingTypes)i.bindingTypes.set(o,v(s));for(let[o,s]of Object.entries(e.toObject())){let a=v(s);if(i.set(o,a),e.isImmutable(s))i.markImmutable(a)}return i}function O(e,n){let t=e.properties.find((r)=>r.name===n);if(!t)throw Error(`Type checker accepted missing diagram property '${n}'`);return t}function Dn(e,n,t,r,i,o){let s=O(e,n),a=g(s.expression,t,r);if(typeof a!==\"number\"||!Number.isFinite(a)){if(a===1/0&&o===i.to)b(\"AMXD010\",\"Infinity value calculated for time upper bound\",s.valueSource??s.source,r);if(a===1/0&&o>i.from&&o<i.to)b(\"AMXD011\",\"Expression produces an infinite result\",s.valueSource??s.source,r);b(\"AMXD008\",\"Invalid primitive geometry\",s.valueSource??s.source,r)}return a}function He(e,n,t,r,i){if(typeof t!==\"number\"||!Number.isFinite(t)||t<n.from||t>n.to)b(\"AMXD004\",\"Invalid time bounds\",e.times[0]?.source??e.source,i);let o=We(r);o.set(n.variable,t);let s=e.elements.map((a)=>{let u=(m)=>Dn(a,m,o,i,n,t),l=(m)=>{let d=O(a,m).expression;if(d.type!==\"stringLiteral\")throw Error(\"Type checker accepted a non-literal diagram style\");return d.value},c=()=>{let m=O(a,\"lineWidth\").expression;if(m.type!==\"numberLiteral\")throw Error(\"Type checker accepted a non-literal line width\");return m.value};try{switch(a.primitive){case\"line\":{let m=a.properties.find((p)=>p.name===\"arrow\")?.expression,d=m?.type===\"stringLiteral\"?m.value:\"none\";return Object.freeze({primitive:\"line\",name:a.name,source:a.source,x1:u(\"x1\"),y1:u(\"y1\"),x2:u(\"x2\"),y2:u(\"y2\"),stroke:l(\"stroke\"),lineWidth:c(),arrow:d})}case\"rectangle\":{let m=u(\"width\"),d=u(\"height\");if(m<=0)b(\"AMXD008\",\"Invalid primitive geometry\",O(a,\"width\").valueSource,i);if(d<=0)b(\"AMXD008\",\"Invalid primitive geometry\",O(a,\"height\").valueSource,i);let p=a.properties.some((y)=>y.name===\"fill\")?l(\"fill\"):void 0;return Object.freeze({primitive:\"rectangle\",name:a.name,source:a.source,x:u(\"x\"),y:u(\"y\"),width:m,height:d,stroke:l(\"stroke\"),...p===void 0?{}:{fill:p},lineWidth:c()})}case\"circle\":{let m=u(\"r\");if(m<=0)b(\"AMXD008\",\"Invalid primitive geometry\",O(a,\"r\").valueSource,i);let d=a.properties.some((p)=>p.name===\"fill\")?l(\"fill\"):void 0;return Object.freeze({primitive:\"circle\",name:a.name,source:a.source,cx:u(\"cx\"),cy:u(\"cy\"),r:m,stroke:l(\"stroke\"),...d===void 0?{}:{fill:d},lineWidth:c()})}case\"text\":{let m=O(a,\"value\"),d=g(m.expression,o,i);if(typeof d!==\"string\")b(\"AMX3002\",\"Expected String, got non-String value\",m.valueSource,i);return Object.freeze({primitive:\"text\",name:a.name,source:a.source,x:u(\"x\"),y:u(\"y\"),value:d,fill:l(\"fill\")})}default:throw Error(`Type checker accepted unsupported diagram primitive '${a.primitive}'`)}}catch(m){if(m instanceof w&&t!==n.from&&m.code!==\"AMXD008\"&&m.code!==\"AMXD010\"&&m.code!==\"AMXD011\")throw new w({code:\"AMXD009\",message:`Frame evaluation leads to invalid results. The underlying error is: ${m.message}`,file:m.file??i,line:m.line??a.source?.line,column:m.column??a.source?.column});throw m}});return Object.freeze({time:t,elements:Object.freeze(s)})}function Y(e,n,t,r,i,o){let s=g(e,n,t);if(typeof s!==\"number\"||!Number.isFinite(s)||(r===\"AMXD003\"||r===\"AMXD014\"||r===\"AMXD005\")&&s<=0)b(r,i,o,t);return s}function Be(e,n,t,r,i){let o=te(v(e)),s=We(n),a=(he)=>{let we=o.properties.find((Ze)=>Ze.name===he);if(!we)throw Error(`Type checker accepted missing diagram property '${he}'`);return we},u=a(\"width\"),l=a(\"height\"),c=Y(u.expression,s,t,\"AMXD003\",\"Canvas width is invalid\",u.valueSource),m=Y(l.expression,s,t,\"AMXD014\",\"Canvas height is invalid\",l.valueSource),d=a(\"title\").expression,p=a(\"description\").expression;if(d.type!==\"stringLiteral\"||p.type!==\"stringLiteral\")throw Error(\"Type checker accepted a non-literal diagram title or description\");let y=o.times[0],M=Y(y.from,s,t,\"AMXD004\",\"Invalid time bounds\",y.fromSource??y.source),h=Y(y.to,s,t,\"AMXD004\",\"Invalid time bounds\",y.toSource??y.source);if(M>=h)b(\"AMXD004\",\"Invalid time bounds\",y.source??o.source,t);let S=Y(y.duration,s,t,\"AMXD005\",\"Invalid playback duration value\",y.durationSource??y.source),R=Object.freeze({variable:y.name,from:M,to:h,duration:S}),Ye=He(o,R,M,s,t),be=Object.freeze({name:o.name,title:d.value,description:p.value,canvas:Object.freeze({width:c,height:m,coordinates:\"bottom-left-y-up\"}),timeline:R,declaration:o,initialFrame:Ye,source:o.source,file:t,documentNodeIndex:r,statementIndex:i});return pe.set(be,s),be}function _e(e,n,t=e.file){let r=pe.get(e);if(!r)throw Error(\"Diagram model has no captured AMX evaluation context\");return He(e.declaration,e.timeline,n,r,t)}var Nn=\"http://www.w3.org/2000/svg\",ge=new Set;function F(e,n={}){let t=document.createElementNS(Nn,e);for(let[r,i]of Object.entries(n))t.setAttribute(r,String(i));return t}function kn(e,n,t){e.setAttribute(\"x\",String(n)),e.setAttribute(\"y\",String(t)),e.setAttribute(\"transform\",`translate(0 ${2*t}) scale(1 -1)`)}function Tn(e,n){let{model:t,canvas:r}=e,i=F(\"defs\"),o=F(\"marker\",{id:`${r.dataset.diagramId}-arrowhead`,markerWidth:6,markerHeight:6,refX:10,refY:5,orient:\"auto-start-reverse\",markerUnits:\"strokeWidth\",viewBox:\"0 0 10 10\"});o.append(F(\"path\",{d:\"M 0 0 L 10 5 L 0 10 z\",fill:\"context-stroke\"})),i.append(o);let s=F(\"g\",{transform:`translate(0 ${t.canvas.height}) scale(1 -1)`});for(let a of n.elements)if(a.primitive===\"line\"){let u=F(\"line\",{x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke:a.stroke,\"stroke-width\":a.lineWidth,\"stroke-linecap\":\"round\"});if(u.setAttribute(\"data-diagram-element\",a.name),a.arrow===\"start\"||a.arrow===\"both\")u.setAttribute(\"marker-start\",`url(#${r.dataset.diagramId}-arrowhead)`);if(a.arrow===\"end\"||a.arrow===\"both\")u.setAttribute(\"marker-end\",`url(#${r.dataset.diagramId}-arrowhead)`);s.append(u)}else if(a.primitive===\"rectangle\"){let u=F(\"rect\",{x:a.x,y:a.y,width:a.width,height:a.height,stroke:a.stroke,fill:a.fill??\"none\",\"stroke-width\":a.lineWidth});u.setAttribute(\"data-diagram-element\",a.name),s.append(u)}else if(a.primitive===\"circle\"){let u=F(\"circle\",{cx:a.cx,cy:a.cy,r:a.r,stroke:a.stroke,fill:a.fill??\"none\",\"stroke-width\":a.lineWidth});u.setAttribute(\"data-diagram-element\",a.name),s.append(u)}else{let u=F(\"text\",{fill:a.fill,\"font-family\":\"sans-serif\",\"font-size\":12});kn(u,a.x,a.y),u.setAttribute(\"data-diagram-element\",a.name),u.textContent=a.value,s.append(u)}r.replaceChildren(i,s),r.removeAttribute(\"aria-hidden\")}function ye(e){window.dispatchEvent(new CustomEvent(\"openamx-diagram-frame\",{detail:e}))}async function $n(e){if(e.dataset.encoding!==\"gzip-base64\")throw Error(\"Unsupported diagram data encoding.\");let n=atob(e.textContent??\"\"),t=new Uint8Array(n.length);for(let i=0;i<n.length;i++)t[i]=n.charCodeAt(i);let r=new Blob([t]).stream().pipeThrough(new DecompressionStream(\"gzip\"));return Pe(await new Response(r).text())}function re(e){let n=e.model.title;e.playButton.textContent=e.running?\"Pause\":\"Play\",e.playButton.setAttribute(\"aria-label\",`${e.running?\"Pause\":\"Play\"} ${n}`),e.scrubber.value=String(e.time),e.scrubber.setAttribute(\"aria-valuetext\",String(e.time)),e.timeOutput.value=String(e.time),e.timeOutput.textContent=String(e.time)}function C(e){if(e.running=!1,e.animationFrame!==void 0)cancelAnimationFrame(e.animationFrame);e.animationFrame=void 0,re(e)}function U(e,n){e.time=n,re(e);try{let t=_e(e.model,n);if(Tn(e,t),e.alert.hidden=!0,e.alert.textContent=\"\",e.failed)e.failed=!1,ye({version:1,type:\"diagram-recovered\",diagramId:e.canvas.dataset.diagramId});return!0}catch(t){C(e),e.canvas.replaceChildren(),e.canvas.setAttribute(\"aria-hidden\",\"true\"),e.failed=!0;let r=t instanceof w?{code:t.code,message:t.message,file:t.file??e.model.file,line:t.line??e.model.source?.line,column:t.column??e.model.source?.column}:{code:\"DIAGRAM_RUNTIME\",message:\"The diagram frame could not be evaluated.\",file:e.model.file,line:e.model.source?.line,column:e.model.source?.column},i=r.file?`${r.file}${r.line?`:${r.line}${r.column?`:${r.column}`:\"\"}`:\"\"}`:r.line?`${r.line}${r.column?`:${r.column}`:\"\"}`:\"\";return e.alert.textContent=`${r.code}: ${r.message}${i?` (${i})`:\"\"}`,e.alert.hidden=!1,ye({version:1,type:\"diagram-error\",diagramId:e.canvas.dataset.diagramId,...r}),!1}}function In(e){if(e.running||e.failed)return;if(e.time>=e.model.timeline.to){if(!e.canvas.closest(\"[data-openamx-diagram]\")?.querySelector(\"[data-diagram-loop]\")?.checked)return;U(e,e.model.timeline.from)}e.running=!0,e.startedAt=performance.now()-(e.time-e.model.timeline.from)/(e.model.timeline.to-e.model.timeline.from)*e.model.timeline.duration*1000,re(e),e.animationFrame=requestAnimationFrame((n)=>Ge(e,n))}function Ge(e,n){if(!e.running||!document.contains(e.canvas)){C(e);return}let t=e.model.timeline.duration,r=(n-e.startedAt)/1000/t;if(r>=1){if(!(e.canvas.closest(\"[data-openamx-diagram]\")?.querySelector(\"[data-diagram-loop]\")?.checked??!1)){U(e,e.model.timeline.to),C(e);return}if(!U(e,e.model.timeline.from))return;e.startedAt=n}else{let i=e.model.timeline.from,o=e.model.timeline.to,s=r<=0?i:i*(1-r)+o*r;if(!U(e,s))return}e.animationFrame=requestAnimationFrame((i)=>Ge(e,i))}async function Fn(e){let n=e.querySelector(\"[data-diagram-model]\"),t=e.querySelector(\"[data-diagram-canvas]\"),r=e.querySelector(\"[data-diagram-play]\"),i=e.querySelector(\"[data-diagram-reset]\"),o=e.querySelector(\"[data-diagram-scrubber]\"),s=e.querySelector(\"[data-diagram-loop]\"),a=e.querySelector(\"[data-diagram-time]\"),u=e.querySelector(\"[data-diagram-error]\");if(!n||!t||!r||!i||!o||!s||!a||!u)throw Error(\"Diagram HTML is missing required runtime elements.\");let l=await $n(n);t.dataset.diagramId=e.dataset.diagramId;let c={model:l,canvas:t,playButton:r,scrubber:o,timeOutput:a,alert:u,running:!1,failed:!1,time:l.timeline.from,startedAt:0};ge.add(c),re(c),r.addEventListener(\"click\",()=>{if(c.running)C(c);else In(c)}),i.addEventListener(\"click\",()=>{C(c),U(c,l.timeline.from)}),o.addEventListener(\"input\",()=>{let m=Number(o.value);C(c),U(c,m)}),U(c,l.timeline.from)}async function Rn(){for(let e of Array.from(document.querySelectorAll(\"[data-openamx-diagram]\")))try{await Fn(e)}catch(n){let t=e.querySelector(\"[data-diagram-error]\");if(!t)throw n;t.textContent=`DIAGRAM_RUNTIME: ${n instanceof Error?n.message:\"The diagram could not be initialized.\"}`,t.hidden=!1,ye({version:1,type:\"diagram-error\",diagramId:e.dataset.diagramId??\"\",code:\"DIAGRAM_RUNTIME\",message:t.textContent})}}document.addEventListener(\"DOMContentLoaded\",()=>{Rn()},{once:!0});window.addEventListener(\"pagehide\",()=>{for(let e of ge)C(e);ge.clear()},{once:!0});})();\n";
|
|
2
|
+
export default diagramBrowserRuntime;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { gzipSync } from 'node:zlib';
|
|
3
|
+
import { serializeDiagramSceneModel } from '../runtime/diagramModel';
|
|
4
|
+
export const MAX_INTERACTIVE_DIAGRAM_HTML_BYTES = 1024 * 1024;
|
|
5
|
+
export function assertDiagramHtmlSize(html, hasDiagrams) {
|
|
6
|
+
if (!hasDiagrams)
|
|
7
|
+
return;
|
|
8
|
+
const bytes = Buffer.byteLength(html, 'utf8');
|
|
9
|
+
if (bytes > MAX_INTERACTIVE_DIAGRAM_HTML_BYTES) {
|
|
10
|
+
throw new Error(`Interactive diagram HTML exceeds the ${MAX_INTERACTIVE_DIAGRAM_HTML_BYTES}-byte limit (${bytes} bytes).`);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function renderDiagramFigure(model, id) {
|
|
14
|
+
const titleId = `${id}-title`;
|
|
15
|
+
const descriptionId = `${id}-description`;
|
|
16
|
+
const serializedModel = gzipSync(serializeDiagramSceneModel(model), { level: 9 }).toString('base64');
|
|
17
|
+
const from = String(model.timeline.from);
|
|
18
|
+
const to = String(model.timeline.to);
|
|
19
|
+
return `<figure class="openamx-diagram" data-openamx-diagram="${id}" data-diagram-id="${id}" aria-labelledby="${titleId}" aria-describedby="${descriptionId}">
|
|
20
|
+
<figcaption><strong id="${titleId}">${escapeHtml(model.title)}</strong><span id="${descriptionId}">${escapeHtml(model.description)}</span></figcaption>
|
|
21
|
+
<div class="openamx-diagram-controls" role="group" aria-label="Playback controls for ${escapeHtml(model.title)}">
|
|
22
|
+
<button type="button" data-diagram-play aria-label="Play ${escapeHtml(model.title)}">Play</button>
|
|
23
|
+
<button type="button" data-diagram-reset aria-label="Reset ${escapeHtml(model.title)}">Reset</button>
|
|
24
|
+
<label><span>Time</span><input type="range" data-diagram-scrubber min="${from}" max="${to}" step="any" value="${from}" aria-label="Time for ${escapeHtml(model.title)}"></label>
|
|
25
|
+
<output data-diagram-time aria-live="polite">${from}</output>
|
|
26
|
+
<label><input type="checkbox" data-diagram-loop aria-label="Loop ${escapeHtml(model.title)}"> Loop</label>
|
|
27
|
+
</div>
|
|
28
|
+
<svg class="openamx-diagram-canvas" data-diagram-canvas width="${model.canvas.width}" height="${model.canvas.height}" viewBox="0 0 ${model.canvas.width} ${model.canvas.height}" preserveAspectRatio="xMidYMid meet" role="img" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"></svg>
|
|
29
|
+
<p class="openamx-diagram-error" data-diagram-error role="alert" hidden></p>
|
|
30
|
+
<script type="application/json" data-diagram-model data-encoding="gzip-base64">${serializedModel}</script>
|
|
31
|
+
</figure>`;
|
|
32
|
+
}
|
|
33
|
+
export function renderDiagramAssets(nonce, runtime) {
|
|
34
|
+
const safeRuntime = runtime.replace(/<\/script/gi, '<\\/script');
|
|
35
|
+
return `<style nonce="${nonce}">
|
|
36
|
+
.openamx-diagram{margin:1.5rem 0}.openamx-diagram figcaption{display:flex;flex-direction:column;gap:.25rem}.openamx-diagram-controls{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap;margin:.75rem 0}.openamx-diagram-controls label{display:inline-flex;align-items:center;gap:.35rem}.openamx-diagram-controls input[type=range]{min-width:10rem}.openamx-diagram-canvas{display:block;width:100%;height:auto;border:1px solid #a8b3bd}.openamx-diagram-error{color:#8b1e1e;font-weight:600}.openamx-diagram button:focus-visible,.openamx-diagram input:focus-visible{outline:3px solid #146c94;outline-offset:2px}
|
|
37
|
+
</style><script nonce="${nonce}">${safeRuntime}</script>`;
|
|
38
|
+
}
|
|
39
|
+
function escapeHtml(value) {
|
|
40
|
+
return value.replace(/[&<>"']/g, character => ({
|
|
41
|
+
'&': '&',
|
|
42
|
+
'<': '<',
|
|
43
|
+
'>': '>',
|
|
44
|
+
'"': '"',
|
|
45
|
+
"'": '''
|
|
46
|
+
})[character]);
|
|
47
|
+
}
|
|
@@ -35,16 +35,34 @@ export async function prepareNarratives(sources, options) {
|
|
|
35
35
|
diagnostics: narrative.diagnostics
|
|
36
36
|
})));
|
|
37
37
|
}
|
|
38
|
-
export function fitNarrativeImage(image, bounds) {
|
|
38
|
+
export function fitNarrativeImage(image, bounds, width) {
|
|
39
39
|
if (!Number.isFinite(bounds.maxWidth) || !Number.isFinite(bounds.maxHeight) || bounds.maxWidth <= 0 || bounds.maxHeight <= 0) {
|
|
40
40
|
throw new RangeError('Narrative image bounds must be finite positive numbers');
|
|
41
41
|
}
|
|
42
42
|
if (!Number.isFinite(image.width) || !Number.isFinite(image.height) || image.width <= 0 || image.height <= 0) {
|
|
43
43
|
throw new RangeError('Narrative image dimensions must be finite positive numbers');
|
|
44
44
|
}
|
|
45
|
-
const
|
|
45
|
+
const targetWidth = width === undefined
|
|
46
|
+
? image.width
|
|
47
|
+
: width.unit === '%'
|
|
48
|
+
? bounds.maxWidth * width.value / 100
|
|
49
|
+
: width.value;
|
|
50
|
+
const scale = Math.min(targetWidth / image.width, bounds.maxWidth / image.width, bounds.maxHeight / image.height);
|
|
46
51
|
return Object.freeze({ width: image.width * scale, height: image.height * scale });
|
|
47
52
|
}
|
|
53
|
+
export function parseNarrativeImageWidth(value) {
|
|
54
|
+
const match = value.trim().match(/^(\d+)(px|%)$/);
|
|
55
|
+
if (!match)
|
|
56
|
+
return undefined;
|
|
57
|
+
const width = Number(match[1]);
|
|
58
|
+
if (!Number.isSafeInteger(width) || width <= 0)
|
|
59
|
+
return undefined;
|
|
60
|
+
if (match[2] === '%' && width > 100)
|
|
61
|
+
return undefined;
|
|
62
|
+
if (match[2] === 'px' && width > 4096)
|
|
63
|
+
return undefined;
|
|
64
|
+
return { value: width, unit: match[2] === '%' ? '%' : 'px' };
|
|
65
|
+
}
|
|
48
66
|
function interpolateSource(source, interpolate, line) {
|
|
49
67
|
const pattern = /\{\{\s*([\s\S]*?)\s*\}\}/g;
|
|
50
68
|
let prefix = '\uE000OPENAMX_INTERPOLATION-';
|
|
@@ -269,18 +287,25 @@ function prepareLink(href, title, context) {
|
|
|
269
287
|
else {
|
|
270
288
|
try {
|
|
271
289
|
const path = parseRelativeTarget(href, context.options.file);
|
|
272
|
-
|
|
290
|
+
const targetExtension = extension(path.path);
|
|
291
|
+
if (targetExtension !== '.amx' && !LOCAL_LINK_EXTENSIONS.has(targetExtension)) {
|
|
292
|
+
return rejectLink(context, 'invalid-local-target');
|
|
293
|
+
}
|
|
294
|
+
if (targetExtension === '.amx' && (path.query !== undefined || path.fragment !== undefined)) {
|
|
273
295
|
return rejectLink(context, 'invalid-local-target');
|
|
296
|
+
}
|
|
274
297
|
const source = sourceContext(context);
|
|
275
298
|
resolveContainedFile(source, path.path, context.options.file, 'Narrative local link must target a contained regular file');
|
|
276
|
-
link =
|
|
277
|
-
type: '
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
299
|
+
link = targetExtension === '.amx'
|
|
300
|
+
? { type: 'amx', path: path.path, ...(title === undefined ? {} : { title }) }
|
|
301
|
+
: {
|
|
302
|
+
type: 'local',
|
|
303
|
+
path: path.path,
|
|
304
|
+
sourceBase: 'document-directory',
|
|
305
|
+
...(path.query === undefined ? {} : { query: path.query }),
|
|
306
|
+
...(path.fragment === undefined ? {} : { fragment: path.fragment }),
|
|
307
|
+
...(title === undefined ? {} : { title })
|
|
308
|
+
};
|
|
284
309
|
}
|
|
285
310
|
catch (error) {
|
|
286
311
|
if (!(error instanceof AmxError))
|
|
@@ -9,8 +9,11 @@ import { AmxError } from '../diagnostics/errors';
|
|
|
9
9
|
import { parseExpression } from '../parser/parseExpression';
|
|
10
10
|
import { evaluateExpression } from '../runtime/evaluateExpression';
|
|
11
11
|
import { evaluateDocumentEnvironment } from '../runtime/evaluateDocument';
|
|
12
|
+
import { formatAmxValue } from '../runtime/valueSerialization';
|
|
12
13
|
import { formatAmx } from '../formatter/formatAmx';
|
|
13
14
|
import { createChartViewModel } from './chartModel';
|
|
15
|
+
import diagramBrowserRuntime from './diagramBrowserRuntime';
|
|
16
|
+
import { assertDiagramHtmlSize, renderDiagramAssets, renderDiagramFigure } from './diagramHtml';
|
|
14
17
|
import { fitNarrativeImage } from './narrativeModel';
|
|
15
18
|
import { hasSymlink, isContained } from './reportPaths';
|
|
16
19
|
const REPORT_MARKDOWN_POLICY = {
|
|
@@ -46,7 +49,21 @@ export function renderHtml(doc, file, env, options) {
|
|
|
46
49
|
emissions.push(emission);
|
|
47
50
|
emissionsByNode.set(emission.documentNodeIndex, emissions);
|
|
48
51
|
}
|
|
52
|
+
const diagramsByNode = new Map();
|
|
53
|
+
const importedDiagrams = [];
|
|
54
|
+
const entryFile = file ? canonicalReportFile(file) : undefined;
|
|
55
|
+
for (const { model } of environment.diagramEmissions) {
|
|
56
|
+
if (entryFile && model.file && canonicalReportFile(model.file) !== entryFile) {
|
|
57
|
+
importedDiagrams.push(model);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const diagrams = diagramsByNode.get(model.documentNodeIndex) ?? [];
|
|
61
|
+
diagrams.push(model);
|
|
62
|
+
diagramsByNode.set(model.documentNodeIndex, diagrams);
|
|
63
|
+
}
|
|
49
64
|
const bodyFragments = [];
|
|
65
|
+
let diagramIndex = 0;
|
|
66
|
+
const firstExecutableNode = doc.nodes.findIndex(node => node.type === 'executableCodeBlock');
|
|
50
67
|
const sourceVisible = resolvedReport.sourceVisible !== false;
|
|
51
68
|
const header = renderReportHeader(resolvedReport, file);
|
|
52
69
|
if (header) {
|
|
@@ -63,8 +80,20 @@ export function renderHtml(doc, file, env, options) {
|
|
|
63
80
|
const formatted = formatAmx(node.content);
|
|
64
81
|
bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(formatted)}</code></pre>`);
|
|
65
82
|
}
|
|
66
|
-
|
|
67
|
-
|
|
83
|
+
if (nodeIndex === firstExecutableNode) {
|
|
84
|
+
for (const model of importedDiagrams) {
|
|
85
|
+
bodyFragments.push(renderDiagramFigure(model, `openamx-diagram-${diagramIndex++}`));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const blockEmissions = [
|
|
89
|
+
...(emissionsByNode.get(nodeIndex) ?? []).map(emission => ({ type: 'view', emission, statementIndex: emission.statementIndex })),
|
|
90
|
+
...(diagramsByNode.get(nodeIndex) ?? []).map(model => ({ type: 'diagram', model, statementIndex: model.statementIndex }))
|
|
91
|
+
].sort((left, right) => left.statementIndex - right.statementIndex);
|
|
92
|
+
for (const emission of blockEmissions) {
|
|
93
|
+
if (emission.type === 'view')
|
|
94
|
+
bodyFragments.push(renderViewEmission(emission.emission, resolvedReport));
|
|
95
|
+
else
|
|
96
|
+
bodyFragments.push(renderDiagramFigure(emission.model, `openamx-diagram-${diagramIndex++}`));
|
|
68
97
|
}
|
|
69
98
|
}
|
|
70
99
|
}
|
|
@@ -74,25 +103,30 @@ export function renderHtml(doc, file, env, options) {
|
|
|
74
103
|
const bodyHtml = bodyFragments.join('');
|
|
75
104
|
const escapedTitle = escapeHtml(title);
|
|
76
105
|
const hasViews = environment.viewEmissions.length > 0;
|
|
77
|
-
const
|
|
106
|
+
const hasDiagrams = environment.diagramEmissions.length > 0;
|
|
107
|
+
const nonce = hasViews || hasDiagrams || !!resolvedReport.accent ? randomBytes(18).toString('base64') : '';
|
|
78
108
|
const accentStyle = safeAccentStyle(resolvedReport.accent, nonce);
|
|
79
109
|
const viewAssets = hasViews ? renderViewAssets(nonce) : '';
|
|
80
|
-
|
|
110
|
+
const diagramAssets = hasDiagrams ? renderDiagramAssets(nonce, diagramBrowserRuntime) : '';
|
|
111
|
+
const html = `<!doctype html>
|
|
81
112
|
<html>
|
|
82
113
|
<head>
|
|
83
114
|
<meta charset="utf-8">
|
|
84
|
-
${renderContentSecurityPolicy(nonce, hasViews)}
|
|
85
|
-
<title>${escapedTitle}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}
|
|
115
|
+
${renderContentSecurityPolicy(nonce, hasViews || hasDiagrams)}
|
|
116
|
+
<title>${escapedTitle}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}${diagramAssets ? `\n${diagramAssets}` : ''}
|
|
86
117
|
</head>
|
|
87
118
|
<body>
|
|
88
119
|
${bodyHtml}</body>
|
|
89
120
|
</html>`;
|
|
121
|
+
assertDiagramHtmlSize(html, hasDiagrams);
|
|
122
|
+
return html;
|
|
90
123
|
}
|
|
91
124
|
export function renderPreparedHtml(report, options = {}) {
|
|
92
125
|
const isPreview = options.mode === 'preview';
|
|
93
126
|
const previewToken = isPreview ? randomBytes(32).toString('hex') : undefined;
|
|
94
127
|
const context = {
|
|
95
128
|
mode: isPreview ? 'preview' : 'standalone',
|
|
129
|
+
imageWidth: report.identity.imageWidth,
|
|
96
130
|
...(previewToken ? { previewToken } : {}),
|
|
97
131
|
...(!isPreview && options.sourceDocumentPath ? { sourceDocumentPath: options.sourceDocumentPath } : {}),
|
|
98
132
|
...(!isPreview && options.projectRoot ? { projectRoot: options.projectRoot } : {}),
|
|
@@ -100,6 +134,7 @@ export function renderPreparedHtml(report, options = {}) {
|
|
|
100
134
|
targets: {}
|
|
101
135
|
};
|
|
102
136
|
const bodyFragments = [];
|
|
137
|
+
let diagramIndex = 0;
|
|
103
138
|
const identity = report.identity;
|
|
104
139
|
const metadata = [
|
|
105
140
|
identity.organization,
|
|
@@ -111,37 +146,61 @@ export function renderPreparedHtml(report, options = {}) {
|
|
|
111
146
|
const logo = identity.logo ? `<img class="openamx-report-logo" src="${escapeHtml(identity.logo.dataUri)}" alt="${escapeHtml(identity.logo.alt)}" />` : '';
|
|
112
147
|
bodyFragments.push(`<header class="openamx-report-header"><div class="openamx-report-identity">${logo}<div class="openamx-report-meta">${metadata.map(value => `<div class="openamx-report-attr">${escapeHtml(value)}</div>`).join('')}</div></div></header>`);
|
|
113
148
|
}
|
|
114
|
-
|
|
149
|
+
const diagramsByPosition = new Map();
|
|
150
|
+
for (const diagram of report.diagrams ?? []) {
|
|
151
|
+
const diagrams = diagramsByPosition.get(diagram.beforeItemIndex) ?? [];
|
|
152
|
+
diagrams.push(diagram);
|
|
153
|
+
diagramsByPosition.set(diagram.beforeItemIndex, diagrams);
|
|
154
|
+
}
|
|
155
|
+
const renderDiagramsAt = (itemIndex) => {
|
|
156
|
+
for (const diagram of (diagramsByPosition.get(itemIndex) ?? []).sort((left, right) => left.order - right.order)) {
|
|
157
|
+
bodyFragments.push(renderDiagramFigure(diagram.model, `openamx-diagram-${diagramIndex++}`));
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
for (const [itemIndex, item] of report.items.entries()) {
|
|
161
|
+
renderDiagramsAt(itemIndex);
|
|
115
162
|
if (item.type === 'narrative')
|
|
116
163
|
bodyFragments.push(renderNarrativeBlocks(item.markdown, context));
|
|
117
164
|
else if (item.type === 'source')
|
|
118
165
|
bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(item.text)}</code></pre>`);
|
|
119
|
-
else
|
|
166
|
+
else if (item.type === 'view')
|
|
120
167
|
bodyFragments.push(renderViewEmission(item.emission, identity));
|
|
121
168
|
}
|
|
169
|
+
renderDiagramsAt(report.items.length);
|
|
122
170
|
if (identity.footer)
|
|
123
171
|
bodyFragments.push(`<footer class="openamx-report-footer">${escapeHtml(identity.footer)}</footer>`);
|
|
124
172
|
const hasViews = report.items.some(item => item.type === 'view');
|
|
173
|
+
const hasDiagrams = !!report.diagrams?.length;
|
|
125
174
|
const hasNarrativeAssets = report.items.some(item => item.type === 'narrative' && hasHtmlAssets(item.markdown));
|
|
126
|
-
const nonce = hasViews || identity.accent !== '#146C94' || hasNarrativeAssets || isPreview ? randomBytes(18).toString('base64') : '';
|
|
175
|
+
const nonce = hasViews || hasDiagrams || identity.accent !== '#146C94' || hasNarrativeAssets || identity.stylesheetCss !== undefined || isPreview ? randomBytes(18).toString('base64') : '';
|
|
127
176
|
const accentStyle = safeAccentStyle(identity.accent, nonce);
|
|
128
177
|
const viewAssets = hasViews ? renderViewAssets(nonce) : '';
|
|
129
|
-
const
|
|
178
|
+
const diagramAssets = hasDiagrams ? renderDiagramAssets(nonce, diagramBrowserRuntime) : '';
|
|
179
|
+
const narrativeAssets = hasNarrativeAssets ? renderNarrativeAssets(nonce, identity.imageWidth) : '';
|
|
180
|
+
const stylesheet = identity.stylesheetCss === undefined ? '' : renderCustomStylesheet(identity.stylesheetCss, nonce);
|
|
130
181
|
const previewNavigation = previewToken ? renderPreviewNavigationBootstrap(nonce, previewToken) : '';
|
|
131
182
|
const html = `<!doctype html>
|
|
132
183
|
<html>
|
|
133
184
|
<head>
|
|
134
185
|
<meta charset="utf-8">
|
|
135
|
-
${renderContentSecurityPolicy(nonce, hasViews, isPreview)}
|
|
136
|
-
<title>${escapeHtml(report.title)}</title>${accentStyle ? `\n${accentStyle}` : ''}${narrativeAssets ? `\n${narrativeAssets}` : ''}${viewAssets ? `\n${viewAssets}` : ''}${previewNavigation ? `\n${previewNavigation}` : ''}
|
|
186
|
+
${renderContentSecurityPolicy(nonce, hasViews || hasDiagrams, isPreview)}
|
|
187
|
+
<title>${escapeHtml(report.title)}</title>${accentStyle ? `\n${accentStyle}` : ''}${narrativeAssets ? `\n${narrativeAssets}` : ''}${viewAssets ? `\n${viewAssets}` : ''}${diagramAssets ? `\n${diagramAssets}` : ''}${stylesheet ? `\n${stylesheet}` : ''}${previewNavigation ? `\n${previewNavigation}` : ''}
|
|
137
188
|
</head>
|
|
138
189
|
<body>
|
|
139
190
|
${bodyFragments.join('')}</body>
|
|
140
191
|
</html>`;
|
|
192
|
+
assertDiagramHtmlSize(html, hasDiagrams);
|
|
141
193
|
if (previewToken)
|
|
142
194
|
return { html, previewToken, targets: context.targets };
|
|
143
195
|
return html;
|
|
144
196
|
}
|
|
197
|
+
function renderCustomStylesheet(css, nonce) {
|
|
198
|
+
return `<style nonce="${nonce}">${css.replace(/</g, '\\3C ')}</style>`;
|
|
199
|
+
}
|
|
200
|
+
function canonicalReportFile(file) {
|
|
201
|
+
const path = existsSync(file) ? realpathSync(file) : resolve(file);
|
|
202
|
+
return process.platform === 'win32' ? path.toLowerCase() : path;
|
|
203
|
+
}
|
|
145
204
|
function renderNarrativeBlocks(blocks, context) {
|
|
146
205
|
return blocks.map(block => {
|
|
147
206
|
switch (block.type) {
|
|
@@ -173,19 +232,19 @@ function tableCellAlignment(alignment) {
|
|
|
173
232
|
function renderNarrativeInlines(inlines, context) {
|
|
174
233
|
return inlines.map(inline => {
|
|
175
234
|
switch (inline.type) {
|
|
176
|
-
case 'text': return
|
|
235
|
+
case 'text': return renderNarrativeText(inline.text);
|
|
177
236
|
case 'lineBreak': return '<br>';
|
|
178
237
|
case 'strong': return `<strong>${renderNarrativeInlines(inline.children, context)}</strong>`;
|
|
179
238
|
case 'emphasis': return `<em>${renderNarrativeInlines(inline.children, context)}</em>`;
|
|
180
239
|
case 'delete': return `<del>${renderNarrativeInlines(inline.children, context)}</del>`;
|
|
181
240
|
case 'inlineCode': return `<code>${escapeHtml(inline.text)}</code>`;
|
|
182
|
-
case 'image': return renderNarrativeImage(inline.image, inline.title);
|
|
241
|
+
case 'image': return renderNarrativeImage(inline.image, inline.title, context.imageWidth);
|
|
183
242
|
case 'link': return renderNarrativeLink(inline.link, inline.children, context);
|
|
184
243
|
}
|
|
185
244
|
}).join('');
|
|
186
245
|
}
|
|
187
|
-
function renderNarrativeImage(image, title) {
|
|
188
|
-
const dimensions = fitNarrativeImage(image, { maxWidth: 1024, maxHeight: 768 });
|
|
246
|
+
function renderNarrativeImage(image, title, imageWidth) {
|
|
247
|
+
const dimensions = fitNarrativeImage(image, { maxWidth: 1024, maxHeight: 768 }, imageWidth);
|
|
189
248
|
return `<img class="openamx-narrative-image" src="${escapeHtml(image.dataUri)}" alt="${escapeHtml(image.alt)}" width="${Math.round(dimensions.width)}" height="${Math.round(dimensions.height)}"${title === undefined ? '' : ` title="${escapeHtml(title)}"`}>`;
|
|
190
249
|
}
|
|
191
250
|
function renderNarrativeLink(link, children, context) {
|
|
@@ -193,12 +252,16 @@ function renderNarrativeLink(link, children, context) {
|
|
|
193
252
|
const title = link.title === undefined ? '' : ` title="${escapeHtml(link.title)}"`;
|
|
194
253
|
if (link.type === 'internal')
|
|
195
254
|
return `<a href="#${encodeURIComponent(link.targetId)}"${title}>${label}</a>`;
|
|
255
|
+
if (link.type === 'amx' && context.mode !== 'preview')
|
|
256
|
+
return label;
|
|
196
257
|
if (context.mode === 'preview') {
|
|
197
258
|
const targetId = addPreviewTarget(context, link);
|
|
198
259
|
return `<a href="#" data-openamx-target="${targetId}"${title}>${label}</a>`;
|
|
199
260
|
}
|
|
200
261
|
if (link.type === 'external')
|
|
201
262
|
return `<a href="${escapeHtml(link.href)}" rel="noopener noreferrer"${title}>${label}</a>`;
|
|
263
|
+
if (link.type === 'amx')
|
|
264
|
+
return label;
|
|
202
265
|
return `<a href="${escapeHtml(standaloneLocalLinkUri(link, context))}"${title}>${label}</a>`;
|
|
203
266
|
}
|
|
204
267
|
function addPreviewTarget(context, link) {
|
|
@@ -208,7 +271,7 @@ function addPreviewTarget(context, link) {
|
|
|
208
271
|
while (context.targets[targetId]);
|
|
209
272
|
context.targets[targetId] = link.type === 'external'
|
|
210
273
|
? { kind: 'external', href: link.href }
|
|
211
|
-
: { kind:
|
|
274
|
+
: { kind: link.type, path: link.path };
|
|
212
275
|
return targetId;
|
|
213
276
|
}
|
|
214
277
|
function standaloneLocalLinkUri(link, context) {
|
|
@@ -253,12 +316,17 @@ function hasInlineHtmlAssets(inlines) {
|
|
|
253
316
|
|| (inline.type === 'link' || inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete')
|
|
254
317
|
&& hasInlineHtmlAssets(inline.children));
|
|
255
318
|
}
|
|
256
|
-
function renderNarrativeAssets(nonce) {
|
|
257
|
-
|
|
319
|
+
function renderNarrativeAssets(nonce, imageWidth) {
|
|
320
|
+
const imageSizing = imageWidth === undefined
|
|
321
|
+
? 'max-width:100%;'
|
|
322
|
+
: imageWidth.unit === '%'
|
|
323
|
+
? `width:${imageWidth.value}%;max-width:min(100%,1024px);max-height:768px;`
|
|
324
|
+
: `width:${imageWidth.value}px;max-width:100%;max-height:768px;`;
|
|
325
|
+
return `<style nonce="${nonce}">.openamx-narrative-image{display:block;${imageSizing}height:auto}.openamx-narrative-table{border-collapse:collapse;width:100%;margin:1rem 0}.openamx-narrative-table th,.openamx-narrative-table td{border:1px solid #a8b3bd;padding:.4rem;text-align:left}.openamx-page-break{break-before:page;page-break-before:always}@media screen{.openamx-page-break{border-top:1px dashed #a8b3bd;margin:1.5rem 0}}</style>`;
|
|
258
326
|
}
|
|
259
327
|
function renderPreviewNavigationBootstrap(nonce, previewToken) {
|
|
260
328
|
const token = JSON.stringify(previewToken);
|
|
261
|
-
return `<script nonce="${nonce}">(()=>{const token=${token};let port;window.addEventListener("message",event=>{const data=event.data;if(event.source!==parent||!data||data.type!=="openamx-preview-init"||data.previewToken!==token||event.ports.length!==1)return;port=event.ports[0];port.start()},{once:true});document.addEventListener("click",event=>{const source=event.target;if(!(source instanceof Element))return;const link=source.closest("a[data-openamx-target]");if(!link)return;event.preventDefault();if(!event.isTrusted||!navigator.userActivation?.isActive||!port)return;const targetId=link.getAttribute("data-openamx-target");if(!targetId)return;port.postMessage({version:1,type:"navigate",previewToken:token,targetId})},true)})();</script>`;
|
|
329
|
+
return `<script nonce="${nonce}">(()=>{const token=${token};let port;let scheduled=false;const pending=[];const validDiagramEvent=value=>{if(!value||typeof value!=="object"||Array.isArray(value)||value.version!==1||typeof value.diagramId!=="string"||!/^openamx-diagram-[0-9]+$/.test(value.diagramId))return false;if(value.type==="diagram-recovered")return Object.keys(value).length===3;if(value.type!=="diagram-error"||typeof value.code!=="string"||value.code.length>32||typeof value.message!=="string"||value.message.length>1000)return false;return Object.keys(value).every(key=>["version","type","diagramId","code","message","file","line","column"].includes(key))&&(value.file===undefined||typeof value.file==="string"&&value.file.length<=4096)&&(value.line===undefined||Number.isSafeInteger(value.line)&&value.line>0)&&(value.column===undefined||Number.isSafeInteger(value.column)&&value.column>0)};const forwardDiagramEvent=value=>{if(!validDiagramEvent(value))return;const outgoing={...value,previewToken:token};if(port)port.postMessage(outgoing);else pending.push(outgoing)};window.addEventListener("openamx-diagram-frame",event=>forwardDiagramEvent(event.detail));const progress=()=>{const maximum=Math.max(0,document.documentElement.scrollHeight-window.innerHeight);return maximum>0?Math.max(0,Math.min(1,window.scrollY/maximum)):0};const reportScroll=()=>{if(!port||scheduled)return;scheduled=true;requestAnimationFrame(()=>{scheduled=false;if(port)port.postMessage({version:1,type:"scroll",previewToken:token,progress:progress()})})};window.addEventListener("scroll",reportScroll,{passive:true});window.addEventListener("message",event=>{const data=event.data;if(event.source!==parent||!data||data.type!=="openamx-preview-init"||data.previewToken!==token||event.ports.length!==1)return;port=event.ports[0];port.onmessage=message=>{const value=message.data;if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length!==4||value.version!==1||value.type!=="set-scroll"||value.previewToken!==token||typeof value.progress!=="number"||!Number.isFinite(value.progress)||value.progress<0||value.progress>1)return;const maximum=Math.max(0,document.documentElement.scrollHeight-window.innerHeight);window.scrollTo(0,maximum*value.progress)};port.start();for(const message of pending.splice(0))port.postMessage(message)},{once:true});document.addEventListener("click",event=>{const source=event.target;if(!(source instanceof Element))return;const link=source.closest("a[data-openamx-target]");if(!link)return;event.preventDefault();if(!event.isTrusted||!navigator.userActivation?.isActive||!port)return;const targetId=link.getAttribute("data-openamx-target");if(!targetId)return;port.postMessage({version:1,type:"navigate",previewToken:token,targetId})},true)})();</script>`;
|
|
262
330
|
}
|
|
263
331
|
function renderViewEmission(emission, identity) {
|
|
264
332
|
if (emission.kind === 'table')
|
|
@@ -275,8 +343,8 @@ function renderTable(emission) {
|
|
|
275
343
|
const rows = emission.data.filter(isRecordValue);
|
|
276
344
|
const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
|
|
277
345
|
const header = columns.map(column => `<th scope="col" aria-sort="none"><button type="button" data-sort="${escapeHtml(column.field)}">${escapeHtml(column.label)}</button></th>`).join('');
|
|
278
|
-
const body = rows.map((row, index) => `<tr data-row-index="${index}">${columns.map(column => `<td>${
|
|
279
|
-
const printBody = rows.map(row => `<tr>${columns.map(column => `<td>${
|
|
346
|
+
const body = rows.map((row, index) => `<tr data-row-index="${index}">${columns.map(column => `<td>${renderNarrativeText(formatAmxValue(row[column.field]))}</td>`).join('')}</tr>`).join('');
|
|
347
|
+
const printBody = rows.map(row => `<tr>${columns.map(column => `<td>${renderNarrativeText(formatAmxValue(row[column.field]))}</td>`).join('')}</tr>`).join('');
|
|
280
348
|
const payload = safeJson({ columns: columns.map(column => ({ field: column.field, label: column.label })), rows });
|
|
281
349
|
return `<section class="openamx-view openamx-table" data-view="${id}" aria-labelledby="${id}-caption">
|
|
282
350
|
<h2 id="${id}-caption" class="sr-only">${escapeHtml(caption)}</h2>
|
|
@@ -302,7 +370,7 @@ function renderChart(emission, identity) {
|
|
|
302
370
|
const zoomControls = browserModel.zoomable
|
|
303
371
|
? `<div class="openamx-chart-controls" role="group" aria-label="Chart zoom controls"><button type="button" data-zoom="out" aria-label="Zoom out">Zoom out</button><button type="button" data-zoom="in" aria-label="Zoom in">Zoom in</button><button type="button" data-zoom="reset">Reset zoom</button></div>`
|
|
304
372
|
: '';
|
|
305
|
-
const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${
|
|
373
|
+
const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${renderNarrativeText(formatAmxValue(value))}</td>`).join('')}</tr>`).join('');
|
|
306
374
|
const data = safeJson(browserModel);
|
|
307
375
|
return `<figure class="openamx-view openamx-chart" id="${id}-figure" data-openamx-chart aria-labelledby="${titleId}" aria-describedby="${descriptionId} ${summaryId}">
|
|
308
376
|
<figcaption><strong id="${titleId}">${escapeHtml(model.title)}</strong><span id="${descriptionId}">${escapeHtml(model.description)}</span></figcaption>
|
|
@@ -492,26 +560,9 @@ function substituteInlines(content, env, file, narrativeLine) {
|
|
|
492
560
|
const source = narrativeLine !== undefined ? { line: narrativeLine, column: 1 } : undefined;
|
|
493
561
|
const exprNode = parseExpression(trimmed, source);
|
|
494
562
|
const value = evaluateExpression(exprNode, env, file);
|
|
495
|
-
return escapeHtml(
|
|
563
|
+
return escapeHtml(formatAmxValue(value));
|
|
496
564
|
});
|
|
497
565
|
}
|
|
498
|
-
function valueToString(v) {
|
|
499
|
-
if (v === null || v === undefined)
|
|
500
|
-
return '';
|
|
501
|
-
if (typeof v === 'string')
|
|
502
|
-
return v;
|
|
503
|
-
if (typeof v === 'number') {
|
|
504
|
-
// Present integers without trailing .0 for natural readability in text.
|
|
505
|
-
return Number.isInteger(v) ? String(v) : String(v);
|
|
506
|
-
}
|
|
507
|
-
if (typeof v === 'boolean')
|
|
508
|
-
return String(v); // "true" / "false"
|
|
509
|
-
if (Array.isArray(v)) {
|
|
510
|
-
// Simple deterministic representation for lists inside narrative text.
|
|
511
|
-
return v.map(valueToString).join(', ');
|
|
512
|
-
}
|
|
513
|
-
return String(v);
|
|
514
|
-
}
|
|
515
566
|
function escapeHtml(s) {
|
|
516
567
|
return s
|
|
517
568
|
.replace(/&/g, '&')
|
|
@@ -519,3 +570,6 @@ function escapeHtml(s) {
|
|
|
519
570
|
.replace(/>/g, '>')
|
|
520
571
|
.replace(/"/g, '"');
|
|
521
572
|
}
|
|
573
|
+
function renderNarrativeText(text) {
|
|
574
|
+
return escapeHtml(text).replace(/\n( *)/g, (_lineBreak, indentation) => `<br>${' '.repeat(indentation.length)}`);
|
|
575
|
+
}
|