@holistics/anfra-sdk 0.20.0 → 0.21.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 +5 -0
- package/dist/api.d.ts +11 -8
- package/dist/api.js +45 -22
- package/dist/app.d.ts +5 -5
- package/dist/app.js +4 -3
- package/dist/{bootstrap-DHU2haC5.d.ts → bootstrap-BxBqFhgm.d.ts} +279 -27
- package/dist/build.d.ts +2 -2
- package/dist/{chunk-32566ZNE.js → chunk-2TTGSNHA.js} +1 -1
- package/dist/{chunk-H52PO7MP.js → chunk-33HI2ODM.js} +25 -0
- package/dist/chunk-4UEESYHH.js +32 -0
- package/dist/{chunk-4TXKXLWK.js → chunk-7I2HXY72.js} +1 -1
- package/dist/{chunk-KKSOTHP4.js → chunk-7NZOMBYE.js} +1 -1
- package/dist/{chunk-DITKCHFQ.js → chunk-CLXZMA5D.js} +1 -1
- package/dist/{chunk-GBXK7F2V.js → chunk-D7DIJRAC.js} +14 -1
- package/dist/{chunk-FTTVLHNN.js → chunk-E3Q3FRKQ.js} +1 -1
- package/dist/{chunk-SXKJQU7A.js → chunk-GPBYPSWK.js} +22 -36
- package/dist/{chunk-T5T76SAR.js → chunk-IHRNKDMO.js} +830 -265
- package/dist/{chunk-EIPHDMZ7.js → chunk-UWRQXPPG.js} +69 -24
- package/dist/common.d.ts +3 -3
- package/dist/{data-ESPFZ5IM.js → data-SZDYO55C.js} +7 -5
- package/dist/{declaration-RYRBX7PH.js → declaration-GYV6OUR3.js} +5 -3
- package/dist/{errors-189T_Mnc.d.ts → errors-DR05L6-y.d.ts} +1 -1
- package/dist/host.d.ts +2 -2
- package/dist/host.js +29 -6
- package/dist/{menu-Cam-hOdJ.d.ts → menu-CuTKq-dC.d.ts} +2 -1
- package/dist/{overview-AWPXJACF.js → overview-KOQJNG2Y.js} +28 -13
- package/dist/{plugin-rRd-zHGt.d.ts → plugin-BIcighnC.d.ts} +7 -2
- package/dist/plugins.d.ts +1 -7
- package/dist/plugins.js +53 -17
- package/dist/{queries-FWMX7H5Z.js → queries-BWKWZQMG.js} +70 -17
- package/dist/{structure-VFRJFC4C.js → structure-JO4YZHKZ.js} +5 -3
- package/dist/{tab-XL2HS5W4.js → tab-QPHE7YUQ.js} +3 -3
- package/dist/testing.d.ts +2 -1
- package/dist/testing.js +8 -7
- package/dist/{types-N0V9n38H.d.ts → types-C_-1rgj2.d.ts} +781 -123
- package/package.json +1 -1
package/dist/host.js
CHANGED
|
@@ -6,16 +6,18 @@ import {
|
|
|
6
6
|
definePlugin
|
|
7
7
|
} from "./chunk-7K6Z63QO.js";
|
|
8
8
|
import {
|
|
9
|
-
createEndpoint,
|
|
10
9
|
eventShortcut,
|
|
11
10
|
isTyping,
|
|
12
11
|
normalizeShortcut
|
|
13
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-4UEESYHH.js";
|
|
14
13
|
import {
|
|
15
14
|
PROVISION_ELEMENT_ID,
|
|
16
15
|
applyTheme,
|
|
17
16
|
resolveTheme
|
|
18
17
|
} from "./chunk-RXPNL7UR.js";
|
|
18
|
+
import {
|
|
19
|
+
createEndpoint
|
|
20
|
+
} from "./chunk-GPBYPSWK.js";
|
|
19
21
|
import {
|
|
20
22
|
DataAppError,
|
|
21
23
|
checkConsoleEvent,
|
|
@@ -28,7 +30,7 @@ import {
|
|
|
28
30
|
import "./chunk-PKBMQBKP.js";
|
|
29
31
|
|
|
30
32
|
// anfra-sdk:anfra-sdk:frame-script
|
|
31
|
-
var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var K=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var rn=Object.getOwnPropertyNames;var on=Object.prototype.hasOwnProperty;var sn=(e,n,t)=>n in e?K(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var i=(e,n)=>K(e,"name",{value:n,configurable:!0});var an=(e,n)=>{for(var t in n)K(e,t,{get:n[t],enumerable:!0})},ln=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of rn(n))!on.call(e,o)&&o!==t&&K(e,o,{get:()=>n[o],enumerable:!(r=nn(n,o))||r.enumerable});return e};var dn=e=>ln(K({},"__esModule",{value:!0}),e);var c=(e,n,t)=>sn(e,typeof n!="symbol"?n+"":n,t);var lr={};an(lr,{bootstrap:()=>tn});var Xe="anfra-provision";function j(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9]+/g,"_").toLowerCase()}i(j,"snakeCase");var H=new WeakMap;function q(e,n){typeof e=="object"&&e!==null&&H.set(e,n)}i(q,"tagCall");function Ze(e){for(let n=e,t=0;typeof n=="object"&&n!==null&&t<5;n=n.cause,t+=1){let r=H.get(n);if(r)return r}}i(Ze,"callOf");function pe(e,n){let t=H.get(e);return t&&H.set(n,t),n}i(pe,"copyCallTag");function fe(e,n){return function(...t){let r=e.apply(this,t);return r&&typeof r.then=="function"?r.then(void 0,o=>{throw q(o,n),o}):r}}i(fe,"namedCall");var me=2e3,cn=4e3;function W(e,n){return e.length<=n?e:`${e.slice(0,n)}\\u2026 (truncated)`}i(W,"truncate");function et(e,n){let t=n,r=typeof t=="object"&&t!==null,o={kind:e,message:W(r&&typeof t.message=="string"?t.message:String(n),me),at:new Date().toISOString()};if(!r)return o;for(let l of["code","scope","requestId","entity"]){let s=t[l];typeof s=="string"&&(o[l]=s)}return!e.startsWith("call.")&&typeof t.stack=="string"&&(o.stack=W(t.stack,cn)),o}i(et,"describeError");function he(e,n=()=>{},t=Date.now){let r=t(),o=0,l=0,s,a=i(()=>{s=void 0;let d=l;if(l=0,d>0)try{n(d)}catch{}},"flush");return{take(){let d=t();return d-r>=6e4&&(s!==void 0&&clearTimeout(s),a(),r=d,o=0),o<e?(o+=1,!0):(l+=1,s===void 0&&(s=setTimeout(a,Math.max(0,r+6e4-d))),!1)},dispose(){s!==void 0&&clearTimeout(s),a()}}}i(he,"createBudget");var tt={query_invalid:"user",query_failed:"user",forbidden:"user",unauthenticated:"user",invalid_request:"client",declaration_invalid:"client",connection_failed:"server",call_failed:"server",internal_server_error:"server"},Y=class Y extends Error{constructor(t){super(t.message);c(this,"code");c(this,"scope");c(this,"status");c(this,"details");c(this,"context");c(this,"requestId");c(this,"entity");c(this,"cause");this.name=new.target.name,this.code=t.code,this.scope=t.scope,t.status!==void 0&&(this.status=t.status),t.details!==void 0&&(this.details=t.details),t.context!==void 0&&(this.context=t.context),t.requestId!==void 0&&(this.requestId=t.requestId),t.entity!==void 0&&(this.entity=t.entity),t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}about(t){return this.entity===t?this:pe(this,new Y({...pn(this),entity:t}))}};i(Y,"DataAppError");var O=Y,X=class X extends O{constructor(n,t){super({code:"declaration_invalid",scope:"client",message:n,entity:t})}about(n){return this.entity===n?this:pe(this,new X(this.message,n))}};i(X,"ValidationError");var y=X;function Q(e){if(e instanceof O)return!0;let n=e;return n instanceof Error&&(n.name==="DataAppError"||n.name==="ValidationError")&&typeof n.code=="string"}i(Q,"isDataAppError");function nt(e,n){return Q(e)&&e.code===n}i(nt,"hasErrorCode");function rt(e){if(!Array.isArray(e))return;let n=e.filter(t=>typeof t?.text=="string").map(t=>typeof t.step=="string"?{step:t.step,text:t.text}:{text:t.text});return n.length?n:void 0}i(rt,"contextOf");function Z(e,n){return new O({code:"invalid_request",scope:"client",message:e,entity:n})}i(Z,"invalidRequest");function ot(e,n){return new O({code:"forbidden",scope:"user",message:e,entity:n})}i(ot,"forbidden");function it(e,n){return new O({code:"connection_failed",scope:"server",message:e,status:n})}i(it,"connectionFailed");function V(e){return new O({code:"call_failed",scope:"server",message:"The call failed.",cause:e})}i(V,"callFailed");function st(e,n,t={}){let{refused:r="invalid_request",requestId:o,entity:l}=t,s;return e===void 0||e===0?s="connection_failed":e===401?s="unauthenticated":e===403?s="forbidden":e>=400&&e<500?s=r:s="internal_server_error",new O({code:s,scope:un(s,e),message:n,status:e||void 0,requestId:o,entity:l})}i(st,"fromHttpStatus");function un(e,n){return e in tt?tt[e]:n!==void 0&&n>=400&&n<500?"user":"server"}i(un,"scopeOf");function at(e){return e==="user"||e==="client"||e==="server"?e:"server"}i(at,"toScope");function pn(e){return{code:e.code,scope:e.scope,message:e.message,status:e.status,details:e.details,context:e.context,requestId:e.requestId,entity:e.entity,cause:e.cause}}i(pn,"fieldsOf");function lt(){let e=new Error("Aborted");return e.name="AbortError",e}i(lt,"abortError");function fn(e){return e?.name==="AbortError"}i(fn,"isAbortError");var mn=new Set(["query_invalid","validation_failed","invalid_request","result_too_large","page_too_large"]);function ge(e,n){let t=typeof n.code=="string"&&n.code?n.code:"call_failed",r={name:e,code:t,scope:at(n.scope),message:typeof n.message=="string"&&n.message?n.message:"The call failed."};typeof n.status=="number"&&(r.status=n.status),n.details!==void 0&&mn.has(t)&&(r.details=n.details);let o=rt(n.context);return o&&(r.context=o),typeof n.requestId=="string"&&(r.requestId=n.requestId),r}i(ge,"crossing");function hn(e){return Q(e)?ge(e.name,e):ge("DataAppError",V())}i(hn,"toBridgeError");function gn(e){if(!e||typeof e!="object")return V();let n=ge(e.name,e);return n.name==="ValidationError"&&n.code==="declaration_invalid"?new y(n.message):new O({code:n.code,scope:n.scope,message:n.message,status:n.status,details:n.details,context:n.context,requestId:n.requestId})}i(gn,"fromBridgeError");function dt(e,n){let t=new Map,r=new Map,o=1,l=i((s,a,d)=>{let p=new AbortController;r.set(s,p),Promise.resolve().then(()=>n.answer(a,d,p.signal)).then(b=>{p.signal.aborted||e({type:"anfra:result",id:s,ok:!0,result:b})}).catch(b=>{if(p.signal.aborted||fn(b))return;let E=hn(b);if(!Q(b))if(n.hidden)try{n.hidden(a,b)}catch{}else console.error(`anfra: \'${a}\' failed; the other side is told only that the call failed.`,b);e({type:"anfra:result",id:s,ok:!1,error:E})}).finally(()=>{r.get(s)===p&&r.delete(s)})},"answer");return{call(s,a,d){return new Promise((p,b)=>{if(d?.aborted){b(lt());return}let E=o++;t.set(E,{resolve:p,reject:b}),d?.addEventListener("abort",()=>{t.delete(E)&&(e({type:"anfra:cancel",id:E}),b(lt()))},{once:!0}),e({type:"anfra:call",id:E,name:s,request:a})})},emit(s,a){e({type:"anfra:event",name:s,payload:a})},receive(s){switch(s?.type){case"anfra:call":return l(s.id,s.name,s.request),!0;case"anfra:result":{let a=t.get(s.id);return a&&(t.delete(s.id),s.ok?a.resolve(s.result):a.reject(gn(s.error))),!0}case"anfra:cancel":return r.get(s.id)?.abort(),r.delete(s.id),!0;case"anfra:event":return n.event(s.name,s.payload),!0;default:return!1}},close(s){r.forEach(a=>a.abort()),r.clear(),t.forEach(({reject:a})=>a(s)),t.clear()}}}i(dt,"createEndpoint");var be;function $(e,n){try{be?.(e,n)}catch{}}i($,"reportError");var ye=120;function yn(e){if(typeof e=="string")return e;if(e instanceof Error)return`${e.name}: ${e.message}`;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}i(yn,"textOf");function ct(e,n,t,r=Date.now){let o=i(E=>k=>n.console?.warn(`anfra: ${k} ${E} over the ${ye} a minute a frame sends were not sent to the host.`),"dropped"),l=he(ye,o("runtime errors"),r),s=he(ye,o("console lines"),r);be=i((E,k)=>{l.take()&&e.emit("error",et(E,k))},"reporter");let a=i(E=>$("app.uncaught",E.error??E.message),"onError"),d=i(E=>{let k=Ze(E.reason);$(k?`call.${k}`:"app.uncaught",E.reason)},"onRejection");n.addEventListener("error",a),n.addEventListener("unhandledrejection",d);let p=n.console,b={};if(t&&p)for(let E of["error","warn"]){let k=p[E];b[E]=k,p[E]=(...x)=>{if(k.apply(p,x),!(typeof x[0]=="string"&&x[0].startsWith("anfra:")))try{s.take()&&e.emit("console",{level:E,message:W(x.map(yn).join(" "),me),at:new Date().toISOString()})}catch{}}}return()=>{be=void 0,l.dispose(),s.dispose(),n.removeEventListener("error",a),n.removeEventListener("unhandledrejection",d);for(let[E,k]of Object.entries(b))p[E]=k}}i(ct,"installReporting");var we=class we{constructor(n){c(this,"listeners",new Set);c(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>{try{n()}catch(t){console.error("anfra: a subscribe() listener threw; the queries carry on.",t),$("app.listener",t)}}),this.parent?.notifyChange()}notify(){this.notifyChange()}};i(we,"Observable");var L=we;var ut=["year","quarter","month","week","day","hour","minute"];function bn(e,n){if(!ut.includes(n))throw new y(`Invalid grain \'${n}\'. Expected one of: ${ut.join(", ")}.`,e)}i(bn,"assertGrain");function pt(e,n){return n?(bn(e,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}i(pt,"drillCondition");function wn(e){let n=e.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}i(wn,"inferType");function kn(e,n){return JSON.stringify(e??null)===JSON.stringify(n??null)}i(kn,"sameCondition");var ke=class ke extends L{constructor(t,r,o){super(r);c(this,"name");c(this,"app");c(this,"pending");c(this,"applied");c(this,"initial");this.name=t,this.app=r,this.initial=o,this.pending=o}locate(){return this.app.locate("control",this.name)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!kn(this.pending,this.applied)}setCondition(t){this.pending=t,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};i(ke,"Control");var F=ke,Ee=class Ee extends F{constructor(t,r,o,l,s){super(t,r,o.default??{operator:"is",values:[]});c(this,"kind","filter");c(this,"declaration");c(this,"type");c(this,"resolved");c(this,"datasetName");c(this,"backend");c(this,"loadedOptions");if(this.declaration=o,this.backend=s,o.field){if(!l)throw new y(`Filter \'${t}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,t);this.resolved=l.resolve(o.field,t),this.datasetName=l.descriptor.name,this.type=o.type??wn(this.resolved.type)}else{if(!o.type)throw new y(`Filter \'${t}\' is a manual filter, so it needs a \\`type\\`.`,t);this.type=o.type}this.assertValues(this.condition.values??[]),this.assertValues(o.options??[])}setCondition(t){this.assertValues(t.values??[]),super.setCondition(t)}assertValues(t){if(this.type!=="number")return;let r=t.find(o=>typeof o=="number");if(r!==void 0)throw new y(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(r))}, not ${String(r)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolved!==void 0}get options(){return this.loadedOptions??this.declaration.options??[]}async loadOptions(t,r=new AbortController().signal){let o=this.resolved?.modelName;if(!this.resolved||!o||!this.backend||!this.datasetName)return this.options;let l=await this.backend.fieldSuggestions({dataset:this.datasetName,model:o,field:this.resolved.fieldName,q:t??""},r).catch(s=>{throw q(s,"load_options"),s});return this.loadedOptions=[...l??[]],this.notify(),this.loadedOptions}toJSON(){return this.declaration}};i(Ee,"Filter");var ee=Ee,ve=class ve extends F{constructor(t,r,o={}){super(t,r,pt(t,o.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=o}setGrain(t){this.setCondition(pt(this.name,t))}toJSON(){return this.declaration}};i(ve,"DateDrillControl");var te=ve;var _={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},ne=`[${_.container}],[${_.block}],[${_.query}],[${_.control}]`;function ft(e){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(e);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}i(ft,"parseRef");var mt=i(e=>(e??"").split(/\\s+/).filter(Boolean),"tokens");function ht(e,n,t,r){let o=n==="query"?_.query:_.control;return[...e.querySelectorAll(`[${o}]`)].filter(l=>mt(l.getAttribute(o)).some(s=>{let a=ft(s);return a?.app===t&&a.name===r}))}i(ht,"markersFor");var En=i((e,n,t)=>{let r=e[t.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,t.name):!1},"hasEntity");function gt(e,n){var E;let t=[],r=new Map,o=new Map,l=new Map,s=new Map,a={container:new Set,block:new Set},d={},p=i((k,x,T)=>{let R=k?l.get(k).children:t,f=k?`${l.get(k).key}.`:"",m={...x,key:`${f}${R.length}`,children:[]};return R.push(m),r.set(m.key,T),o.set(T,[...o.get(T)??[],m.key]),m},"place");for(let k of e.querySelectorAll(ne)){let x=k.parentElement?.closest(ne)??null,T=k.getAttribute(_.container),R=k.getAttribute(_.block),f=k.getAttribute(_.label)??void 0,m=x&&(s.get(x)==="block"?x:x.closest(`[${_.block}]`)),w;if(T!==null||R!==null){let h=T!==null?"container":"block",v=(T??R??"").trim(),g=[];T!==null&&R!==null&&g.push("This element is marked as a container and as a block. It counts as a container."),v?a[h].has(v)?g.push(`Another ${h} already has the id "${v}".`):a[h].add(v):g.push(`This ${h} has no id.`),m&&g.push(`A block can\'t hold a ${h}. This one is inside the block "${m.getAttribute(_.block)}".`),w=p(x,{kind:h,id:v,...f!==void 0?{label:f}:{},problems:g},k),l.set(k,w),s.set(k,h)}let u=w?k:x;for(let h of["query","control"])for(let v of mt(k.getAttribute(h==="query"?_.query:_.control))){let g=ft(v),S=[];if(g?En(n,h,g)||S.push(n[g.app]?`No ${h} is called "${g.name}" in app ${g.app}.`:`The page has no app ${g.app}.`):S.push(`Can\'t read "${v}". Write the ${h}\'s name, or app/name when the page has several apps.`),p(u,{kind:h,name:g?.name??v,app:g?.app??0,problems:S},k),g&&!S.length){let A=`${g.app}/${g.name}`,C=d[E=`${h}:${A}`]??(d[E]={elements:new Set,blocks:new Set});C.elements.add(k);let D=w?.kind==="block"?w.id:m?.getAttribute(_.block);D&&C.blocks.add(D)}}}let b=Object.fromEntries(Object.entries(d).map(([k,x])=>[k,{markers:x.elements.size,blocks:[...x.blocks]}]));return{nodes:t,usage:b,elements:r,keysOf:o}}i(gt,"buildStructure");var vn=i((e,n,t)=>`${e}:${n}/${t}`,"usageKey");function xn(e){let n=e.getBoundingClientRect();return`${Math.round(n.width)} \\xD7 ${Math.round(n.height)}`}i(xn,"sizeOf");function yt(e,n,t){let r=xn(n);if(e.kind==="container"||e.kind==="block")return{kind:e.kind,name:e.id??"",...e.label?{label:e.label}:{},size:r};let o=t.usage[vn(e.kind,e.app??0,e.name??"")];return{kind:e.kind,name:e.name??"",...o&&o.markers>1?{note:`1 of ${o.markers}`}:{},size:r}}i(yt,"describeNode");var kt=["color-bg","color-fg","color-muted","color-border","color-accent","color-danger","radius","font","font-mono","color-bg-sunken","color-fg-weak","color-border-strong","color-hover","color-active","color-selected","color-warning","color-success"],bt="\'Inter Variable\', ui-sans-serif, system-ui, sans-serif",wt="\'Geist Mono Variable\', ui-monospace, monospace",xe={light:{"color-bg":"oklch(1 0 0)","color-bg-sunken":"oklch(0.973 0.005 95.1)","color-fg":"oklch(0.201 0.022 301.1)","color-fg-weak":"oklch(0.392 0.021 304.3)","color-muted":"oklch(0.485 0.022 306.3)","color-border":"oklch(0.201 0.022 301.1 / 0.12)","color-border-strong":"oklch(0.201 0.022 301.1 / 0.24)","color-accent":"oklch(0.484 0.181 298.1)","color-danger":"oklch(0.501 0.17 27.2)","color-warning":"oklch(0.501 0.1 70.3)","color-success":"oklch(0.479 0.1 151.8)","color-hover":"oklch(0.201 0.022 301.1 / 0.05)","color-active":"oklch(0.201 0.022 301.1 / 0.09)","color-selected":"oklch(0.946 0.027 304.8)",radius:"10px",font:bt,"font-mono":wt},dark:{"color-bg":"oklch(0.19 0.012 300)","color-bg-sunken":"oklch(0.157 0.009 296.9)","color-fg":"oklch(0.961 0.007 304.2)","color-fg-weak":"oklch(0.879 0.016 302.5)","color-muted":"oklch(0.835 0.018 300)","color-border":"oklch(0.343 0.025 298.2)","color-border-strong":"oklch(0.392 0.021 304.3)","color-accent":"oklch(0.845 0.085 300)","color-danger":"oklch(0.82 0.09 27)","color-warning":"oklch(0.84 0.12 69.6)","color-success":"oklch(0.8 0.12 151.9)","color-hover":"oklch(1 0 0 / 0.06)","color-active":"oklch(1 0 0 / 0.1)","color-selected":"oklch(0.565 0.194 300.3 / 0.18)",radius:"10px",font:bt,"font-mono":wt}};var Sn=/[;{}<>]|url\\(|expression\\(|@import|\\\\/i;function Et(e){let n=typeof e=="object"&&e!==null?e:{},t=n.scheme==="dark"?"dark":"light",r={...xe[t]},o=typeof n.tokens=="object"&&n.tokens!==null?n.tokens:{},l=new Set;for(let s of kt){let a=o[s];typeof a=="string"&&a.trim()!==""&&a.length<=200&&!Sn.test(a)&&(r[s]=a.trim(),l.add(s))}for(let[s,{from:a,value:d}]of Object.entries(Cn)){if(l.has(s)||!a.some(b=>l.has(b)))continue;let p=d(r);p.length<=200&&(r[s]=p)}return Object.freeze({scheme:t,tokens:Object.freeze(r)})}i(Et,"resolveTheme");var Cn={"color-bg-sunken":{from:["color-fg","color-bg"],value:i(e=>`color-mix(in srgb, ${e["color-fg"]} 4%, ${e["color-bg"]})`,"value")},"color-fg-weak":{from:["color-fg","color-bg"],value:i(e=>`color-mix(in srgb, ${e["color-fg"]} 80%, ${e["color-bg"]})`,"value")},"color-border-strong":{from:["color-fg","color-border"],value:i(e=>`color-mix(in srgb, ${e["color-fg"]} 10%, ${e["color-border"]})`,"value")},"color-hover":{from:["color-fg"],value:i(e=>`color-mix(in srgb, ${e["color-fg"]} 7%, transparent)`,"value")},"color-active":{from:["color-fg"],value:i(e=>`color-mix(in srgb, ${e["color-fg"]} 12%, transparent)`,"value")},"color-selected":{from:["color-accent"],value:i(e=>`color-mix(in srgb, ${e["color-accent"]} 14%, transparent)`,"value")}};function Se(e,n){for(let t of kt)e.setProperty(`--anfra-${t}`,n.tokens[t]);e.setProperty("color-scheme",n.scheme)}i(Se,"applyTheme");var Ce="data-anfra-layer",vt=new WeakMap,Tn="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function An(e){let n=e.querySelector(`[${Ce}]`);if(n instanceof(e.defaultView?.HTMLElement??HTMLElement))return n;let t=e.createElement("div");t.setAttribute(Ce,""),t.setAttribute("style",Tn);let r=vt.get(e);return r&&Se(t.style,r),(e.body??e.documentElement).appendChild(t),t}i(An,"layerOf");function z(e,n){let t=An(e),r=[...t.children].find(l=>l.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let o=e.createElement("div");return o.setAttribute("data-part",n),t.appendChild(o),o.attachShadow({mode:"open"})}i(z,"layerRoot");function xt(e,n){vt.set(e,n);let t=e.querySelector(`[${Ce}]`);t&&Se(t.style,n)}i(xt,"themeLayer");var St="anfra-overlay",Dn=1500,Rn="position:fixed;box-sizing:border-box;background:oklch(0.546 0.215 262.9 / 0.22);outline:1px solid oklch(0.546 0.215 262.9);outline-offset:-1px;",_n="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:oklch(0.208 0.04 265.8);color:oklch(0.984 0.003 247.9);font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px oklch(0 0 0 / 0.35);",On={kind:"color:oklch(0.711 0.035 256.8);",name:"color:oklch(0.809 0.096 251.8);font-weight:700;",label:"color:oklch(0.984 0.003 247.9);",note:"color:oklch(0.711 0.035 256.8);",size:"color:oklch(0.711 0.035 256.8);margin-left:10px;"},Ae=class Ae{constructor(n){c(this,"doc",n);c(this,"root");c(this,"shown",[]);c(this,"text",{kind:"",name:""});c(this,"timer");c(this,"reposition",i(()=>this.draw(),"reposition"));let t=z(n,"anfra"),r=t.getElementById(St);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=St,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),t.appendChild(this.root))}show(n,t){if(this.clearTimer(),this.root.isConnected||z(this.doc,"anfra").appendChild(this.root),this.shown=[...n],this.text=t,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,t,r=Dn){this.show(n,t),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(a=>{let d=a.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${Rn}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),p}),t=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let o=this.doc.defaultView?.innerHeight??0,l=t.top>=26?t.top-24:Math.max(4,t.top+4),s=Math.max(4,Math.min(t.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${_n}left:${s}px;top:${Math.min(l,o-24)}px;`);for(let a of["kind","name","label","note","size"]){let d=this.text[a];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",On[a]),p.setAttribute("data-part",a),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};i(Ae,"Overlay");var Te=Ae,Ct=new WeakMap;function re(e){let n=Ct.get(e);return n||(n=new Te(e),Ct.set(e,n)),n}i(re,"overlayFor");function oe(e){typeof e.scrollIntoView=="function"&&e.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}i(oe,"scrollTo");function Tt(e,n){let t=null,r=i(d=>d.target instanceof Element?d.target.closest(ne):null,"under"),o=i(d=>{let p=r(d);p!==t&&(t=p,n.onHover(p))},"onMove"),l=i(d=>{d.preventDefault(),d.stopPropagation();let p=r(d);p&&n.onPick(p)},"onClick"),s=i(d=>{d.key==="Escape"&&n.onCancel()},"onKey"),a={capture:!0};return e.addEventListener("mousemove",o,a),e.addEventListener("click",l,a),e.addEventListener("keydown",s,a),()=>{e.removeEventListener("mousemove",o,a),e.removeEventListener("click",l,a),e.removeEventListener("keydown",s,a)}}i(Tt,"startPick");function At(e,n){for(let t of e){if(t.key===n)return t;let r=At(t.children,n);if(r)return r}}i(At,"findNode");function Dt(e){let n=e.window,t=n.document,r=!1,o,l,s="",a,d;function p(){if(o=void 0,!!r)try{l=e.structure(),s=JSON.stringify(l.nodes),e.emit("snapshot",{apps:e.sdk.apps.map(f=>f.toInspectJSON()),structure:{nodes:l.nodes,usage:l.usage}})}catch{}}i(p,"postSnapshot");function b(){r&&o===void 0&&(o=setTimeout(p,50))}i(b,"scheduleSnapshot");function E(){let f=n.MutationObserver;if(a||typeof f!="function")return;let m=new f(()=>{if(!(!r||o!==void 0))try{JSON.stringify(e.structure().nodes)!==s&&b()}catch{}});a=m,m.observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:Object.values(_)})}i(E,"observeStructure");function k(f){let m=f!==null&&l?At(l.nodes,f):void 0,w=f!==null?l?.elements.get(f):void 0;if(!m||!w||!l){e.overlay.hide();return}e.overlay.show([w],yt(m,w,l))}i(k,"highlight");function x(f){if(!f){d?.(),d=void 0;return}if(d)return;let m=i(w=>l?.keysOf.get(w)?.[0],"keyOf");d=Tt(t,{onHover:i(w=>k(w?m(w)??null:null),"onHover"),onPick:i(w=>{let u=m(w);u!==void 0&&e.emit("picked",{node:u})},"onPick"),onCancel:i(()=>{x(!1),e.overlay.hide(),e.emit("picked",{node:null})},"onCancel")})}i(x,"setPicking");function T(f){r=f,f?(E(),p()):(a?.disconnect(),a=void 0,x(!1),e.overlay.hide(),l=void 0,s="")}i(T,"setInspecting");function R(f){if("node"in f){let m=l?.elements.get(f.node);m&&oe(m),k(f.node)}else e.sdk.apps[f.app]?.locate(f.kind,f.name);b()}i(R,"locate"),e.on("watch",f=>T(f===!0)),e.on("highlight",f=>k(f)),e.on("locate",f=>R(f)),e.on("pick",f=>x(f===!0)),e.onApp(f=>{f.subscribe(b),b()})}i(Dt,"installInspection");var De;function Rt(e,n){return De?De(e,n):!1}i(Rt,"openRowsMenu");var $n=`[${_.block}]`,Mn=\'[data-anfra-menu="off"]\',In=i(e=>({...e,children:e.children.map(n=>({...n,children:[]}))}),"bare");function _t(e,n,t=[]){for(let r of e){if(r.key===n)return[...t,r];let o=_t(r.children,n,[...t,r]);if(o)return o}}i(_t,"pathTo");var Fn=i(e=>typeof e?.closest=="function","isElement");function Ot(e){let n=e.window,t=n.document,r=[],o=new Set,l=!1,s,a=i(()=>e.body(),"ui"),d=i(()=>z(t,"anfra-ui"),"root"),p=i(u=>o.has(u)||r.some(h=>h.target===u),"offered"),b=i(()=>{let u=s;s=void 0,u?.()},"closeCurrent");function E(u){let h=Fn(u)?u.closest($n):null;return h&&!h.closest(Mn)?h:void 0}i(E,"blockOf");function k(u){let h=e.structure(),v=h.keysOf.get(u)?.[0],g=v!==void 0?_t(h.nodes,v):void 0;if(!g)return;let{x:S,y:A,width:C,height:D}=u.getBoundingClientRect();return{kind:"node",node:In(g[g.length-1]),ancestors:g.slice(0,-1).map(P=>({...P,children:[]})),rect:{x:S,y:A,width:C,height:D}}}i(k,"nodeTarget");function x(u){let h=new Map,v=[];for(let g of r){if(g.target!==u.kind)continue;let S=!0;try{S=g.when?g.when(u)!==!1:!0}catch{S=!1}if(!S)continue;let A=`frame:${g.full}:${u.kind}`;if(!g.entries){v.push({id:A,label:g.label}),h.set(A,()=>g.run(u));continue}let C=[];try{C=g.entries(u)??[]}catch{C=[]}C.forEach((D,P)=>{if(typeof D?.label!="string")return;let I=typeof D.disabled=="string"&&D.disabled?D.disabled:void 0;if(!I&&typeof D.run!="function")return;let M=`${A}:${P}`;v.push({id:M,label:D.label,...I?{disabled:I}:{}}),I||h.set(M,D.run)})}return{entries:v,run:h}}i(x,"frameEntries");async function T(u,h){let v=new Map(h.run),g=[...h.entries];if(o.has(u.kind))try{let S=await e.call("anfra.menu",u);for(let A of Array.isArray(S)?S:[]){if(typeof A?.id!="string"||typeof A.label!="string")continue;let C=`host:${A.id}:${u.kind}`;g.push({id:C,label:A.label,...typeof A.disabled=="string"?{disabled:A.disabled}:{}}),v.set(C,()=>e.call("anfra.run",{id:A.id,target:u}))}}catch{}return{entries:g,run:v}}i(T,"entriesFor");function R(u,h){let v=h.map(C=>({target:C,own:x(C)})).filter(({target:C,own:D})=>D.entries.length||o.has(C.kind));if(!v.length)return!1;u.preventDefault();let g=u,S=typeof g.clientX=="number"?g.clientX:0,A=typeof g.clientY=="number"?g.clientY:0;return(async()=>{let[C,...D]=await Promise.all([a(),...v.map(({target:M,own:ue})=>T(M,ue))]),P=D.map(M=>M.entries).filter(M=>M.length);if(!P.length)return;b();let I=C.menu(d(),{x:S,y:A,groups:P,onPick:i(M=>{let ue=D.map(J=>J.run.get(M)).find(Boolean);Promise.resolve().then(ue).catch(J=>{n.console?.error("anfra: a menu item failed:",J),$("plugin.uncaught",J)})},"onPick"),onClose:i(()=>{s===I&&(s=void 0)},"onClose")});s=I})().catch(C=>{n.console?.error("anfra: the menu failed to open:",C),$("plugin.uncaught",C)}),!0}i(R,"open");function f(){l||!(p("node")||p("rows"))||(l=!0,n.addEventListener("contextmenu",u=>{if(u.defaultPrevented||u.shiftKey)return;let h=E(u.target),v=h&&k(h);v&&R(u,[v])}))}i(f,"listen"),De=i((u,h)=>{if(u.defaultPrevented||u.shiftKey)return!1;let v=E(u.target),g=v?k(v):void 0,S=g?{...h,node:g}:h;return R(u,g?[S,g]:[S])},"rowsOpener"),e.on("menu",u=>{let h=u?.kinds;o=new Set((Array.isArray(h)?h:[]).filter(v=>v==="node"||v==="rows")),f()});let m=i(u=>h=>{try{return u(h)}catch(v){throw $("plugin.uncaught",v),v}},"reported");async function w(u,h){let v=await a();b();let g=i(()=>{},"close");return g=h(v,i(()=>{s===g&&(s=void 0);try{u.onClose?.()}catch{}},"onClose")),s=g,{close:g}}return i(w,"show"),{addItem(u,h){r.push({...h,full:`${u}.${h.id}`}),f()},modal:i(u=>w(u,(h,v)=>h.modal(d(),{title:u.title,size:u.size,mount:m(u.mount),onClose:v})),"modal"),popover:i(u=>w(u,(h,v)=>{let{anchor:g}=u,S;if("kind"in g){let A=e.structure().elements.get(g.node.key);S=i(()=>{if(!A?.isConnected)return;let{x:C,y:D,width:P,height:I}=A.getBoundingClientRect();return{x:C,y:D,width:P,height:I}},"rect")}else S=i(()=>({x:g.x,y:g.y,width:0,height:0}),"rect");return h.popover(d(),{anchor:S,side:u.side,mount:m(u.mount),dismiss:u.dismiss,closeButton:u.closeButton,onClose:v})}),"popover")}}i(Ot,"installContentUi");var $t=["ctrl","alt","shift","meta"];function Mt(e){if(typeof e!="string")return;let n=e.split("+").map(o=>o.trim().toLowerCase()).filter(Boolean),t=n.pop(),r=i(o=>$t.includes(o),"isModifier");if(!(!t||r(t)||!n.every(r)))return[...$t.filter(o=>n.includes(o)),t].join("+")}i(Mt,"normalizeShortcut");function It(e){let n=e;return!n||typeof n.tagName!="string"?!1:n.isContentEditable===!0||["INPUT","TEXTAREA","SELECT"].includes(n.tagName.toUpperCase())}i(It,"isTyping");function Ft(e){let n=typeof e.code=="string"?e.code:"",t=/^Key[A-Z]$/.test(n)?n.slice(3).toLowerCase():/^Digit[0-9]$/.test(n)?n.slice(5):(e.key??"").toLowerCase();return[e.ctrlKey&&"ctrl",e.altKey&&"alt",e.shiftKey&&"shift",e.metaKey&&"meta",t].filter(Boolean).join("+")}i(Ft,"eventShortcut");function Re(e,n,t,r,o){if(r in n||e.has(r))throw new y(`Plugin \'${r}\' can\'t add \'${r}\' to a ${t}: it already has one.`);e.set(r,o)}i(Re,"addExtension");function ie(e,n){return n?.forEach((t,r)=>{let o=!1,l;Object.defineProperty(e,r,{configurable:!0,enumerable:!1,get(){return o||(l=t(e),o=!0),l}})}),e}i(ie,"applyExtensions");var Nn="anfra.body",_e="__anfraBodyExports",Pn={DataAppError:O,ValidationError:y,invalidRequest:Z,forbidden:ot,connectionFailed:it,callFailed:V,fromHttpStatus:st,hasErrorCode:nt,isDataAppError:Q};function Qn(e,n){let t=e,r=e.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(_e)}] = __anfraBody; })();`,(e.document.head??e.document.documentElement).appendChild(r),r.remove();let o=t[_e];if(delete t[_e],!o)throw new y("The host sent a plugin body that did not run.");return o.default??o}i(Qn,"runBody");function Oe(e,n){if(typeof e=="function")return fe(e,n);if(typeof e!="object"||e===null)return e;let t=new Map;return new Proxy(e,{get(r,o,l){let s=Reflect.get(r,o,l);if(typeof s!="function"||typeof o!="string")return s;let a=t.get(o);if(a?.of===s)return a.fn;let d=fe(s.bind(r),`${n}_${j(o)}`);return t.set(o,{of:s,fn:d}),d}})}i(Oe,"namedMember");function $e(e,n,t){let{window:r,sdk:o,endpoint:l}=n,s;return{plugin:e,window:r,sdk:o,errors:Pn,get overlay(){return re(r.document)},structure:i(()=>gt(r.document,o.apps),"structure"),queryRequest(a){let d=o.apps.find(p=>p.queries[a?.name]===a);if(!d)throw new y(`Query \'${String(a?.name)}\' belongs to no app.`,a?.name);return d.requestFor(a)},call:i((a,d,p)=>l.call(a,d??null,p),"call"),emit:i((a,d)=>l.emit(`${e}.${a}`,d??null),"emit"),handle(a,d){n.handlers.set(`${e}.${a}`,d)},on(a,d){let p=`${e}.${a}`;n.listeners.has(p)||n.listeners.set(p,new Set),n.listeners.get(p).add(d)},onApp(a){n.appListeners.add(a),o.apps.forEach(d=>a(d))},provide(a){if(e in o)throw new y(`Plugin \'${e}\' can\'t add a member Anfra already has.`);Object.defineProperty(o,e,{value:Oe(a,j(e)),enumerable:!0})},provideOnQuery:i(a=>Re(o.extensions.query,t.Query.prototype,"query",e,d=>Oe(a(d),j(e))),"provideOnQuery"),provideOnControl:i(a=>Re(o.extensions.control,t.Control.prototype,"control",e,d=>Oe(a(d),j(e))),"provideOnControl"),layer:i(()=>z(r.document,e),"layer"),menuItem:i(a=>n.contentUi?.addItem(e,a),"menuItem"),modal:i(a=>n.contentUi.modal(a),"modal"),popover:i(a=>n.contentUi.popover(a),"popover"),body(){return s??(s=l.call(Nn,{plugin:e}).then(a=>Qn(r,a)).catch(a=>{throw s=void 0,a})),s}}}i($e,"createKernel");var Me=class Me extends L{constructor(t,r,o){super(r);c(this,"kind","query");c(this,"name");c(this,"declaration");c(this,"dataset");c(this,"app");c(this,"_state","idle");c(this,"runFailed",!1);c(this,"_result");c(this,"_error");c(this,"_page",1);c(this,"_sort",[]);c(this,"lastRunSignature");c(this,"lastPageRows",0);c(this,"controller");if(!o.aql?.trim())throw new y(`Query \'${t}\' declares no AQL.`,t);let{pageSize:l}=o;if(l!==void 0&&!(Number.isInteger(l)&&l>=1))throw new y(`Query \'${t}\' declares pageSize ${l}; it must be a whole number of at least 1.`,t);this.name=t,this.app=r,this.declaration=o,this.dataset=r.datasetIndex(o.dataset,t)}locate(){return this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(t){this._sort=[...t],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0?!1:this._result.meta.hasMore??this.lastPageRows>=this.pageSize}signature(){let t=this.app.mappingsTo(this.name).map(r=>({field:r.field,aggregation:r.aggregation,condition:r.from.condition})).sort((r,o)=>r.field.localeCompare(o.field)||JSON.stringify(r).localeCompare(JSON.stringify(o)));return JSON.stringify({declaration:this.declaration,conditions:t,selection:this.app.selectionConditionsFor(this.name,"pending"),selectionExpression:this.app.selectionExpressionFor(this.name,"pending"),sort:this._sort,timezone:this.app.timezone,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}shouldRun(t=!1){return t||this.runFailed||this.lastRunSignature===void 0||this.isDirty}abort(){this.controller?.abort()}async fetchMore(){try{if(this.pageSize===void 0)throw new y(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);if(!this.hasMore)return;this._page+=1,await this.app.fetchPage(this)}catch(t){throw q(t,"fetch_more"),t}}menu(t,r,o={}){return this.app.menu(this,t,Array.isArray(r)?r:[r],o.fields,o.measure)}select(t,r={}){this.app.select(this,Array.isArray(t)?t:[t],r.fields)}get selectedRows(){let{selection:t}=this.app;if(t?.source!==this.name)return[];let r=this._result?.rows;if(!r)return t.rows;let o=i(s=>JSON.stringify(t.fields.map(a=>s[a]??null)),"key"),l=new Set(t.rows.map(o));return r.filter(s=>l.has(o(s)))}markExecuting(){this._state="executing",this._error=void 0,this.notify()}markSuccess(t,r,o){if(this._state="success",this._error=void 0,o||(this.runFailed=!1),this.lastRunSignature=r,this.lastPageRows=t.rows.length,o&&this._result){let l=[...this._result.rows,...t.rows];this._result={...t,rows:l,meta:{...t.meta,numRows:l.length}}}else this._result=t;this.notify()}markError(t,r=!1){r||(this.runFailed=!0),this._state="error",this._error=t,this.notify()}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this.declaration}};i(Me,"Query");var N=Me;var Ie=class Ie{constructor(n,t,r,o){c(this,"kind","control");c(this,"from");c(this,"to");c(this,"field");c(this,"aggregation");this.from=n,this.to=t,this.field=r,this.aggregation=o}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};i(Ie,"Mapping");var se=Ie,Fe=class Fe{constructor(n,t){c(this,"kind","crossFilter");c(this,"from");c(this,"to");this.from=n,this.to=t}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};i(Fe,"CrossFilter");var ae=Fe;var Ne=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function Ln(e,n){let t=e.length+1,r=n.length+1,o=Array.from({length:r},(l,s)=>s);for(let l=1;l<t;l++){let s=[l];for(let a=1;a<r;a++)s[a]=Math.min(o[a]+1,s[a-1]+1,o[a-1]+(e[l-1]===n[a-1]?0:1));o=s}return o[r-1]}i(Ln,"editDistance");function Bn(e,n){let t,r=1/0;n.forEach(l=>{let s=Ln(e.toLowerCase(),l.toLowerCase());s<r&&(r=s,t=l)});let o=Math.max(2,Math.floor(e.length/3));return r<=o?t:void 0}i(Bn,"suggest");function B(e,n,t){let r=Bn(n,t);return r?`${e} Did you mean \'${r}\'?`:e}i(B,"withSuggestion");var Pe=class Pe{constructor(n){c(this,"descriptor");c(this,"fields",new Map);c(this,"references");this.descriptor=n,n.data_models.forEach(t=>{t.fields.forEach(r=>{let o=String(t.name);this.fields.set(`${o}.${r.name}`,{modelName:o,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(t=>{this.fields.set(t.name,{fieldName:t.name,isMetric:!0,type:t.type,label:t.label??t.name})}),this.references=[...this.fields.keys()]}resolve(n,t){let r=this.fields.get(n);if(r)return r;throw new y(B(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),t)}};i(Pe,"DatasetIndex");var le=Pe;function Nt(e,n,t){let r=e[n];if(r)return r;throw new y(B(`Unknown dataset \'${n}\'.`,n,Object.keys(e)),t)}i(Nt,"resolveDataset");function Pt(e,n){if(!Ne.includes(e))throw new y(B(`Invalid filter aggregation \'${e}\'.`,e,[...Ne]),n)}i(Pt,"assertValidFilterAggregation");function Qt(e,n,t){if(!n)throw new y(`A ${t} needs a name.`);for(let r of e)if(r===n)throw new y(`\'${n}\' is already declared in this app.`,n)}i(Qt,"assertUniqueName");function zn(e,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:e.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...e.aggregation?{aggregation:e.aggregation}:{}}}i(zn,"toFilter");function Kn(e,n){if(n?.operator!=="transform_date_drill")return;let t=n.values?.[0];if(typeof t!="string")return;let r=t.replace(/^datetrunc\\s+/,"");return{field:e.field,grain:r}}i(Kn,"toDateDrill");function jn(e,n){let t=n.columns??[],r=(n.values??[]).map(l=>{let s={};return t.forEach((a,d)=>{s[a.name]=l[d]}),s}),{pageSize:o}=e;return{columns:t,rows:r,meta:{...o!==void 0?{page:n.meta?.page??e.page,pageSize:n.meta?.pageSize??o,...n.meta?.hasMore!==void 0?{hasMore:n.meta.hasMore}:{}}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}i(jn,"toResult");function de(e,n,t,r){let o=n.map(d=>zn(d,d.from.appliedCondition)).filter(d=>d!==void 0),l=n.map(d=>Kn(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=t.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),a=t.expression?[{expr:t.expression}]:[];return{dataset:e.dataset.descriptor.name,aql:e.declaration.aql,input:{filters:[...o,...s],conditions:a,sorts:e.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:l},...r.timezone?{timezone:r.timezone}:{}}}i(de,"buildQuery");function qn(e,n,t,r){return{...de(e,n,t,r),...e.pageSize!==void 0?{page:e.page,pageSize:e.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}i(qn,"buildRequest");function Vn(e,n){let t=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return t?`${t} - ${e.name}`:e.name}i(Vn,"defaultExportFilename");function Lt(e,n,t,r,o){let l=o.format??"csv",s=l==="csv"?{bom:!0,...o.formatOptions}:o.formatOptions;return{...de(e,n,t,r),format:l,...s?{formatOptions:s}:{},filename:o.filename?.trim()||Vn(e,r.title)}}i(Lt,"buildExportRequest");async function Qe(e,n,t,r,o){let l=qn(e,n,t,r),s=await r.backend.submitQuery(l,o);return jn(e,s)}i(Qe,"runQuery");function Un(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(n==="number"&&typeof e=="string")return Hn(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new RangeError(`Cannot express ${e} in AQL.`);return Math.abs(e)>=1e21?BigInt(e).toString():String(e)}return JSON.stringify(e).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}i(Un,"literal");function Bt(e,n,t){return n===null?`is(${e}, null)`:`${e} is ${Un(n,t)}`}i(Bt,"equals");var Gn=new Set(["NaN","Infinity","-Infinity"]),Jn=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function Hn(e){let n=Jn.exec(e);if(!n)throw Gn.has(e)?new RangeError(`Cannot express ${e} in AQL.`):new TypeError(`${JSON.stringify(e)} is not a number: a number is a string in JSON\'s number syntax.`);let[,t,r,o="",l]=n;if(l===void 0)return e;let s=r+o,a=r.length+Number(l),d;return a<=0?d=`0.${"0".repeat(-a)}${s}`:a>=s.length?d=s+"0".repeat(a-s.length):d=`${s.slice(0,a)}.${s.slice(a)}`,t+d.replace(/^0+(?=\\d)/,"")}i(Hn,"numberLiteral");function zt(e,n,t){return`${e} matches @(${n} until ${t})`}i(zt,"dateRange");function Kt(e,n){if(n.length===0)throw new RangeError(`\\`${e}\\` needs at least one operand.`);return n.length===1?n[0]:`${e}(${n.join(", ")})`}i(Kt,"combine");var jt=i(e=>Kt("and",e),"and"),qt=i(e=>Kt("or",e),"or");var Wn=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,Yn={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function Vt(e){if(typeof e!="string")return;let n=Wn.exec(e);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}i(Vt,"parseStamp");function U(e,n){let t=new Date(e),r=i(l=>String(l).padStart(2,"0"),"pad"),o=`${t.getUTCFullYear()}-${r(t.getUTCMonth()+1)}-${r(t.getUTCDate())}`;return n?`${o} ${r(t.getUTCHours())}:${r(t.getUTCMinutes())}:${r(t.getUTCSeconds())}`:o}i(U,"format");function Ut(e){return Date.UTC(e.year,e.month,e.day,e.hour,e.minute,e.second)}i(Ut,"toMs");function Le(e){let n=Vt(e);if(n)return U(Ut(n),n.hasTime)}i(Le,"normalise");function Be(e,n){let t=Vt(e);if(!t)return;let{year:r,month:o,day:l,hour:s,minute:a,second:d,hasTime:p}=t;return U(n==="year"?Date.UTC(r+1,o,l,s,a,d):n==="quarter"?Date.UTC(r,o+3,l,s,a,d):n==="month"?Date.UTC(r,o+1,l,s,a,d):Ut(t)+Yn[n],p)}i(Be,"addGrain");function Gt(e){if(e?.startsWith("datetrunc "))return e.slice(10)}i(Gt,"grainOf");function Xn(e){let n=new Set;return e.filter(t=>{let r=`${typeof t}:${String(t)}`;return n.has(r)?!1:(n.add(r),!0)})}i(Xn,"distinct");function Zn(e,n){let t=e.map(Le);if(t.some(o=>o===void 0))return!1;let r=t.slice().sort();for(let o=1;o<r.length;o+=1)if(Be(r[o-1],n)!==r[o])return!1;return!0}i(Zn,"isContiguous");function er(e,n,t){let r=n.map(Le);if(r.some(d=>d===void 0))return;let o=r.slice().sort(),l=o[0],s=Be(o[o.length-1],t);if(!s)return;let a=Zn(n,t);return{condition:{field:e,operator:"matches",values:[`${l} until ${s}`]},admits:a?n.length:Number.POSITIVE_INFINITY,lossy:!a}}i(er,"dateRange");function tr(e,n,t){let r=t.filter(a=>a!=null),o=Xn(r);if(!o.length)return{condition:{field:e,operator:"is_null",values:[]},admits:1,lossy:!1};let l=r.length!==t.length,s=Gt(n);if(s){let a=er(e,o,s);if(a)return{...a,lossy:a.lossy||l}}return{condition:{field:e,operator:"is",values:o},admits:o.length,lossy:l}}i(tr,"deriveOne");function Jt(e){return e.modelId?`${e.modelId}.${e.fieldName}`:e.fieldName}i(Jt,"fieldReferenceOf");function nr(e,n,t,r){try{let o=t.map(l=>jt(n.map(s=>{let a=e.get(s),d=Jt(a),p=l[s]??null,b=Gt(r[d]);if(b&&typeof p=="string"){let E=Le(p),k=Be(p,b);if(E&&k)return zt(d,E,k)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Bt(d,p,a.semantic_type)})));return qt(o)}catch{return}}i(nr,"selectionExpression");function ze(e,n,t,r={}){let o=e.result?.columns??[],l=new Map(o.map(f=>[f.name,f]));t?.forEach(f=>{let m=l.get(f);if(m){if(m.adhoc)throw new y(`Query \'${e.name}\' cannot cross-filter on \'${f}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,e.name);if(m.isMeasure)throw new y(`Query \'${e.name}\' cannot cross-filter on \'${f}\': it is a measure, and a selection conditions dimensions only.`,e.name);return}throw new y(B(`Query \'${e.name}\' has no column \'${f}\' in its last result.`,f,[...l.keys()]),e.name)});let s=o.filter(f=>!f.isMeasure),a=s.filter(f=>!f.adhoc).map(f=>f.name),d=t?[...t]:a;if(!n.length||!d.length)return;let p=[],b=1,E=!t&&a.length!==s.length,k=!1;d.forEach(f=>{let m=l.get(f),w=Jt(m),u=tr(w,r[w],n.map(h=>h[f]));p.push(u.condition),b*=u.admits,k=k||u.lossy});let x=new Set(n.map(f=>JSON.stringify(d.map(m=>f[m]??null))));b>x.size&&(k=!0);let T=p.sort((f,m)=>f.field.localeCompare(m.field)),R={source:e.name,rows:[...n],fields:d};if(k){let f=nr(l,d,n,r);if(f)return{...R,conditions:[],expression:f,lossy:E}}return{...R,conditions:T,lossy:E||k}}i(ze,"deriveSelection");var Ke=Object.freeze([]);function je(e){return e instanceof Error&&e.name==="AbortError"}i(je,"isAbort");function Ht(e,n){return e.controller!==n}i(Ht,"superseded");function rr(e){return{name:e.name,code:e.code,scope:e.scope,message:e.message,...e.entity?{entity:e.entity}:{},...typeof e.status=="number"?{status:e.status}:{},...e.requestId?{requestId:e.requestId}:{},...e.stack?{stack:e.stack}:{}}}i(rr,"inspectError");function or(e){let{result:n}=e;return{state:e.state,isDirty:e.isDirty,page:e.page,hasMore:e.hasMore,columns:n?n.columns.map(t=>({...t})):[],rowCount:n?.meta.numRows??0,selectedRowCount:e.selectedRows.length,signature:e.signature(),...e.error?{error:rr(e.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}i(or,"inspectQuery");function ir(e){let{options:n}=e;return{kind:e.kind,condition:{...e.condition},...e.appliedCondition?{appliedCondition:{...e.appliedCondition}}:{},isDirty:e.isDirty,...n?{options:[...n]}:{}}}i(ir,"inspectControl");function Wt(e){return{source:e.source,fields:[...e.fields],rowCount:e.rows.length,conditions:e.conditions.map(n=>({...n})),...e.expression?{expression:e.expression}:{},lossy:e.lossy}}i(Wt,"inspectSelection");function Yt(e){return e?JSON.stringify({source:e.source,conditions:e.conditions,expression:e.expression}):"none"}i(Yt,"selectionKey");function qe(e,n,t="The query failed."){return Q(e)?e.about(n):(console.error(`anfra: \'${n}\' failed; the app is told only that it failed.`,e),new O({code:"call_failed",scope:"server",message:t,entity:n,cause:e}))}i(qe,"toDataAppError");var Ve=class Ve extends L{constructor(t,r,o,l,s){super();c(this,"extensions",s);c(this,"title");c(this,"_timezone");c(this,"datasets");c(this,"backend");c(this,"features");c(this,"_queries",new Map);c(this,"_controls",new Map);c(this,"_mappings",[]);c(this,"_crossFilters",[]);c(this,"_selection");c(this,"_appliedSelection");c(this,"selectionCommitted",!1);c(this,"index",0);this.title=t.title,this._timezone=t.timezone,this.datasets=r,this.backend=o,this.features=l}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(t,r){this.assertNameFree(t,"query");let o=ie(new N(t,this,r),this.extensions?.query);return this._queries.set(t,o),this.notify(),o}createFilter(t,r){this.assertNameFree(t,"filter");let o=r.dataset?this.datasetIndex(r.dataset,t):this.soleDataset(t,r.field),l=ie(new ee(t,this,r,o,this.backend),this.extensions?.control);return this._controls.set(t,l),this.notify(),l}createDateDrill(t,r={}){if(this.features?.dateDrill===!1)throw new y(`Date drill \'${t}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,t);this.assertNameFree(t,"date drill control");let o=ie(new te(t,this,r),this.extensions?.control);return this._controls.set(t,o),this.notify(),o}mapControl(t,r,o){if(!(t instanceof F))throw new y("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(this._controls.get(t.name)!==t)throw new y(`Control \'${t.name}\' belongs to a different app.`,t.name);if(this._queries.get(r.name)!==r)throw new y(`Query \'${r.name}\' belongs to a different app.`,r.name);o.aggregation&&Pt(o.aggregation,t.name);let l=new se(t,r,o.field,o.aggregation);if(this._mappings.some(s=>s.id===l.id))throw new y(`Mapping \'${l.id}\' is already declared.`,t.name);return this.assertAcyclic(l),this._mappings.push(l),this.notify(),l}mapCrossFilter(t,r){if(!(t instanceof N)||!(r instanceof N))throw new y("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(this._queries.get(t.name)!==t)throw new y(`Query \'${t.name}\' belongs to a different app.`,t.name);if(this._queries.get(r.name)!==r)throw new y(`Query \'${r.name}\' belongs to a different app.`,r.name);if(t===r)throw new y(`Query \'${t.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,t.name);if(t.declaration.dataset!==r.declaration.dataset)throw new y(`Cross-filter \'${t.name}\' -> \'${r.name}\' spans two datasets (\'${t.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,t.name);let o=new ae(t,r);if(this._crossFilters.some(l=>l.id===o.id))throw new y(`Cross-filter \'${o.id}\' is already declared.`,t.name);return this._crossFilters.push(o),this.notify(),o}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(t){this._timezone=t,this.notify()}get timezone(){return this._timezone}datasetIndex(t,r){return Nt(this.datasets,t,r)}mappingsTo(t){return this._mappings.filter(r=>r.to.name===t)}selectionExpressionFor(t,r){return this.selectionFor(t,r)?.expression}selectionFor(t,r){let o=r==="pending"?this._selection:this._appliedSelection;return!o||o.source===t?void 0:this._crossFilters.some(s=>s.from.name===o.source&&s.to.name===t)?o:void 0}selectionConditionsFor(t,r){let o=r==="pending"?this._selection:this._appliedSelection;return!o||o.source===t?Ke:this._crossFilters.some(s=>s.from.name===o.source&&s.to.name===t)?o.conditions:Ke}drillTransformations(t){let r={};return this._mappings.forEach(o=>{if(o.to!==t)return;let l=o.from.appliedCondition;if(l?.operator!=="transform_date_drill")return;let[s]=l.values??[];typeof s=="string"&&(r[o.field]=s)}),r}menu(t,r,o,l,s){if(this._queries.get(t.name)!==t)throw new y(`Query \'${t.name}\' belongs to a different app.`,t.name);if(s!==void 0){let d=t.result?.columns??[],p=d.find(b=>b.name===s);if(!p?.isMeasure)throw new y(p?`Query \'${t.name}\' can\'t open a menu on \'${s}\' as its measure: it is a dimension.`:B(`Query \'${t.name}\' has no measure \'${s}\' in its last result.`,s,d.filter(b=>b.isMeasure).map(b=>b.name)),t.name)}let a=ze(t,o,l,this.drillTransformations(t));return Rt(r,{kind:"rows",app:this.index,query:t.name,rows:[...o],fields:a?.fields?[...a.fields]:[],...s!==void 0?{measure:s}:{},conditions:a?.conditions?[...a.conditions]:[],...a?.expression?{expression:a.expression}:{}})}requestFor(t){if(this._queries.get(t.name)!==t)throw new y(`Query \'${t.name}\' belongs to a different app.`,t.name);return de(t,this.mappingsTo(t.name),{conditions:this.selectionConditionsFor(t.name,"applied"),expression:this.selectionExpressionFor(t.name,"applied")},{timezone:this._timezone})}select(t,r,o){if(this._queries.get(t.name)!==t)throw new y(`Query \'${t.name}\' belongs to a different app.`,t.name);let l=ze(t,r,o,this.drillTransformations(t));l?.lossy&&console.warn(`[anfra-sdk] The selection in \'${t.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=l,this.notify()}get hasChanges(){return[...this._controls.values()].some(t=>t.isDirty)||this.isSelectionDirty}get isSelectionDirty(){return this.selectionCommitted?Yt(this._selection)!==Yt(this._appliedSelection):!1}async execute(t={}){let r=[...this._queries.values()].filter(a=>a.shouldRun(t.force));this._controls.forEach(a=>a.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(a=>{a.controller?.abort(),a.resetPage()});let o={backend:this.backend,timezone:this._timezone,bustCache:t.bustCache},l=[],s=[];return await Promise.all(r.map(async a=>{let d=new AbortController;a.controller=d;let p=a.signature();a.markExecuting();try{let b=await Qe(a,this.mappingsTo(a.name),{conditions:this.selectionConditionsFor(a.name,"applied"),expression:this.selectionExpressionFor(a.name,"applied")},o,d.signal);if(Ht(a,d))return;a.markSuccess(b,p,!1),l.push(a.name)}catch(b){if(Ht(a,d)||je(b))return;let E=qe(b,a.name);a.markError(E),$("call.query",E),s.push(a.name)}finally{a.controller===d&&(a.controller=void 0)}})),{succeeded:l,failed:s}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(t=>t.abort())}async fetchPage(t){let r=new AbortController;t.controller=r;let o=t.signature();t.markExecuting();try{let l=await Qe(t,this.mappingsTo(t.name),{conditions:this.selectionConditionsFor(t.name,"applied"),expression:this.selectionExpressionFor(t.name,"applied")},{backend:this.backend,timezone:this._timezone},r.signal);t.markSuccess(l,o,!0)}catch(l){if(t.rewindPage(),je(l))return;let s=qe(l,t.name);throw t.markError(s,!0),s}finally{t.controller===r&&(t.controller=void 0)}}async exportQuery(t,r,o){let l=Lt(t,this.mappingsTo(t.name),{conditions:this.selectionConditionsFor(t.name,"applied"),expression:this.selectionExpressionFor(t.name,"applied")},{backend:this.backend,timezone:this._timezone,title:this.title},r);try{return await o(l,r.signal??new AbortController().signal)}catch(s){throw je(s)?s:qe(s,t.name,"The export failed.")}}toJSON(){let t=i(r=>Object.fromEntries([...this._controls.entries()].filter(([,o])=>o.kind===r).map(([o,l])=>[o,l.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,o])=>[r,o.toJSON()])),filters:t("filter"),dateDrills:t("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([t,r])=>[t,or(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([t,r])=>[t,ir(r)])),...this._selection?{selection:Wt(this._selection)}:{},...this._appliedSelection?{appliedSelection:Wt(this._appliedSelection)}:{}}}locate(t,r){let o=globalThis.document;if(!o)return!1;let l=ht(o,t,this.index,r);return l.length?(oe(l[0]),re(o).flash(l,{kind:t,name:r,...l.length>1?{note:`in ${l.length} places`}:{}}),!0):!1}assertNameFree(t,r){Qt([...this._queries.keys(),...this._controls.keys()],t,r)}soleDataset(t,r){if(!r)return;let o=Object.keys(this.datasets);if(o.length===1)return this.datasets[o[0]];throw new y(o.length?`Filter \'${t}\' names a field but the environment has ${o.length} datasets. Say which one: ${o.join(", ")}.`:`Filter \'${t}\' names a field but the environment has no datasets.`,t)}assertAcyclic(t){let r=[...this._mappings,t],o=new Map;r.forEach(d=>{let p=d.from.name;o.set(p,[...o.get(p)??[],d.to.name])});let l=new Set,s=new Set,a=i(d=>{if(l.has(d))return!0;if(s.has(d))return!1;l.add(d);let p=(o.get(d)??[]).some(a);return l.delete(d),s.add(d),p},"walk");if([...o.keys()].some(a))throw new y(`Mapping \'${t.id}\' would make the app\'s mappings cyclic.`,t.from.name)}};i(Ve,"App");var ce=Ve;var Xt="0.20.0";var He=class He{constructor(){c(this,"current",{scheme:"light",tokens:xe.light});c(this,"listeners",new Set)}get scheme(){return this.current.scheme}get tokens(){return this.current.tokens}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}set(n){this.current=n,this.listeners.forEach(t=>{try{t(n)}catch{}})}};i(He,"HostTheme");var Ue=He,We=class We{constructor(n){c(this,"list");this.list=Object.freeze(n.map(({name:t,version:r})=>Object.freeze({name:t,version:r})))}has(n){return this.list.some(t=>t.name===n)}version(n){return this.list.find(t=>t.name===n)?.version}};i(We,"InstalledPlugins");var Ge=We,ar=Xt,Ye=class Ye{constructor(n){c(this,"version",ar);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"plugins");c(this,"theme",new Ue);c(this,"gates");c(this,"deprecatedFeatures");c(this,"extensions",{query:new Map,control:new Map});if(!n?.datasets)throw new y("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new y("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new y("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([t,r])=>[t,new le(r)])),this.backend=n.backend,this.gates=Object.freeze({...n.features}),this.plugins=new Ge(n.plugins??[])}get features(){return this.deprecatedFeatures||(console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has(\'export\'), Anfra.plugins.has(\'render\') or Anfra.plugins.has(\'lineage\') instead."),this.deprecatedFeatures=Object.freeze({...this.gates,export:this.plugins.has("export"),render:this.plugins.has("render"),lineage:this.plugins.has("lineage")})),this.deprecatedFeatures}createApp(n={}){let t=new ce(n,this.indices,this.backend,this.gates,this.extensions);return t.index=this._apps.length,this._apps.push(t),t}get apps(){return this._apps}};i(Ye,"Sdk");var Je=Ye;function Zt(e){return new Je(e)}i(Zt,"createSdk");var G="Anfra";function en(e,n=globalThis){let t=n[G],r=G in n;return n[G]=e,()=>{r?n[G]=t:delete n[G]}}i(en,"installSandbox");function tn(e,n=[]){let t=e.document.getElementById(Xe);if(!t?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(t.textContent),o=i(m=>e.parent.postMessage(m,r.hostOrigin),"post"),l=new Map,s=new Map,a=dt(o,{answer:i(async(m,w,u)=>{let h=l.get(m);if(!h)throw Z(`Nothing in this frame answers \'${m}\'.`);return h(w,u)},"answer"),hidden:i((m,w)=>{e.console?.error(`anfra: \'${m}\' failed; the host is told only that the call failed.`,w),$("plugin.uncaught",w)},"hidden"),event:i((m,w)=>{s.get(m)?.forEach(u=>{try{u(w)}catch{}})},"event")}),d=i(m=>m.source===e.parent||!!r.hostOrigin&&r.hostOrigin!=="null"&&m.origin===r.hostOrigin,"fromHost");e.addEventListener("message",m=>{d(m)&&a.receive(m.data)});let p={submitQuery:i((m,w)=>a.call("core.submitQuery",m,w).then(u=>(u.debug?.executedAt&&(u.debug.executedAt=new Date(u.debug.executedAt)),u)),"submitQuery"),fieldSuggestions:i((m,w)=>a.call("core.fieldSuggestions",m,w),"fieldSuggestions")},b=Zt({datasets:r.datasets,user:r.user,backend:p,plugins:r.plugins??[]}),E=new Set,k=b.createApp.bind(b);b.createApp=m=>{let w=k(m);return E.forEach(u=>{try{u(w)}catch{}}),w};let x={window:e,sdk:b,endpoint:a,handlers:l,listeners:s,appListeners:E},T=$e("anfra",x,{Query:N,Control:F});ct(T,e,r.captureConsole===!0),Dt(T),x.contentUi=Ot(T),T.on("theme",m=>{let w=Et(m);xt(e.document,w),b.theme.set(w)});let R=new Set,f=!1;T.on("shortcuts",m=>{R=new Set((Array.isArray(m)?m:[]).map(Mt).filter(w=>!!w)),!(f||!R.size)&&(f=!0,e.addEventListener("keydown",w=>{if(w.defaultPrevented||w.repeat||It(w.target))return;let u=Ft(w);R.has(u)&&(w.preventDefault(),T.emit("shortcut",u))}))});for(let[m,w]of n)if(typeof w=="function")try{w($e(m,x,{Query:N,Control:F}))}catch(u){e.console?.error(`anfra: plugin \'${m}\' failed to set up:`,u),$("plugin.uncaught",u)}en(b,e),o({type:"anfra:ready"})}i(tn,"bootstrap");return dn(lr);})();\n';
|
|
33
|
+
var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var z=Object.defineProperty;var bn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var vn=Object.prototype.hasOwnProperty;var kn=(t,n,e)=>n in t?z(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var i=(t,n)=>z(t,"name",{value:n,configurable:!0});var En=(t,n)=>{for(var e in n)z(t,e,{get:n[e],enumerable:!0})},xn=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of wn(n))!vn.call(t,o)&&o!==e&&z(t,o,{get:()=>n[o],enumerable:!(r=bn(n,o))||r.enumerable});return t};var Sn=t=>xn(z({},"__esModule",{value:!0}),t);var c=(t,n,e)=>kn(t,typeof n!="symbol"?n+"":n,e);var Tr={};En(Tr,{bootstrap:()=>yn});var ut="anfra-provision";function V(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9]+/g,"_").toLowerCase()}i(V,"snakeCase");var ee=new WeakMap;function U(t,n){typeof t=="object"&&t!==null&&ee.set(t,n)}i(U,"tagCall");function pt(t){for(let n=t,e=0;typeof n=="object"&&n!==null&&e<5;n=n.cause,e+=1){let r=ee.get(n);if(r)return r}}i(pt,"callOf");function Ee(t,n){let e=ee.get(t);return e&&ee.set(n,e),n}i(Ee,"copyCallTag");function xe(t,n){return function(...e){let r=t.apply(this,e);return r&&typeof r.then=="function"?r.then(void 0,o=>{throw U(o,n),o}):r}}i(xe,"namedCall");var Se=2e3,Cn=4e3;function te(t,n){return t.length<=n?t:`${t.slice(0,n)}\\u2026 (truncated)`}i(te,"truncate");function ft(t,n){let e=n,r=typeof e=="object"&&e!==null,o={kind:t,message:te(r&&typeof e.message=="string"?e.message:String(n),Se),at:new Date().toISOString()};if(!r)return o;for(let s of["code","scope","requestId","entity"]){let a=e[s];typeof a=="string"&&(o[s]=a)}return!t.startsWith("call.")&&typeof e.stack=="string"&&(o.stack=te(e.stack,Cn)),o}i(ft,"describeError");function Ce(t,n=()=>{},e=Date.now){let r=e(),o=0,s=0,a,l=i(()=>{a=void 0;let d=s;if(s=0,d>0)try{n(d)}catch{}},"flush");return{take(){let d=e();return d-r>=6e4&&(a!==void 0&&clearTimeout(a),l(),r=d,o=0),o<t?(o+=1,!0):(s+=1,a===void 0&&(a=setTimeout(l,Math.max(0,r+6e4-d))),!1)},dispose(){a!==void 0&&clearTimeout(a),l()}}}i(Ce,"createBudget");var mt={query_invalid:"user",query_failed:"user",forbidden:"user",unauthenticated:"user",invalid_request:"client",declaration_invalid:"client",connection_failed:"server",call_failed:"server",internal_server_error:"server"},ne=class ne extends Error{constructor(e){super(e.message);c(this,"code");c(this,"scope");c(this,"status");c(this,"details");c(this,"context");c(this,"requestId");c(this,"entity");c(this,"cause");this.name=new.target.name,this.code=e.code,this.scope=e.scope,e.status!==void 0&&(this.status=e.status),e.details!==void 0&&(this.details=e.details),e.context!==void 0&&(this.context=e.context),e.requestId!==void 0&&(this.requestId=e.requestId),e.entity!==void 0&&(this.entity=e.entity),e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}about(e){return this.entity===e?this:Ee(this,new ne({...Tn(this),entity:e}))}};i(ne,"DataAppError");var $=ne,re=class re extends ${constructor(n,e){super({code:"declaration_invalid",scope:"client",message:n,entity:e})}about(n){return this.entity===n?this:Ee(this,new re(this.message,n))}};i(re,"ValidationError");var m=re;function L(t){if(t instanceof $)return!0;let n=t;return n instanceof Error&&(n.name==="DataAppError"||n.name==="ValidationError")&&typeof n.code=="string"}i(L,"isDataAppError");function ht(t,n){return L(t)&&t.code===n}i(ht,"hasErrorCode");function gt(t){if(!Array.isArray(t))return;let n=t.filter(e=>typeof e?.text=="string").map(e=>typeof e.step=="string"?{step:e.step,text:e.text}:{text:e.text});return n.length?n:void 0}i(gt,"contextOf");function oe(t,n){return new $({code:"invalid_request",scope:"client",message:t,entity:n})}i(oe,"invalidRequest");function yt(t,n){return new $({code:"forbidden",scope:"user",message:t,entity:n})}i(yt,"forbidden");function bt(t,n){return new $({code:"connection_failed",scope:"server",message:t,status:n})}i(bt,"connectionFailed");function G(t){return new $({code:"call_failed",scope:"server",message:"The call failed.",cause:t})}i(G,"callFailed");function wt(t,n,e={}){let{refused:r="invalid_request",requestId:o,entity:s}=e,a;return t===void 0||t===0?a="connection_failed":t===401?a="unauthenticated":t===403?a="forbidden":t>=400&&t<500?a=r:a="internal_server_error",new $({code:a,scope:Dn(a,t),message:n,status:t||void 0,requestId:o,entity:s})}i(wt,"fromHttpStatus");function Dn(t,n){return t in mt?mt[t]:n!==void 0&&n>=400&&n<500?"user":"server"}i(Dn,"scopeOf");function vt(t){return t==="user"||t==="client"||t==="server"?t:"server"}i(vt,"toScope");function Tn(t){return{code:t.code,scope:t.scope,message:t.message,status:t.status,details:t.details,context:t.context,requestId:t.requestId,entity:t.entity,cause:t.cause}}i(Tn,"fieldsOf");function ie(){let t=new Error("Aborted");return t.name="AbortError",t}i(ie,"abortError");function An(t){return t?.name==="AbortError"}i(An,"isAbortError");function _n(t){return{app:t.app,query:t.query,...t.id!==void 0&&{id:t.id},...t.variant!==void 0&&{variant:t.variant}}}i(_n,"copyStamp");var Rn=new Set(["query_invalid","validation_failed","invalid_request","result_too_large","page_too_large"]);function De(t,n){let e=typeof n.code=="string"&&n.code?n.code:"call_failed",r={name:t,code:e,scope:vt(n.scope),message:typeof n.message=="string"&&n.message?n.message:"The call failed."};typeof n.status=="number"&&(r.status=n.status),n.details!==void 0&&Rn.has(e)&&(r.details=n.details);let o=gt(n.context);return o&&(r.context=o),typeof n.requestId=="string"&&(r.requestId=n.requestId),r}i(De,"crossing");function On(t){return L(t)?De(t.name,t):De("DataAppError",G())}i(On,"toBridgeError");function $n(t){if(!t||typeof t!="object")return G();let n=De(t.name,t);return n.name==="ValidationError"&&n.code==="declaration_invalid"?new m(n.message):new $({code:n.code,scope:n.scope,message:n.message,status:n.status,details:n.details,context:n.context,requestId:n.requestId})}i($n,"fromBridgeError");function kt(t,n){let e=new Map,r=new Map,o=1,s=i((a,l,d,p)=>{let g=new AbortController;r.set(a,g),Promise.resolve().then(()=>n.answer(l,d,g.signal,p)).then(k=>{g.signal.aborted||t({type:"anfra:result",id:a,ok:!0,result:k})}).catch(k=>{if(g.signal.aborted||An(k))return;let y=On(k);if(!L(k))if(n.hidden)try{n.hidden(l,k)}catch{}else console.error(`anfra: \'${l}\' failed; the other side is told only that the call failed.`,k);t({type:"anfra:result",id:a,ok:!1,error:y})}).finally(()=>{r.get(a)===g&&r.delete(a)})},"answer");return{call(a,l,d,p){return new Promise((g,k)=>{if(d?.aborted){k(ie());return}let y=o++;e.set(y,{resolve:g,reject:k}),d?.addEventListener("abort",()=>{e.delete(y)&&(t({type:"anfra:cancel",id:y}),k(ie()))},{once:!0}),t({type:"anfra:call",id:y,name:a,request:l,...p?{stamp:_n(p)}:{}})})},emit(a,l){t({type:"anfra:event",name:a,payload:l})},receive(a){switch(a?.type){case"anfra:call":return s(a.id,a.name,a.request,a.stamp),!0;case"anfra:result":{let l=e.get(a.id);return l&&(e.delete(a.id),a.ok?l.resolve(a.result):l.reject($n(a.error))),!0}case"anfra:cancel":return r.get(a.id)?.abort(),r.delete(a.id),!0;case"anfra:event":return n.event(a.name,a.payload),!0;default:return!1}},close(a){r.forEach(l=>l.abort()),r.clear(),e.forEach(({reject:l})=>l(a)),e.clear()}}}i(kt,"createEndpoint");var Ae;function I(t,n){try{Ae?.(t,n)}catch{}}i(I,"reportError");var Te=120;function In(t){if(typeof t=="string")return t;if(t instanceof Error)return`${t.name}: ${t.message}`;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}i(In,"textOf");function Et(t,n,e,r=Date.now){let o=i(k=>y=>n.console?.warn(`anfra: ${y} ${k} over the ${Te} a minute a frame sends were not sent to the host.`),"dropped"),s=Ce(Te,o("runtime errors"),r),a=Ce(Te,o("console lines"),r);Ae=i((k,y)=>{s.take()&&t.emit("error",ft(k,y))},"reporter");let l=i(k=>I("app.uncaught",k.error??k.message),"onError"),d=i(k=>{let y=pt(k.reason);I(y?`call.${y}`:"app.uncaught",k.reason)},"onRejection");n.addEventListener("error",l),n.addEventListener("unhandledrejection",d);let p=n.console,g={};if(e&&p)for(let k of["error","warn"]){let y=p[k];g[k]=y,p[k]=(...x)=>{if(y.apply(p,x),!(typeof x[0]=="string"&&x[0].startsWith("anfra:")))try{a.take()&&t.emit("console",{level:k,message:te(x.map(In).join(" "),Se),at:new Date().toISOString()})}catch{}}}return()=>{Ae=void 0,s.dispose(),a.dispose(),n.removeEventListener("error",l),n.removeEventListener("unhandledrejection",d);for(let[k,y]of Object.entries(g))p[k]=y}}i(Et,"installReporting");var _e=class _e{constructor(n){c(this,"listeners",new Set);c(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>{try{n()}catch(e){console.error("anfra: a subscribe() listener threw; the queries carry on.",e),I("app.listener",e)}}),this.parent?.notifyChange()}notify(){this.notifyChange()}};i(_e,"Observable");var P=_e;function J(t,n,e=Object.keys(n)){let r={...t};return e.forEach(o=>{if(!(o in n))return;let s=n[o];s===void 0?delete r[o]:r[o]=s}),r}i(J,"withChanges");var xt=["year","quarter","month","week","day","hour","minute"];function Fn(t,n){if(!xt.includes(n))throw new m(`Invalid grain \'${n}\'. Expected one of: ${xt.join(", ")}.`,t)}i(Fn,"assertGrain");function Re(t,n){return n?(Fn(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}i(Re,"drillCondition");function Mn(t){let n=t.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}i(Mn,"inferType");function Qn(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}i(Qn,"sameCondition");var Oe=class Oe extends P{constructor(e,r,o){super(r);c(this,"name");c(this,"app");c(this,"pending");c(this,"applied");c(this,"initial");c(this,"removed",!1);this.name=e,this.app=r,this.initial=o,this.pending=o}locate(){return this.assertLive(),this.app.locate("control",this.name)}get isRemoved(){return this.removed}remove(){this.assertLive(),this.app.removeEntity(this)}assertLive(){if(this.removed)throw new m(`Control \'${this.name}\' was removed from its app; it can\'t be used any more.`,this.name)}markRemoved(){this.removed=!0,this.dropInFlight()}dropInFlight(){}redefault(e,r){this.initial=e,r&&(this.pending=e)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!Qn(this.pending,this.applied)}setCondition(e){this.assertLive(),this.pending=e,this.notify()}reset(){this.assertLive(),this.setCondition(this.initial)}commit(){this.applied=this.pending}};i(Oe,"Control");var Q=Oe,W=class W extends Q{constructor(e,r,o,s,a){super(e,r,o.default??{operator:"is",values:[]});c(this,"kind","filter");c(this,"_declaration");c(this,"resolution");c(this,"backend");c(this,"loadedOptions");c(this,"loading",new Set);this.backend=a,this.resolution=W.resolve(e,o,s),this._declaration=o,this.assertValues(this.condition.values??[]),this.assertValues(o.options??[])}static resolve(e,r,o){if(r.field){if(!o)throw new m(`Filter \'${e}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,e);let s=o.resolve(r.field,e);return{resolved:s,datasetName:o.descriptor.name,type:r.type??Mn(s.type)}}if(!r.type)throw new m(`Filter \'${e}\' is a manual filter, so it needs a \\`type\\`.`,e);return{type:r.type}}get declaration(){return this._declaration}get type(){return this.resolution.type}setCondition(e){this.assertLive(),this.assertValues(e.values??[]),super.setCondition(e)}update(e){this.assertLive();let r=J(this._declaration,e),o=this._declaration,s=["field","dataset","type"].some(p=>r[p]!==o[p]),a=s?W.resolve(this.name,r,this.app.filterDataset(this.name,r)):this.resolution,l=r.default??{operator:"is",values:[]},d=i(p=>p.values??[],"values");this.assertValuesOf(a.type,d(l)),this.assertValuesOf(a.type,r.options??[]),s||this.assertValuesOf(a.type,d(this.condition)),this._declaration=r,this.resolution=a,this.redefault(l,s),s&&(this.loadedOptions=void 0,this.dropInFlight()),this.notify()}dropInFlight(){this.loading.forEach(e=>e.abort()),this.loading.clear()}assertValues(e){this.assertValuesOf(this.type,e)}assertValuesOf(e,r){if(e!=="number")return;let o=r.find(s=>typeof s=="number");if(o!==void 0)throw new m(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(o))}, not ${String(o)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolution.resolved!==void 0}get options(){return this.loadedOptions??this._declaration.options??[]}async loadOptions(e,r=new AbortController().signal){this.assertLive();let{resolved:o,datasetName:s}=this.resolution,a=o?.modelName;if(!o||!a||!this.backend||!s)return this.options;let l=new AbortController,d=i(()=>l.abort(),"follow");r.aborted?l.abort():r.addEventListener("abort",d,{once:!0}),this.loading.add(l);try{let p=await this.backend.fieldSuggestions({dataset:s,model:a,field:o.fieldName,q:e??""},l.signal).catch(g=>{throw U(g,"load_options"),g});if(l.signal.aborted&&!this.loading.has(l))throw ie();return this.loadedOptions=[...p??[]],this.notify(),this.loadedOptions}finally{this.loading.delete(l),r.removeEventListener("abort",d)}}toJSON(){return this._declaration}};i(W,"Filter");var se=W,$e=class $e extends Q{constructor(e,r,o={}){super(e,r,Re(e,o.default));c(this,"kind","dateDrill");c(this,"_declaration");this._declaration=o}get declaration(){return this._declaration}update(e){this.assertLive();let r=J(this._declaration,e),o=Re(this.name,r.default);this._declaration=r,this.redefault(o,!1),this.notify()}setGrain(e){this.assertLive(),this.setCondition(Re(this.name,e))}toJSON(){return this._declaration}};i($e,"DateDrillControl");var ae=$e;function St(t){t.handle("execute",async()=>{let n=await Promise.all(t.sdk.apps.map(e=>e.refresh()));return{succeeded:n.flatMap(e=>e.succeeded),failed:n.flatMap(e=>e.failed)}})}i(St,"installCore");var _={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},le=`[${_.container}],[${_.block}],[${_.query}],[${_.control}]`;function Ct(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}i(Ct,"parseRef");var Dt=i(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Tt(t,n,e,r){let o=n==="query"?_.query:_.control;return[...t.querySelectorAll(`[${o}]`)].filter(s=>Dt(s.getAttribute(o)).some(a=>{let l=Ct(a);return l?.app===e&&l.name===r}))}i(Tt,"markersFor");var Nn=i((t,n,e)=>{let r=t[e.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,e.name):!1},"hasEntity");function At(t,n){var k;let e=[],r=new Map,o=new Map,s=new Map,a=new Map,l={container:new Set,block:new Set},d={},p=i((y,x,D)=>{let R=y?s.get(y).children:e,f=y?`${s.get(y).key}.`:"",h={...x,key:`${f}${R.length}`,children:[]};return R.push(h),r.set(h.key,D),o.set(D,[...o.get(D)??[],h.key]),h},"place");for(let y of t.querySelectorAll(le)){let x=y.parentElement?.closest(le)??null,D=y.getAttribute(_.container),R=y.getAttribute(_.block),f=y.getAttribute(_.label)??void 0,h=x&&(a.get(x)==="block"?x:x.closest(`[${_.block}]`)),w;if(D!==null||R!==null){let u=D!==null?"container":"block",b=(D??R??"").trim(),v=[];D!==null&&R!==null&&v.push("This element is marked as a container and as a block. It counts as a container."),b?l[u].has(b)?v.push(`Another ${u} already has the id "${b}".`):l[u].add(b):v.push(`This ${u} has no id.`),h&&v.push(`A block can\'t hold a ${u}. This one is inside the block "${h.getAttribute(_.block)}".`),w=p(x,{kind:u,id:b,...f!==void 0?{label:f}:{},problems:v},y),s.set(y,w),a.set(y,u)}let S=w?y:x;for(let u of["query","control"])for(let b of Dt(y.getAttribute(u==="query"?_.query:_.control))){let v=Ct(b),E=[];if(v?Nn(n,u,v)||E.push(n[v.app]?`No ${u} is called "${v.name}" in app ${v.app}.`:`The page has no app ${v.app}.`):E.push(`Can\'t read "${b}". Write the ${u}\'s name, or app/name when the page has several apps.`),p(S,{kind:u,name:v?.name??b,app:v?.app??0,problems:E},y),v&&!E.length){let C=`${v.app}/${v.name}`,T=d[k=`${u}:${C}`]??(d[k]={elements:new Set,blocks:new Set});T.elements.add(y);let O=w?.kind==="block"?w.id:h?.getAttribute(_.block);O&&T.blocks.add(O)}}}let g=Object.fromEntries(Object.entries(d).map(([y,x])=>[y,{markers:x.elements.size,blocks:[...x.blocks]}]));return{nodes:e,usage:g,elements:r,keysOf:o}}i(At,"buildStructure");var Ln=i((t,n,e)=>`${t}:${n}/${e}`,"usageKey");function Pn(t){let n=t.getBoundingClientRect();return`${Math.round(n.width)} \\xD7 ${Math.round(n.height)}`}i(Pn,"sizeOf");function _t(t,n,e){let r=Pn(n);if(t.kind==="container"||t.kind==="block")return{kind:t.kind,name:t.id??"",...t.label?{label:t.label}:{},size:r};let o=e.usage[Ln(t.kind,t.app??0,t.name??"")];return{kind:t.kind,name:t.name??"",...o&&o.markers>1?{note:`1 of ${o.markers}`}:{},size:r}}i(_t,"describeNode");var $t=["color-bg","color-fg","color-muted","color-border","color-accent","color-danger","radius","font","font-mono","color-bg-sunken","color-fg-weak","color-border-strong","color-hover","color-active","color-selected","color-warning","color-success"],Rt="\'Inter Variable\', ui-sans-serif, system-ui, sans-serif",Ot="\'Geist Mono Variable\', ui-monospace, monospace",Ie={light:{"color-bg":"oklch(1 0 0)","color-bg-sunken":"oklch(0.973 0.005 95.1)","color-fg":"oklch(0.201 0.022 301.1)","color-fg-weak":"oklch(0.392 0.021 304.3)","color-muted":"oklch(0.485 0.022 306.3)","color-border":"oklch(0.201 0.022 301.1 / 0.12)","color-border-strong":"oklch(0.201 0.022 301.1 / 0.24)","color-accent":"oklch(0.484 0.181 298.1)","color-danger":"oklch(0.501 0.17 27.2)","color-warning":"oklch(0.501 0.1 70.3)","color-success":"oklch(0.479 0.1 151.8)","color-hover":"oklch(0.201 0.022 301.1 / 0.05)","color-active":"oklch(0.201 0.022 301.1 / 0.09)","color-selected":"oklch(0.946 0.027 304.8)",radius:"10px",font:Rt,"font-mono":Ot},dark:{"color-bg":"oklch(0.19 0.012 300)","color-bg-sunken":"oklch(0.157 0.009 296.9)","color-fg":"oklch(0.961 0.007 304.2)","color-fg-weak":"oklch(0.879 0.016 302.5)","color-muted":"oklch(0.835 0.018 300)","color-border":"oklch(0.343 0.025 298.2)","color-border-strong":"oklch(0.392 0.021 304.3)","color-accent":"oklch(0.845 0.085 300)","color-danger":"oklch(0.82 0.09 27)","color-warning":"oklch(0.84 0.12 69.6)","color-success":"oklch(0.8 0.12 151.9)","color-hover":"oklch(1 0 0 / 0.06)","color-active":"oklch(1 0 0 / 0.1)","color-selected":"oklch(0.565 0.194 300.3 / 0.18)",radius:"10px",font:Rt,"font-mono":Ot}};var Bn=/[;{}<>]|url\\(|expression\\(|@import|\\\\/i;function It(t){let n=typeof t=="object"&&t!==null?t:{},e=n.scheme==="dark"?"dark":"light",r={...Ie[e]},o=typeof n.tokens=="object"&&n.tokens!==null?n.tokens:{},s=new Set;for(let a of $t){let l=o[a];typeof l=="string"&&l.trim()!==""&&l.length<=200&&!Bn.test(l)&&(r[a]=l.trim(),s.add(a))}for(let[a,{from:l,value:d}]of Object.entries(qn)){if(s.has(a)||!l.some(g=>s.has(g)))continue;let p=d(r);p.length<=200&&(r[a]=p)}return Object.freeze({scheme:e,tokens:Object.freeze(r)})}i(It,"resolveTheme");var qn={"color-bg-sunken":{from:["color-fg","color-bg"],value:i(t=>`color-mix(in srgb, ${t["color-fg"]} 4%, ${t["color-bg"]})`,"value")},"color-fg-weak":{from:["color-fg","color-bg"],value:i(t=>`color-mix(in srgb, ${t["color-fg"]} 80%, ${t["color-bg"]})`,"value")},"color-border-strong":{from:["color-fg","color-border"],value:i(t=>`color-mix(in srgb, ${t["color-fg"]} 10%, ${t["color-border"]})`,"value")},"color-hover":{from:["color-fg"],value:i(t=>`color-mix(in srgb, ${t["color-fg"]} 7%, transparent)`,"value")},"color-active":{from:["color-fg"],value:i(t=>`color-mix(in srgb, ${t["color-fg"]} 12%, transparent)`,"value")},"color-selected":{from:["color-accent"],value:i(t=>`color-mix(in srgb, ${t["color-accent"]} 14%, transparent)`,"value")}};function Fe(t,n){for(let e of $t)t.setProperty(`--anfra-${e}`,n.tokens[e]);t.setProperty("color-scheme",n.scheme)}i(Fe,"applyTheme");var Me="data-anfra-layer",Ft=new WeakMap,Kn="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function jn(t){let n=t.querySelector(`[${Me}]`);if(n instanceof(t.defaultView?.HTMLElement??HTMLElement))return n;let e=t.createElement("div");e.setAttribute(Me,""),e.setAttribute("style",Kn);let r=Ft.get(t);return r&&Fe(e.style,r),(t.body??t.documentElement).appendChild(e),e}i(jn,"layerOf");function K(t,n){let e=jn(t),r=[...e.children].find(s=>s.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let o=t.createElement("div");return o.setAttribute("data-part",n),e.appendChild(o),o.attachShadow({mode:"open"})}i(K,"layerRoot");function Mt(t,n){Ft.set(t,n);let e=t.querySelector(`[${Me}]`);e&&Fe(e.style,n)}i(Mt,"themeLayer");var Qt="anfra-overlay",zn=1500,Vn="position:fixed;box-sizing:border-box;background:oklch(0.546 0.215 262.9 / 0.22);outline:1px solid oklch(0.546 0.215 262.9);outline-offset:-1px;",Un="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:oklch(0.208 0.04 265.8);color:oklch(0.984 0.003 247.9);font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px oklch(0 0 0 / 0.35);",Gn={kind:"color:oklch(0.711 0.035 256.8);",name:"color:oklch(0.809 0.096 251.8);font-weight:700;",label:"color:oklch(0.984 0.003 247.9);",note:"color:oklch(0.711 0.035 256.8);",size:"color:oklch(0.711 0.035 256.8);margin-left:10px;"},Ne=class Ne{constructor(n){c(this,"doc",n);c(this,"root");c(this,"shown",[]);c(this,"text",{kind:"",name:""});c(this,"timer");c(this,"reposition",i(()=>this.draw(),"reposition"));let e=K(n,"anfra"),r=e.getElementById(Qt);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=Qt,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),e.appendChild(this.root))}show(n,e){if(this.clearTimer(),this.root.isConnected||K(this.doc,"anfra").appendChild(this.root),this.shown=[...n],this.text=e,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,e,r=zn){this.show(n,e),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(l=>{let d=l.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${Vn}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),p}),e=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let o=this.doc.defaultView?.innerHeight??0,s=e.top>=26?e.top-24:Math.max(4,e.top+4),a=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Un}left:${a}px;top:${Math.min(s,o-24)}px;`);for(let l of["kind","name","label","note","size"]){let d=this.text[l];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",Gn[l]),p.setAttribute("data-part",l),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};i(Ne,"Overlay");var Qe=Ne,Nt=new WeakMap;function de(t){let n=Nt.get(t);return n||(n=new Qe(t),Nt.set(t,n)),n}i(de,"overlayFor");function ce(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}i(ce,"scrollTo");function Lt(t,n){let e=null,r=i(d=>d.target instanceof Element?d.target.closest(le):null,"under"),o=i(d=>{let p=r(d);p!==e&&(e=p,n.onHover(p))},"onMove"),s=i(d=>{d.preventDefault(),d.stopPropagation();let p=r(d);p&&n.onPick(p)},"onClick"),a=i(d=>{d.key==="Escape"&&n.onCancel()},"onKey"),l={capture:!0};return t.addEventListener("mousemove",o,l),t.addEventListener("click",s,l),t.addEventListener("keydown",a,l),()=>{t.removeEventListener("mousemove",o,l),t.removeEventListener("click",s,l),t.removeEventListener("keydown",a,l)}}i(Lt,"startPick");function Pt(t,n){for(let e of t){if(e.key===n)return e;let r=Pt(e.children,n);if(r)return r}}i(Pt,"findNode");function Bt(t){let n=t.window,e=n.document,r=!1,o,s,a="",l,d;function p(){if(o=void 0,!!r)try{s=t.structure(),a=JSON.stringify(s.nodes),t.emit("snapshot",{apps:t.sdk.apps.map(f=>f.toInspectJSON()),structure:{nodes:s.nodes,usage:s.usage}})}catch{}}i(p,"postSnapshot");function g(){r&&o===void 0&&(o=setTimeout(p,50))}i(g,"scheduleSnapshot");function k(){let f=n.MutationObserver;if(l||typeof f!="function")return;let h=new f(()=>{if(!(!r||o!==void 0))try{JSON.stringify(t.structure().nodes)!==a&&g()}catch{}});l=h,h.observe(e.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:Object.values(_)})}i(k,"observeStructure");function y(f){let h=f!==null&&s?Pt(s.nodes,f):void 0,w=f!==null?s?.elements.get(f):void 0;if(!h||!w||!s){t.overlay.hide();return}t.overlay.show([w],_t(h,w,s))}i(y,"highlight");function x(f){if(!f){d?.(),d=void 0;return}if(d)return;let h=i(w=>s?.keysOf.get(w)?.[0],"keyOf");d=Lt(e,{onHover:i(w=>y(w?h(w)??null:null),"onHover"),onPick:i(w=>{let S=h(w);S!==void 0&&t.emit("picked",{node:S})},"onPick"),onCancel:i(()=>{x(!1),t.overlay.hide(),t.emit("picked",{node:null})},"onCancel")})}i(x,"setPicking");function D(f){r=f,f?(k(),p()):(l?.disconnect(),l=void 0,x(!1),t.overlay.hide(),s=void 0,a="")}i(D,"setInspecting");function R(f){if("node"in f){let h=s?.elements.get(f.node);h&&ce(h),y(f.node)}else t.sdk.apps[f.app]?.locate(f.kind,f.name);g()}i(R,"locate"),t.on("watch",f=>D(f===!0)),t.on("highlight",f=>y(f)),t.on("locate",f=>R(f)),t.on("pick",f=>x(f===!0)),t.onApp(f=>{f.subscribe(g),g()})}i(Bt,"installInspection");var Le;function qt(t,n){return Le?Le(t,n):!1}i(qt,"openRowsMenu");var Jn=`[${_.block}]`,Wn=\'[data-anfra-menu="off"]\',Hn=i(t=>({...t,children:t.children.map(n=>({...n,children:[]}))}),"bare");function Kt(t,n,e=[]){for(let r of t){if(r.key===n)return[...e,r];let o=Kt(r.children,n,[...e,r]);if(o)return o}}i(Kt,"pathTo");var Yn=i(t=>typeof t?.closest=="function","isElement");function jt(t){let n=t.window,e=n.document,r=[],o=new Set,s=!1,a,l,d=i(()=>t.body(),"ui"),p=i(()=>K(e,"anfra-ui"),"root"),g=i(u=>o.has(u)||r.some(b=>b.target===u),"offered"),k=i(()=>{let u=a;a=void 0,l=void 0,u?.()},"closeCurrent");function y(u){let b=Yn(u)?u.closest(Jn):null;return b&&!b.closest(Wn)?b:void 0}i(y,"blockOf");function x(u){let b=t.structure(),v=b.keysOf.get(u)?.[0],E=v!==void 0?Kt(b.nodes,v):void 0;if(!E)return;let{x:C,y:T,width:O,height:A}=u.getBoundingClientRect();return{kind:"node",node:Hn(E[E.length-1]),ancestors:E.slice(0,-1).map(M=>({...M,children:[]})),rect:{x:C,y:T,width:O,height:A}}}i(x,"nodeTarget");function D(u){let b=new Map,v=[];for(let E of r){if(E.target!==u.kind)continue;let C=!0;try{C=E.when?E.when(u)!==!1:!0}catch{C=!1}if(!C)continue;let T=`frame:${E.full}:${u.kind}`;if(!E.entries){v.push({id:T,label:E.label}),b.set(T,()=>E.run(u));continue}let O=[];try{O=E.entries(u)??[]}catch{O=[]}O.forEach((A,M)=>{if(typeof A?.label!="string")return;let N=typeof A.disabled=="string"&&A.disabled?A.disabled:void 0;if(!N&&typeof A.run!="function")return;let j=`${T}:${M}`;v.push({id:j,label:A.label,...N?{disabled:N}:{}}),N||b.set(j,A.run)})}return{entries:v,run:b}}i(D,"frameEntries");async function R(u,b){let v=new Map(b.run),E=[...b.entries];if(o.has(u.kind))try{let C=await t.call("anfra.menu",u);for(let T of Array.isArray(C)?C:[]){if(typeof T?.id!="string"||typeof T.label!="string")continue;let O=`host:${T.id}:${u.kind}`;E.push({id:O,label:T.label,...typeof T.disabled=="string"?{disabled:T.disabled}:{}}),v.set(O,()=>t.call("anfra.run",{id:T.id,target:u}))}}catch{}return{entries:E,run:v}}i(R,"entriesFor");function f(u,b,v){let E=b.map(A=>({target:A,own:D(A)})).filter(({target:A,own:M})=>M.entries.length||o.has(A.kind));if(!E.length)return!1;u.preventDefault();let C=u,T=typeof C.clientX=="number"?C.clientX:0,O=typeof C.clientY=="number"?C.clientY:0;return(async()=>{let[A,...M]=await Promise.all([d(),...E.map(({target:q,own:ke})=>R(q,ke))]),N=M.map(q=>q.entries).filter(q=>q.length);if(!N.length)return;k();let j=A.menu(p(),{x:T,y:O,groups:N,onPick:i(q=>{let ke=M.map(Z=>Z.run.get(q)).find(Boolean);Promise.resolve().then(ke).catch(Z=>{n.console?.error("anfra: a menu item failed:",Z),I("plugin.uncaught",Z)})},"onPick"),onClose:i(()=>{a===j&&(a=void 0)},"onClose")});a=j,l=v})().catch(A=>{n.console?.error("anfra: the menu failed to open:",A),I("plugin.uncaught",A)}),!0}i(f,"open");function h(){s||!(g("node")||g("rows"))||(s=!0,n.addEventListener("contextmenu",u=>{if(u.defaultPrevented||u.shiftKey)return;let b=y(u.target),v=b&&x(b);v&&f(u,[v])}))}i(h,"listen"),Le=i((u,b)=>{if(u.defaultPrevented||u.shiftKey)return!1;let v=y(u.target),E=v?x(v):void 0,C=E?{...b,node:E}:b;return f(u,E?[C,E]:[C],{app:b.app,query:b.query})},"rowsOpener"),t.onApp(u=>u.onRemoved(b=>{b.kind==="query"&&l?.app===u.index&&l.query===b.name&&k()})),t.on("menu",u=>{let b=u?.kinds;o=new Set((Array.isArray(b)?b:[]).filter(v=>v==="node"||v==="rows")),h()});let w=i(u=>b=>{try{return u(b)}catch(v){throw I("plugin.uncaught",v),v}},"reported");async function S(u,b){let v=await d();k();let E=i(()=>{},"close");return E=b(v,i(()=>{a===E&&(a=void 0);try{u.onClose?.()}catch{}},"onClose")),a=E,l=u.about?{app:u.about.app,query:u.about.query}:void 0,{close:E}}return i(S,"show"),{addItem(u,b){r.push({...b,full:`${u}.${b.id}`}),h()},modal:i(u=>S(u,(b,v)=>b.modal(p(),{title:u.title,size:u.size,mount:w(u.mount),onClose:v})),"modal"),popover:i(u=>S(u,(b,v)=>{let{anchor:E}=u,C;if("kind"in E){let T=t.structure().elements.get(E.node.key);C=i(()=>{if(!T?.isConnected)return;let{x:O,y:A,width:M,height:N}=T.getBoundingClientRect();return{x:O,y:A,width:M,height:N}},"rect")}else C=i(()=>({x:E.x,y:E.y,width:0,height:0}),"rect");return b.popover(p(),{anchor:C,side:u.side,mount:w(u.mount),dismiss:u.dismiss,closeButton:u.closeButton,onClose:v})}),"popover")}}i(jt,"installContentUi");var zt=["ctrl","alt","shift","meta"];function Vt(t){if(typeof t!="string")return;let n=t.split("+").map(o=>o.trim().toLowerCase()).filter(Boolean),e=n.pop(),r=i(o=>zt.includes(o),"isModifier");if(!(!e||r(e)||!n.every(r)))return[...zt.filter(o=>n.includes(o)),e].join("+")}i(Vt,"normalizeShortcut");function Ut(t){let n=t;return!n||typeof n.tagName!="string"?!1:n.isContentEditable===!0||["INPUT","TEXTAREA","SELECT"].includes(n.tagName.toUpperCase())}i(Ut,"isTyping");function Gt(t){let n=typeof t.code=="string"?t.code:"",e=/^Key[A-Z]$/.test(n)?n.slice(3).toLowerCase():/^Digit[0-9]$/.test(n)?n.slice(5):(t.key??"").toLowerCase();return[t.ctrlKey&&"ctrl",t.altKey&&"alt",t.shiftKey&&"shift",t.metaKey&&"meta",e].filter(Boolean).join("+")}i(Gt,"eventShortcut");function Pe(t,n,e,r,o){if(r in n||t.has(r))throw new m(`Plugin \'${r}\' can\'t add \'${r}\' to a ${e}: it already has one.`);t.set(r,o)}i(Pe,"addExtension");function ue(t,n){return n?.forEach((e,r)=>{let o=!1,s;Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){return o||(s=e(t),o=!0),s}})}),t}i(ue,"applyExtensions");var Xn="anfra.body",Be="__anfraBodyExports",Zn={DataAppError:$,ValidationError:m,invalidRequest:oe,forbidden:yt,connectionFailed:bt,callFailed:G,fromHttpStatus:wt,hasErrorCode:ht,isDataAppError:L};function er(t,n){let e=t,r=t.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(Be)}] = __anfraBody; })();`,(t.document.head??t.document.documentElement).appendChild(r),r.remove();let o=e[Be];if(delete e[Be],!o)throw new m("The host sent a plugin body that did not run.");return o.default??o}i(er,"runBody");function qe(t,n){if(typeof t=="function")return xe(t,n);if(typeof t!="object"||t===null)return t;let e=new Map;return new Proxy(t,{get(r,o,s){let a=Reflect.get(r,o,s);if(typeof a!="function"||typeof o!="string")return a;let l=e.get(o);if(l?.of===a)return l.fn;let d=xe(a.bind(r),`${n}_${V(o)}`);return e.set(o,{of:a,fn:d}),d}})}i(qe,"namedMember");function tr(t,{app:n,query:e,variant:r}){let o=t.apps[n]?.queries??{},s=Object.hasOwn(o,e)?o[e]?.id:void 0;return{app:n,query:e,...s!==void 0&&{id:s},...r!==void 0&&{variant:r}}}i(tr,"withQueryId");function pe(t,n,e){let{window:r,sdk:o,endpoint:s}=n,a;return{plugin:t,window:r,sdk:o,errors:Zn,get overlay(){return de(r.document)},structure:i(()=>At(r.document,o.apps),"structure"),queryRequest(l){let d=o.apps.find(p=>p.queries[l?.name]===l);if(!d)throw new m(`Query \'${String(l?.name)}\' belongs to no app.`,l?.name);return d.requestFor(l)},call:i((l,d,p,g)=>s.call(l,d??null,p,g&&tr(o,g)),"call"),emit:i((l,d)=>s.emit(`${t}.${l}`,d??null),"emit"),handle(l,d){n.handlers.set(`${t}.${l}`,d)},on(l,d){let p=`${t}.${l}`;n.listeners.has(p)||n.listeners.set(p,new Set),n.listeners.get(p).add(d)},onApp(l){n.appListeners.add(l),o.apps.forEach(d=>l(d))},provide(l){if(t in o)throw new m(`Plugin \'${t}\' can\'t add a member Anfra already has.`);Object.defineProperty(o,t,{value:qe(l,V(t)),enumerable:!0})},provideOnQuery:i(l=>Pe(o.extensions.query,e.Query.prototype,"query",t,d=>qe(l(d),V(t))),"provideOnQuery"),provideOnControl:i(l=>Pe(o.extensions.control,e.Control.prototype,"control",t,d=>qe(l(d),V(t))),"provideOnControl"),layer:i(()=>K(r.document,t),"layer"),menuItem:i(l=>n.contentUi?.addItem(t,l),"menuItem"),modal:i(l=>n.contentUi.modal(l),"modal"),popover:i(l=>n.contentUi.popover(l),"popover"),body(){return a??(a=s.call(Xn,{plugin:t}).then(l=>er(r,l)).catch(l=>{throw a=void 0,l})),a}}}i(pe,"createKernel");var Ke=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function nr(t,n){let e=t.length+1,r=n.length+1,o=Array.from({length:r},(s,a)=>a);for(let s=1;s<e;s++){let a=[s];for(let l=1;l<r;l++)a[l]=Math.min(o[l]+1,a[l-1]+1,o[l-1]+(t[s-1]===n[l-1]?0:1));o=a}return o[r-1]}i(nr,"editDistance");function je(t,n){let e,r=1/0;n.forEach(s=>{let a=nr(t.toLowerCase(),s.toLowerCase());a<r&&(r=a,e=s)});let o=Math.max(2,Math.floor(t.length/3));return r<=o?e:void 0}i(je,"suggest");function B(t,n,e){let r=je(n,e);return r?`${t} Did you mean \'${r}\'?`:t}i(B,"withSuggestion");var Ve=class Ve{constructor(n){c(this,"descriptor");c(this,"fields",new Map);c(this,"references");this.descriptor=n,n.data_models.forEach(e=>{e.fields.forEach(r=>{let o=String(e.name);this.fields.set(`${o}.${r.name}`,{modelName:o,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(e=>{this.fields.set(e.name,{fieldName:e.name,isMetric:!0,type:e.type,label:e.label??e.name})}),this.references=[...this.fields.keys()]}resolve(n,e){let r=this.fields.get(n);if(r)return r;throw new m(B(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};i(Ve,"DatasetIndex");var fe=Ve;function Jt(t,n,e){let r=t[n];if(r)return r;throw new m(B(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}i(Jt,"resolveDataset");function Wt(t,n){if(!Ke.includes(t))throw new m(B(`Invalid filter aggregation \'${t}\'.`,t,[...Ke]),n)}i(Wt,"assertValidFilterAggregation");function Ht(t,n,e){if(!n)throw new m(`A ${e} needs a name.`);for(let r of t)if(r===n)throw new m(`\'${n}\' is already declared in this app.`,n)}i(Ht,"assertUniqueName");var rr={ns:1e-6,us:.001,\\u00B5s:.001,ms:1,s:1e3,m:6e4,h:36e5},or=168*36e5;function ir(t){if(t==="0")return 0;let n=/(\\d+(?:\\.\\d*)?|\\.\\d+)(ns|us|\xB5s|ms|s|m|h)/y,e=0,r=0;for(let o=n.exec(t);o;o=n.exec(t))e+=parseFloat(o[1])*rr[o[2]],r=n.lastIndex;return r>0&&r===t.length?e:void 0}i(ir,"parseDuration");function H(t,n,e,r){let o=JSON.stringify(e);return r==="sets"?`${t} sets ${n} to ${o}`:`${t} declares ${n} ${o}`}i(H,"gave");var ze=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];function me(t,n,e,r="declares"){if(t===void 0||ze.includes(t))return;let o=`${H(n,e,t,r)}.`,s=typeof t=="string"?je(t.trim(),[...ze]):void 0;if(s)throw new m(`${o} Did you mean ${JSON.stringify(s)}?`);let a=ze.map(l=>JSON.stringify(l));throw new m(`${o} Use one of: ${a.slice(0,-1).join(", ")}, or ${a[a.length-1]}.`)}i(me,"assertWeekStartDay");function he(t,n,e,r,o="declares"){if(t===void 0)return;let s=typeof t=="string"?ir(t):void 0;if(s===void 0)throw new m(`${H(n,e,t,o)}, which isn\'t a duration. Use one such as 30s, 10m or 2h.`,r);if(s>or)throw new m(`${H(n,e,t,o)}, which is over 168h (7 days), the longest a result can be cached.`,r)}i(he,"assertCacheDuration");function Ue(t,n,e="declares"){if(!n.aql?.trim())throw new m(`Query \'${t}\' ${e} no AQL.`,t);let{pageSize:r}=n;if(r!==void 0&&!(Number.isInteger(r)&&r>=1))throw new m(`${H(`Query \'${t}\'`,"pageSize",r,e)}, but it must be a whole number of at least 1.`,t);he(n.cache?.duration,`Query \'${t}\'`,"cache.duration",t,e)}i(Ue,"assertDeclaration");var Ge=class Ge extends P{constructor(e,r,o,s){super(r);c(this,"kind","query");c(this,"name");c(this,"id");c(this,"_declaration");c(this,"_dataset");c(this,"removed",!1);c(this,"app");c(this,"_state","idle");c(this,"runFailed",!1);c(this,"_result");c(this,"_error");c(this,"_page",1);c(this,"_run");c(this,"_sort",[]);c(this,"resultSuperseded",!1);c(this,"lastRunSignature");c(this,"lastPageRows",0);c(this,"controller");c(this,"runningSignature");c(this,"failedSignature");Ue(e,o),this.name=e,this.id=s,this.app=r,this._declaration=o,this._dataset=r.datasetIndex(o.dataset,e)}get declaration(){return this._declaration}get dataset(){return this._dataset}get isRemoved(){return this.removed}update(e){this.assertLive(),this.app.updateQuery(this,e)}remove(){this.assertLive(),this.app.removeEntity(this)}assertLive(){if(this.removed)throw new m(`Query \'${this.name}\' was removed from its app; it can\'t be used any more.`,this.name)}replaceDeclaration(e,r,o){this.controller?.abort(),this.controller=void 0,this.runningSignature=void 0,this._state==="executing"&&(this._state=this._result?"success":"idle"),this.resultSuperseded=!0,this._declaration=e,this._dataset=r,this._sort=[...o],this._run=void 0,this.resetPage(),this.notify()}markRemoved(){this.removed=!0,this.controller?.abort(),this.controller=void 0,this.runningSignature=void 0}locate(){return this.assertLive(),this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(e){this.assertLive(),this._sort=[...e],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0||this.resultSuperseded?!1:this._result.meta.hasMore??this.lastPageRows>=this.pageSize}signature(e="pending"){let r=this.app.mappingsTo(this.name).map(o=>({field:o.field,aggregation:o.aggregation,condition:e==="pending"?o.from.condition:o.from.appliedCondition})).sort((o,s)=>o.field.localeCompare(s.field)||JSON.stringify(o).localeCompare(JSON.stringify(s)));return JSON.stringify({declaration:this.declaration,conditions:r,selection:this.app.selectionConditionsFor(this.name,e),selectionExpression:this.app.selectionExpressionFor(this.name,e),sort:this._sort,inputDefaults:this.app.queryInputDefaults,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}hasUnappliedChange(e){let r=this.signature();return r===this.runningSignature?!1:this.runFailed?r!==this.failedSignature:this.lastRunSignature===void 0?e&&this.runningSignature===void 0:r!==this.lastRunSignature}shouldRun(e=!1){return e||this.runFailed||this.lastRunSignature===void 0||this.isDirty}shouldRunAlone(e=!1){return e||this.runFailed||this.lastRunSignature===void 0||this.signature("applied")!==this.lastRunSignature}execute(e={}){return this.assertLive(),this.app.executeQuery(this,e)}abort(){this.assertLive(),this.controller?.abort()}async fetchMore(){try{if(this.assertLive(),this.pageSize===void 0)throw new m(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);if(!this.hasMore)return;this._page+=1,await this.app.fetchPage(this)}catch(e){throw U(e,"fetch_more"),e}}menu(e,r,o={}){return this.assertLive(),this.app.menu(this,e,Array.isArray(r)?r:[r],o.fields,o.measure)}select(e,r={}){this.assertLive(),this.app.select(this,Array.isArray(e)?e:[e],r.fields)}get selectedRows(){let{selection:e}=this.app;if(e?.source!==this.name)return[];let r=this._result?.rows;if(!r)return e.rows;let o=i(a=>JSON.stringify(e.fields.map(l=>a[l]??null)),"key"),s=new Set(e.rows.map(o));return r.filter(a=>s.has(o(a)))}markExecuting(){this.removed||(this._state="executing",this._error=void 0,this.notify())}get cacheDuration(){return this.declaration.cache?.duration??this.app.queryCacheDefaultDuration}get run(){return this._run}markSuccess(e,r,o,s){if(!this.removed){if(this._state="success",o||(this._run=s,this.resultSuperseded=!1),this._error=void 0,o||(this.runFailed=!1),this.lastRunSignature=r,this.lastPageRows=e.rows.length,o&&this._result){let a=e.meta.pivot?sr(this._result.rows,e.rows):e.rows,l=[...this._result.rows,...a];this._result={...e,rows:l,meta:{...e.meta,numRows:l.length}}}else this._result=e;this.notify()}}markError(e,r=!1,o){this.removed||(r||(this.runFailed=!0,this.failedSignature=o),this._state="error",this._error=e,this.notify())}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this._declaration}};i(Ge,"Query");var F=Ge,Yt="__pivot_row__";function sr(t,n){let e=new Set(t.map(r=>String(r[Yt])));return n.filter(r=>!e.has(String(r[Yt])))}i(sr,"newGridRows");function Xt(t,n){if(n)throw new m(`Edge \'${t.id}\' was removed from its app; map again to have it back.`,t.from.name)}i(Xt,"assertLive");var Je=class Je{constructor(n,e,r,o,s){c(this,"kind","control");c(this,"from");c(this,"to");c(this,"field");c(this,"aggregation");c(this,"owner");c(this,"removed",!1);this.from=n,this.to=e,this.field=r,this.aggregation=o,this.owner=s}remove(){Xt(this,this.removed),this.owner?.removeEdge(this)}markRemoved(){this.removed=!0}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};i(Je,"Mapping");var ge=Je,We=class We{constructor(n,e,r){c(this,"kind","crossFilter");c(this,"from");c(this,"to");c(this,"owner");c(this,"removed",!1);this.from=n,this.to=e,this.owner=r}remove(){Xt(this,this.removed),this.owner?.removeEdge(this)}markRemoved(){this.removed=!0}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};i(We,"CrossFilter");var ye=We;function ar(t,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:t.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...t.aggregation?{aggregation:t.aggregation}:{}}}i(ar,"toFilter");function lr(t,n){if(n?.operator!=="transform_date_drill")return;let e=n.values?.[0];if(typeof e!="string")return;let r=e.replace(/^datetrunc\\s+/,"");return{field:t.field,grain:r}}i(lr,"toDateDrill");function dr(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let a={};return e.forEach((l,d)=>{a[l.name]=s[d]}),a}),{pageSize:o}=t;return{columns:e,rows:r,meta:{...o!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??o,...n.meta?.hasMore!==void 0?{hasMore:n.meta.hasMore}:{},...n.meta?.pivot?{pivot:n.meta.pivot}:{}}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}i(dr,"toResult");function be(t,n,e,r){let o=n.map(d=>ar(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>lr(d,d.from.appliedCondition)).filter(d=>d!==void 0),a=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),l=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...o,...a],conditions:l,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s,...r.timezone?{timezone:r.timezone}:{},...r.weekStartDay?{weekStartDay:r.weekStartDay}:{}},...t.cacheDuration?{cacheDuration:t.cacheDuration}:{}}}i(be,"buildQuery");function He(t,n,e,r){let{input:o,...s}=be(t,n,e,r);return{...s,input:en(o,t),...r.bustCache?{bustCache:!0}:{}}}i(He,"buildRequest");function Zt(t,n){return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:en(n.input,t),...t.cacheDuration?{cacheDuration:t.cacheDuration}:{},...n.cachedAt?{minCachedAt:n.cachedAt}:{}}}i(Zt,"pageRequest");function en(t,n){let{pagination:e,...r}=t;return n.pageSize!==void 0?{...r,pagination:{page:n.page,pageSize:n.pageSize}}:r}i(en,"withPage");function cr(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}i(cr,"defaultExportFilename");function tn(t,n,e,r,o,s){let a=o.format??"csv",l=a==="csv"?{bom:!0,...o.formatOptions}:o.formatOptions,d=be(t,n,e,r),{pagination:p,...g}=s?.input??d.input;return{...d,input:g,...s?.cachedAt?{minCachedAt:s.cachedAt}:{},format:a,...l?{formatOptions:l}:{},filename:o.filename?.trim()||cr(t,r.title)}}i(tn,"buildExportRequest");async function Ye(t,n,e,r,o){let s=await e.submitQuery(n,r,o),a=s.debug?.cache?.cachedAt?.toISOString();return{result:dr(t,s),run:{input:s.input??n.input,...a?{cachedAt:a}:{}}}}i(Ye,"runQuery");function ur(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return mr(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError(`Cannot express ${t} in AQL.`);return Math.abs(t)>=1e21?BigInt(t).toString():String(t)}return JSON.stringify(t).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}i(ur,"literal");function nn(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${ur(n,e)}`}i(nn,"equals");var pr=new Set(["NaN","Infinity","-Infinity"]),fr=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function mr(t){let n=fr.exec(t);if(!n)throw pr.has(t)?new RangeError(`Cannot express ${t} in AQL.`):new TypeError(`${JSON.stringify(t)} is not a number: a number is a string in JSON\'s number syntax.`);let[,e,r,o="",s]=n;if(s===void 0)return t;let a=r+o,l=r.length+Number(s),d;return l<=0?d=`0.${"0".repeat(-l)}${a}`:l>=a.length?d=a+"0".repeat(l-a.length):d=`${a.slice(0,l)}.${a.slice(l)}`,e+d.replace(/^0+(?=\\d)/,"")}i(mr,"numberLiteral");function rn(t,n,e){return`${t} matches @(${n} until ${e})`}i(rn,"dateRange");function on(t,n){if(n.length===0)throw new RangeError(`\\`${t}\\` needs at least one operand.`);return n.length===1?n[0]:`${t}(${n.join(", ")})`}i(on,"combine");var sn=i(t=>on("and",t),"and"),an=i(t=>on("or",t),"or");var hr=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,gr={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function ln(t){if(typeof t!="string")return;let n=hr.exec(t);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}i(ln,"parseStamp");function Y(t,n){let e=new Date(t),r=i(s=>String(s).padStart(2,"0"),"pad"),o=`${e.getUTCFullYear()}-${r(e.getUTCMonth()+1)}-${r(e.getUTCDate())}`;return n?`${o} ${r(e.getUTCHours())}:${r(e.getUTCMinutes())}:${r(e.getUTCSeconds())}`:o}i(Y,"format");function dn(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}i(dn,"toMs");function Xe(t){let n=ln(t);if(n)return Y(dn(n),n.hasTime)}i(Xe,"normalise");function Ze(t,n){let e=ln(t);if(!e)return;let{year:r,month:o,day:s,hour:a,minute:l,second:d,hasTime:p}=e;return Y(n==="year"?Date.UTC(r+1,o,s,a,l,d):n==="quarter"?Date.UTC(r,o+3,s,a,l,d):n==="month"?Date.UTC(r,o+1,s,a,l,d):dn(e)+gr[n],p)}i(Ze,"addGrain");function cn(t){if(t?.startsWith("datetrunc "))return t.slice(10)}i(cn,"grainOf");function yr(t){let n=new Set;return t.filter(e=>{let r=`${typeof e}:${String(e)}`;return n.has(r)?!1:(n.add(r),!0)})}i(yr,"distinct");function br(t,n){let e=t.map(Xe);if(e.some(o=>o===void 0))return!1;let r=e.slice().sort();for(let o=1;o<r.length;o+=1)if(Ze(r[o-1],n)!==r[o])return!1;return!0}i(br,"isContiguous");function wr(t,n,e){let r=n.map(Xe);if(r.some(d=>d===void 0))return;let o=r.slice().sort(),s=o[0],a=Ze(o[o.length-1],e);if(!a)return;let l=br(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${a}`]},admits:l?n.length:Number.POSITIVE_INFINITY,lossy:!l}}i(wr,"dateRange");function vr(t,n,e){let r=e.filter(l=>l!=null),o=yr(r);if(!o.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,a=cn(n);if(a){let l=wr(t,o,a);if(l)return{...l,lossy:l.lossy||s}}return{condition:{field:t,operator:"is",values:o},admits:o.length,lossy:s}}i(vr,"deriveOne");function un(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}i(un,"fieldReferenceOf");function kr(t,n,e,r){try{let o=e.map(s=>sn(n.map(a=>{let l=t.get(a),d=un(l),p=s[a]??null,g=cn(r[d]);if(g&&typeof p=="string"){let k=Xe(p),y=Ze(p,g);if(k&&y)return rn(d,k,y)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return nn(d,p,l.semantic_type)})));return an(o)}catch{return}}i(kr,"selectionExpression");function et(t,n,e,r={}){let o=t.result?.columns??[],s=new Map(o.map(f=>[f.name,f]));e?.forEach(f=>{let h=s.get(f);if(h){if(h.adhoc)throw new m(`Query \'${t.name}\' cannot cross-filter on \'${f}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,t.name);if(h.isMeasure)throw new m(`Query \'${t.name}\' cannot cross-filter on \'${f}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new m(B(`Query \'${t.name}\' has no column \'${f}\' in its last result.`,f,[...s.keys()]),t.name)});let a=o.filter(f=>!f.isMeasure),l=a.filter(f=>!f.adhoc).map(f=>f.name),d=e?[...e]:l;if(!n.length||!d.length)return;let p=[],g=1,k=!e&&l.length!==a.length,y=!1;d.forEach(f=>{let h=s.get(f),w=un(h),S=vr(w,r[w],n.map(u=>u[f]));p.push(S.condition),g*=S.admits,y=y||S.lossy});let x=new Set(n.map(f=>JSON.stringify(d.map(h=>f[h]??null))));g>x.size&&(y=!0);let D=p.sort((f,h)=>f.field.localeCompare(h.field)),R={source:t.name,rows:[...n],fields:d};if(y){let f=kr(s,d,n,r);if(f)return{...R,conditions:[],expression:f,lossy:k}}return{...R,conditions:D,lossy:k||y}}i(et,"deriveSelection");var tt=Object.freeze([]);function nt(t){return t instanceof Error&&t.name==="AbortError"}i(nt,"isAbort");function we(t,n){return t.controller!==n}i(we,"superseded");function Er(t){return{name:t.name,code:t.code,scope:t.scope,message:t.message,...t.entity?{entity:t.entity}:{},...typeof t.status=="number"?{status:t.status}:{},...t.requestId?{requestId:t.requestId}:{},...t.stack?{stack:t.stack}:{}}}i(Er,"inspectError");function xr(t){let{result:n}=t;return{id:t.id,state:t.state,isDirty:t.isDirty,page:t.page,hasMore:t.hasMore,columns:n?n.columns.map(e=>({...e})):[],rowCount:n?.meta.numRows??0,selectedRowCount:t.selectedRows.length,signature:t.signature(),...t.error?{error:Er(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}i(xr,"inspectQuery");function Sr(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}i(Sr,"inspectControl");function pn(t){return{source:t.source,fields:[...t.fields],rowCount:t.rows.length,conditions:t.conditions.map(n=>({...n})),...t.expression?{expression:t.expression}:{},lossy:t.lossy}}i(pn,"inspectSelection");function fn(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}i(fn,"selectionKey");function rt(t,n,e="The query failed."){return L(t)?t.about(n):(console.error(`anfra: \'${n}\' failed; the app is told only that it failed.`,t),new $({code:"call_failed",scope:"server",message:e,entity:n,cause:t}))}i(rt,"toDataAppError");var ot=class ot extends P{constructor(e,r,o,s,a){super();c(this,"extensions",a);c(this,"title");c(this,"_timezone");c(this,"_weekStartDay");c(this,"queryInput");c(this,"queryCacheDefaultDuration");c(this,"datasets");c(this,"backend");c(this,"features");c(this,"_queries",new Map);c(this,"_controls",new Map);c(this,"_mappings",[]);c(this,"_crossFilters",[]);c(this,"_selection");c(this,"_appliedSelection");c(this,"selectionCommitted",!1);c(this,"nextQueryId",1);c(this,"removedListeners",new Set);c(this,"index",0);this.title=e.title,this._timezone=e.timezone,me(e.weekStartDay,"The app","weekStartDay"),this._weekStartDay=e.weekStartDay;let l=e.query?.default?.input??{};me(l.weekStartDay,"The app","query.default.input.weekStartDay"),this.queryInput={...l};let d=e.query?.default?.cache?.duration;he(d,"The app","query.default.cache.duration"),this.queryCacheDefaultDuration=d,this.datasets=r,this.backend=o,this.features=s}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(e,r){this.assertNameFree(e,"query");let o=ue(new F(e,this,r,this.nextQueryId++),this.extensions?.query);return this._queries.set(e,o),this.notify(),o}createFilter(e,r){this.assertNameFree(e,"filter");let o=this.filterDataset(e,r),s=ue(new se(e,this,r,o,this.backend),this.extensions?.control);return this._controls.set(e,s),this.notify(),s}createDateDrill(e,r={}){if(this.features?.dateDrill===!1)throw new m(`Date drill \'${e}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,e);this.assertNameFree(e,"date drill control");let o=ue(new ae(e,this,r),this.extensions?.control);return this._controls.set(e,o),this.notify(),o}mapControl(e,r,o){if(!(e instanceof Q))throw new m("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(e.assertLive(),r.assertLive(),this._controls.get(e.name)!==e)throw new m(`Control \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new m(`Query \'${r.name}\' belongs to a different app.`,r.name);o.aggregation&&Wt(o.aggregation,e.name);let s=new ge(e,r,o.field,o.aggregation,this);if(this._mappings.some(a=>a.id===s.id))throw new m(`Mapping \'${s.id}\' is already declared.`,e.name);return this.assertAcyclic(s),this._mappings.push(s),this.notify(),s}mapCrossFilter(e,r){if(!(e instanceof F)||!(r instanceof F))throw new m("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(e.assertLive(),r.assertLive(),this._queries.get(e.name)!==e)throw new m(`Query \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new m(`Query \'${r.name}\' belongs to a different app.`,r.name);if(e===r)throw new m(`Query \'${e.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,e.name);if(e.declaration.dataset!==r.declaration.dataset)throw new m(`Cross-filter \'${e.name}\' -> \'${r.name}\' spans two datasets (\'${e.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,e.name);let o=new ye(e,r,this);if(this._crossFilters.some(s=>s.id===o.id))throw new m(`Cross-filter \'${o.id}\' is already declared.`,e.name);return this._crossFilters.push(o),this.notify(),o}updateQuery(e,r){let o=e.declaration,s=J(o,r,["dataset","aql","pageSize","cache"]);Ue(e.name,s,"sets");let a=this.datasetIndex(s.dataset,e.name);if(s.dataset!==o.dataset){let p=this._crossFilters.filter(g=>g.from===e?g.to.declaration.dataset!==s.dataset:g.to===e?g.from.declaration.dataset!==s.dataset:!1);if(p.length)throw new m(`Query \'${e.name}\' can\'t move to dataset \'${s.dataset}\': its cross-filters ${p.map(g=>`\'${g.id}\'`).join(", ")} would span two datasets. Remove them first.`,e.name)}let l=s.aql!==o.aql||s.dataset!==o.dataset,d=r.sort??(l?[]:e.sort);l&&this.dropSelectionFrom(e.name),e.replaceDeclaration(s,a,d)}removeEntity(e){if(e instanceof F){if(this._queries.get(e.name)!==e)throw new m(`Query \'${e.name}\' belongs to a different app.`,e.name);this._queries.delete(e.name),this.dropEdges(r=>r.to===e||r.from===e),this.dropSelectionFrom(e.name)}else{if(this._controls.get(e.name)!==e)throw new m(`Control \'${e.name}\' belongs to a different app.`,e.name);this._controls.delete(e.name),this.dropEdges(r=>r.from===e)}e.markRemoved(),this.removedListeners.forEach(r=>{try{r(e)}catch{}}),this.notify()}removeEdge(e){if(!this.dropEdges(r=>r===e))throw new m(`Edge \'${e.id}\' belongs to a different app.`,e.from.name);this.notify()}onRemoved(e){return this.removedListeners.add(e),()=>{this.removedListeners.delete(e)}}dropEdges(e){let r=this.mappings.filter(e);r.forEach(s=>s.markRemoved());let o=i(s=>{let a=s.filter(l=>!r.includes(l));s.splice(0,s.length,...a)},"keep");return o(this._mappings),o(this._crossFilters),r.length>0}dropSelectionFrom(e){this._selection?.source===e&&(this._selection=void 0),this._appliedSelection?.source===e&&(this._appliedSelection=void 0)}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(e){this._timezone=e,this.notify()}get timezone(){return this._timezone}setWeekStartDay(e){me(e,"The app","weekStartDay","sets"),this._weekStartDay=e,this.notify()}get weekStartDay(){return this._weekStartDay}get queryInputDefaults(){let e=this.queryInput.timezone??this._timezone,r=this.queryInput.weekStartDay??this._weekStartDay;return{...e?{timezone:e}:{},...r?{weekStartDay:r}:{}}}datasetIndex(e,r){return Jt(this.datasets,e,r)}filterDataset(e,r){return r.dataset?this.datasetIndex(r.dataset,e):this.soleDataset(e,r.field)}mappingsTo(e){return this._mappings.filter(r=>r.to.name===e)}selectionExpressionFor(e,r){return this.selectionFor(e,r)?.expression}selectionFor(e,r){let o=r==="pending"?this._selection:this._appliedSelection;return!o||o.source===e?void 0:this._crossFilters.some(a=>a.from.name===o.source&&a.to.name===e)?o:void 0}selectionConditionsFor(e,r){let o=r==="pending"?this._selection:this._appliedSelection;return!o||o.source===e?tt:this._crossFilters.some(a=>a.from.name===o.source&&a.to.name===e)?o.conditions:tt}drillTransformations(e){let r={};return this._mappings.forEach(o=>{if(o.to!==e)return;let s=o.from.appliedCondition;if(s?.operator!=="transform_date_drill")return;let[a]=s.values??[];typeof a=="string"&&(r[o.field]=a)}),r}menu(e,r,o,s,a){if(this._queries.get(e.name)!==e)throw new m(`Query \'${e.name}\' belongs to a different app.`,e.name);if(a!==void 0){let d=e.result?.columns??[],p=d.find(g=>g.name===a);if(!p?.isMeasure)throw new m(p?`Query \'${e.name}\' can\'t open a menu on \'${a}\' as its measure: it is a dimension.`:B(`Query \'${e.name}\' has no measure \'${a}\' in its last result.`,a,d.filter(g=>g.isMeasure).map(g=>g.name)),e.name)}let l=et(e,o,s,this.drillTransformations(e));return qt(r,{kind:"rows",app:this.index,query:e.name,rows:[...o],fields:l?.fields?[...l.fields]:[],...a!==void 0?{measure:a}:{},conditions:l?.conditions?[...l.conditions]:[],...l?.expression?{expression:l.expression}:{}})}requestFor(e){if(this._queries.get(e.name)!==e)throw new m(`Query \'${e.name}\' belongs to a different app.`,e.name);return be(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},this.queryInputDefaults)}select(e,r,o){if(this._queries.get(e.name)!==e)throw new m(`Query \'${e.name}\' belongs to a different app.`,e.name);let s=et(e,r,o,this.drillTransformations(e));s?.lossy&&console.warn(`[anfra-sdk] The selection in \'${e.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=s,this.notify()}get hasChanges(){return[...this._controls.values()].some(e=>e.isDirty)||this.isSelectionDirty||[...this._queries.values()].some(e=>e.hasUnappliedChange(this.selectionCommitted))}get isSelectionDirty(){return this.selectionCommitted?fn(this._selection)!==fn(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(l=>l.shouldRun(e.force));this._controls.forEach(l=>l.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(l=>{l.controller?.abort(),l.resetPage()});let o={backend:this.backend,...this.queryInputDefaults,bustCache:e.bustCache},s=[],a=[];return await Promise.all(r.map(async l=>{let d=await this.run(l,l.signature(),o);d==="succeeded"?s.push(l.name):d==="failed"&&a.push(l.name)})),{succeeded:s,failed:a}}async executeQuery(e,r={}){if(!e.shouldRunAlone(r.force))return{succeeded:[],failed:[]};e.controller?.abort(),e.resetPage();let o=await this.run(e,e.signature("applied"),{backend:this.backend,...this.queryInputDefaults,bustCache:r.bustCache});return{succeeded:o==="succeeded"?[e.name]:[],failed:o==="failed"?[e.name]:[]}}async run(e,r,o){let s=new AbortController;e.controller=s,e.runningSignature=r,e.markExecuting();try{let a=He(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},o),{result:l,run:d}=await Ye(e,a,o.backend,s.signal,this.stampOf(e));return we(e,s)?void 0:(e.markSuccess(l,r,!1,d),"succeeded")}catch(a){if(we(e,s)||nt(a))return;let l=rt(a,e.name);return e.markError(l,!1,r),I("call.query",l),"failed"}finally{e.controller===s&&(e.controller=void 0,e.runningSignature=void 0)}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(e=>e.abort())}async fetchPage(e){let r=new AbortController,o=e.signature("applied");e.controller=r,e.runningSignature=o,e.markExecuting();try{let s=e.run?Zt(e,e.run):He(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,...this.queryInputDefaults}),{result:a}=await Ye(e,s,this.backend,r.signal,this.stampOf(e));if(we(e,r))return;e.markSuccess(a,o,!0)}catch(s){if(we(e,r)||(e.rewindPage(),nt(s)))return;let a=rt(s,e.name);throw e.markError(a,!0),a}finally{e.controller===r&&(e.controller=void 0,e.runningSignature=void 0)}}async exportQuery(e,r,o){let s=tn(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{...this.queryInputDefaults,title:this.title},r,e.run);try{return await o(s,r.signal??new AbortController().signal,{app:this.index,query:e.name})}catch(a){throw nt(a)?a:rt(a,e.name,"The export failed.")}}toJSON(){let e=i(r=>Object.fromEntries([...this._controls.entries()].filter(([,o])=>o.kind===r).map(([o,s])=>[o,s.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},...this._weekStartDay?{weekStartDay:this._weekStartDay}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,o])=>[r,o.toJSON()])),filters:e("filter"),dateDrills:e("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},...this._weekStartDay?{weekStartDay:this._weekStartDay}:{},...Object.keys(this.queryInput).length>0?{queryInput:{...this.queryInput}}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([e,r])=>[e,xr(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Sr(r)])),...this._selection?{selection:pn(this._selection)}:{},...this._appliedSelection?{appliedSelection:pn(this._appliedSelection)}:{}}}locate(e,r){let o=globalThis.document;if(!o)return!1;let s=Tt(o,e,this.index,r);return s.length?(ce(s[0]),de(o).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}stampOf(e){return{app:this.index,query:e.name,id:e.id}}assertNameFree(e,r){Ht([...this._queries.keys(),...this._controls.keys()],e,r)}soleDataset(e,r){if(!r)return;let o=Object.keys(this.datasets);if(o.length===1)return this.datasets[o[0]];throw new m(o.length?`Filter \'${e}\' names a field but the environment has ${o.length} datasets. Say which one: ${o.join(", ")}.`:`Filter \'${e}\' names a field but the environment has no datasets.`,e)}assertAcyclic(e){let r=[...this._mappings,e],o=new Map;r.forEach(d=>{let p=d.from.name;o.set(p,[...o.get(p)??[],d.to.name])});let s=new Set,a=new Set,l=i(d=>{if(s.has(d))return!0;if(a.has(d))return!1;s.add(d);let p=(o.get(d)??[]).some(l);return s.delete(d),a.add(d),p},"walk");if([...o.keys()].some(l))throw new m(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};i(ot,"App");var ve=ot;var mn="0.21.0";var lt=class lt{constructor(){c(this,"current",{scheme:"light",tokens:Ie.light});c(this,"listeners",new Set)}get scheme(){return this.current.scheme}get tokens(){return this.current.tokens}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}set(n){this.current=n,this.listeners.forEach(e=>{try{e(n)}catch{}})}};i(lt,"HostTheme");var it=lt,dt=class dt{constructor(n){c(this,"list");this.list=Object.freeze(n.map(({name:e,version:r})=>Object.freeze({name:e,version:r})))}has(n){return this.list.some(e=>e.name===n)}version(n){return this.list.find(e=>e.name===n)?.version}};i(dt,"InstalledPlugins");var st=dt,Dr=mn,ct=class ct{constructor(n){c(this,"version",Dr);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"plugins");c(this,"theme",new it);c(this,"gates");c(this,"deprecatedFeatures");c(this,"extensions",{query:new Map,control:new Map});if(!n?.datasets)throw new m("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new m("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new m("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([e,r])=>[e,new fe(r)])),this.backend=n.backend,this.gates=Object.freeze({...n.features}),this.plugins=new st(n.plugins??[])}get features(){return this.deprecatedFeatures||(console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has(\'export\'), Anfra.plugins.has(\'render\') or Anfra.plugins.has(\'lineage\') instead."),this.deprecatedFeatures=Object.freeze({...this.gates,export:this.plugins.has("export"),render:this.plugins.has("render"),lineage:this.plugins.has("lineage")})),this.deprecatedFeatures}createApp(n={}){let e=new ve(n,this.indices,this.backend,this.gates,this.extensions);return e.index=this._apps.length,this._apps.push(e),e}get apps(){return this._apps}};i(ct,"Sdk");var at=ct;function hn(t){return new at(t)}i(hn,"createSdk");var X="Anfra";function gn(t,n=globalThis){let e=n[X],r=X in n;return n[X]=t,()=>{r?n[X]=e:delete n[X]}}i(gn,"installSandbox");function yn(t,n=[]){let e=t.document.getElementById(ut);if(!e?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(e.textContent),o=i(h=>t.parent.postMessage(h,r.hostOrigin),"post"),s=new Map,a=new Map,l=kt(o,{answer:i(async(h,w,S)=>{let u=s.get(h);if(!u)throw oe(`Nothing in this frame answers \'${h}\'.`);return u(w,S)},"answer"),hidden:i((h,w)=>{t.console?.error(`anfra: \'${h}\' failed; the host is told only that the call failed.`,w),I("plugin.uncaught",w)},"hidden"),event:i((h,w)=>{a.get(h)?.forEach(S=>{try{S(w)}catch{}})},"event")}),d=i(h=>h.source===t.parent||!!r.hostOrigin&&r.hostOrigin!=="null"&&h.origin===r.hostOrigin,"fromHost");t.addEventListener("message",h=>{d(h)&&l.receive(h.data)});let p={submitQuery:i((h,w,S)=>l.call("core.submitQuery",h,w,S).then(u=>(u.debug?.executedAt&&(u.debug.executedAt=new Date(u.debug.executedAt)),u)),"submitQuery"),fieldSuggestions:i((h,w)=>l.call("core.fieldSuggestions",h,w),"fieldSuggestions")},g=hn({datasets:r.datasets,user:r.user,backend:p,plugins:r.plugins??[]}),k=new Set,y=g.createApp.bind(g);g.createApp=h=>{let w=y(h);return k.forEach(S=>{try{S(w)}catch{}}),w};let x={window:t,sdk:g,endpoint:l,handlers:s,listeners:a,appListeners:k},D=pe("anfra",x,{Query:F,Control:Q});Et(D,t,r.captureConsole===!0),Bt(D),St(pe("core",x,{Query:F,Control:Q})),x.contentUi=jt(D),D.on("theme",h=>{let w=It(h);Mt(t.document,w),g.theme.set(w)});let R=new Set,f=!1;D.on("shortcuts",h=>{R=new Set((Array.isArray(h)?h:[]).map(Vt).filter(w=>!!w)),!(f||!R.size)&&(f=!0,t.addEventListener("keydown",w=>{if(w.defaultPrevented||w.repeat||Ut(w.target))return;let S=Gt(w);R.has(S)&&(w.preventDefault(),D.emit("shortcut",S))}))});for(let[h,w]of n)if(typeof w=="function")try{w(pe(h,x,{Query:F,Control:Q}))}catch(S){t.console?.error(`anfra: plugin \'${h}\' failed to set up:`,S),I("plugin.uncaught",S)}gn(g,t),o({type:"anfra:ready"})}i(yn,"bootstrap");return Sn(Tr);})();\n';
|
|
32
34
|
|
|
33
35
|
// anfra-sdk:anfra-sdk:ui
|
|
34
36
|
var anfra_sdk_ui_default = '"use strict";var __anfraBody=(()=>{var R=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var a=(n,t)=>R(n,"name",{value:t,configurable:!0});var B=(n,t)=>{for(var e in t)R(n,e,{get:t[e],enumerable:!0})},D=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of I(t))!O.call(n,d)&&d!==e&&R(n,d,{get:()=>t[d],enumerable:!(r=C(t,d))||r.enumerable});return n};var T=n=>D(R({},"__esModule",{value:!0}),n);var Y={};B(Y,{default:()=>z});var W=`\n:host { all: initial; }\n* { box-sizing: border-box; }\n/* A part\'s container: over the whole viewport in the top layer, letting the pointer through to the page. */\n.part { position: fixed; inset: 0; width: auto; height: auto; margin: 0; padding: 0; border: 0; overflow: visible; background: none; pointer-events: none; }\n.surface, .backdrop { pointer-events: auto; }\n.surface { position: fixed; z-index: 1; color: var(--anfra-color-fg, oklch(0.201 0.022 301.1)); background: var(--anfra-color-bg, oklch(1 0 0));\n border: 1px solid var(--anfra-color-border, oklch(0.201 0.022 301.1 / 0.12)); border-radius: calc(var(--anfra-radius, 10px) + 4px); /* a surface: the controls\' radius plus 4px, anfra-design\'s xl */\n box-shadow: 0 8px 24px oklch(0 0 0 / 18%), 0 1px 3px oklch(0 0 0 / 10%); font: 13px/1.45 var(--anfra-font, system-ui, sans-serif); }\n.menu { min-width: 180px; max-width: 320px; padding: 4px; outline: none; }\n.menu button { display: block; width: 100%; padding: 6px 10px; border: 0; border-radius: var(--anfra-radius, 10px); background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }\n/* One highlight, as a native menu has: the focused entry, which the pointer and the arrows both move. */\n.menu button:focus { outline: none; background: color-mix(in srgb, var(--anfra-color-accent, oklch(0.484 0.181 298.1)) 14%, transparent); }\n.menu button[aria-disabled="true"] { color: var(--anfra-color-muted, oklch(0.485 0.022 306.3)); cursor: default; }\n.menu .reason { display: block; font-size: 11px; color: var(--anfra-color-muted, oklch(0.485 0.022 306.3)); }\n.menu hr { margin: 4px 0; border: 0; border-top: 1px solid var(--anfra-color-border, oklch(0.201 0.022 301.1 / 0.12)); }\n.backdrop { position: fixed; inset: 0; background: oklch(0 0 0 / 40%); }\n.modal { display: flex; flex-direction: column; left: 50%; top: 50%; transform: translate(-50%, -50%); max-width: calc(100vw - 32px); max-height: calc(100vh - 32px); }\n.modal.sm { width: 360px; } .modal.md { width: 560px; } .modal.lg { width: 860px; }\n.modal.full { width: calc(100vw - 32px); height: calc(100vh - 32px); }\n.modal header { display: flex; align-items: center; gap: 8px; padding: 10px 12px 10px 16px; border-bottom: 1px solid var(--anfra-color-border, oklch(0.201 0.022 301.1 / 0.12)); }\n.modal h2 { flex: 1; margin: 0; font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.close { display: grid; place-items: center; width: 26px; height: 26px; padding: 0; border: 0; border-radius: 4px; background: none; color: var(--anfra-color-muted, oklch(0.485 0.022 306.3)); cursor: pointer; font: 18px/1 var(--anfra-font, system-ui, sans-serif); }\n.close:hover { color: var(--anfra-color-fg, oklch(0.201 0.022 301.1)); background: color-mix(in srgb, var(--anfra-color-fg, oklch(0.201 0.022 301.1)) 7%, transparent); }\n.content { flex: 1; min-height: 0; overflow: auto; }\n.popover { max-width: min(360px, calc(100vw - 16px)); outline: none; }\n.popover > .close { position: absolute; top: 4px; right: 4px; width: 22px; height: 22px; font-size: 16px; }\n.popover.closable > .content { padding-right: 26px; }\n`;function N(n){return{width:n.innerWidth,height:n.innerHeight}}a(N,"viewport");function H(n,t,e,r,d){let{width:y,height:o}=N(n),s=e,g=r;return s+t.width>y-8&&(s=d?d.left-t.width:y-8-t.width),g+t.height>o-8&&(g=d?d.top-t.height:o-8-t.height),{left:Math.max(8,s),top:Math.max(8,g)}}a(H,"place");var P={right:"left",left:"right",bottom:"top",top:"bottom"};function K(n,t,e,r){let{width:d,height:y}=N(n),o=a(c=>c==="right"?{left:e.x+e.width+6,top:e.y}:c==="left"?{left:e.x-t.width-6,top:e.y}:c==="bottom"?{left:e.x,top:e.y+e.height+6}:{left:e.x,top:e.y-t.height-6},"at"),s=a(c=>{let{left:w,top:v}=o(c);return c==="right"||c==="left"?w>=8&&w+t.width<=d-8:v>=8&&v+t.height<=y-8},"fits"),g=[r,P[r],...["right","bottom","left","top"].filter(c=>c!==r&&c!==P[r])],{left:x,top:b}=o(g.find(s)??r),f=a((c,w,v)=>Math.max(8,Math.min(c,v-8-w)),"clamp");return{left:f(x,t.width,d),top:f(b,t.height,y)}}a(K,"beside");function L(n){let t=n.ownerDocument,e=t.createElement("div");e.className="part",e.setAttribute("popover","manual");let r=t.createElement("style");return r.textContent=W,e.append(r),n.append(e),e.showPopover?.(),{container:e,remove:a(()=>e.remove(),"remove")}}a(L,"part");function S(n,t){let e=n.createElement("div");return e.className=t,{element:e,root:e.attachShadow({mode:"open"})}}a(S,"contentRoot");function G(n,t,e){try{let r=t(e);return typeof r=="function"?r:()=>{}}catch(r){return n.console?.error("anfra: a plugin failed to draw:",r),()=>{}}}a(G,"mountContent");function $(n,t){let e=n.ownerDocument,r=e.defaultView,{container:d,remove:y}=L(n),o=e.createElement("div");o.className="surface menu",o.setAttribute("role","menu");let s=[];t.groups.filter(i=>i.length).forEach((i,m)=>{m>0&&o.append(e.createElement("hr"));for(let u of i){let p=e.createElement("button");if(p.type="button",p.setAttribute("role","menuitem"),p.dataset.item=u.id,p.textContent=u.label,u.disabled){p.setAttribute("aria-disabled","true"),p.title=u.disabled;let A=e.createElement("span");A.className="reason",A.textContent=u.disabled,p.append(A)}p.addEventListener("click",()=>{u.disabled||(h(),t.onPick(u.id))}),s.push(p),o.append(p)}}),d.append(o);let g=o.getBoundingClientRect(),{left:x,top:b}=H(r,g,t.x,t.y,{left:t.x,top:t.y});o.style.left=`${x}px`,o.style.top=`${b}px`,o.tabIndex=-1,o.focus();let f=s.filter(i=>!i.hasAttribute("aria-disabled"));o.addEventListener("pointermove",i=>{let m=i.composedPath().find(u=>s.includes(u));m&&f.includes(m)?n.activeElement!==m&&m.focus():n.activeElement!==o&&o.focus()}),o.addEventListener("pointerleave",()=>o.focus());let c=a(i=>{if(i.key==="Escape"){i.preventDefault(),h();return}if(i.key!=="ArrowDown"&&i.key!=="ArrowUp"||(i.preventDefault(),!f.length))return;let m=f.indexOf(n.activeElement),u=i.key==="ArrowDown"?1:-1,p=m===-1?u===1?0:f.length-1:(m+u+f.length)%f.length;f[p].focus()},"onKey"),w=a(i=>{i.composedPath().includes(o)||h()},"onOutside"),v=a(()=>h(),"onAway"),E=[[e,"keydown",c,!0],[e,"pointerdown",w,!0],[r,"scroll",v,!0],[r,"resize",v,!1],[r,"blur",v,!1]];E.forEach(([i,m,u,p])=>i.addEventListener(m,u,p));let l=!1;function h(){l||(l=!0,E.forEach(([i,m,u,p])=>i.removeEventListener(m,u,p)),y(),t.onClose())}return a(h,"close"),h}a($,"menu");function V(n,t){let e=n.ownerDocument,r=e.defaultView,{container:d,remove:y}=L(n),o=e.createElement("div");o.className="backdrop";let s=e.createElement("section");s.className=`surface modal ${t.size??"md"}`,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true");let g=e.createElement("header"),x=e.createElement("h2");x.id="anfra-modal-title",x.textContent=t.title,s.setAttribute("aria-labelledby",x.id);let b=e.createElement("button");b.type="button",b.className="close",b.setAttribute("aria-label","Close"),b.textContent="\\xD7",b.addEventListener("click",()=>A()),g.append(x,b);let f=S(e,"content");s.append(g,f.element),d.append(o,s);let c=n.host.parentElement,w=r,v=[],E=a(k=>{for(let M of k)!(M instanceof w.Element)||M===c||M.hasAttribute("inert")||(M.setAttribute("inert",""),v.push(M))},"inert");E(e.body.children);let l=new w.MutationObserver(k=>k.forEach(M=>E(M.addedNodes)));l.observe(e.body,{childList:!0});let h=e.documentElement,i={overflow:h.style.overflow,gutter:h.style.getPropertyValue("scrollbar-gutter")};r.innerWidth>h.clientWidth&&h.style.setProperty("scrollbar-gutter","stable"),h.style.overflow="hidden";let m=G(r,t.mount,f.root);b.focus();let u=a(k=>{k.key==="Escape"&&(k.preventDefault(),A())},"onKey");e.addEventListener("keydown",u,!0);let p=!1;function A(){if(!p){p=!0,e.removeEventListener("keydown",u,!0);try{m()}catch{}l.disconnect(),v.forEach(k=>k.removeAttribute("inert")),h.style.overflow=i.overflow,i.gutter?h.style.setProperty("scrollbar-gutter",i.gutter):h.style.removeProperty("scrollbar-gutter"),y(),t.onClose()}}return a(A,"close"),A}a(V,"modal");function U(n,t){let e=n.ownerDocument,r=e.defaultView,{container:d,remove:y}=L(n),o=e.createElement("section");o.className="surface popover",o.setAttribute("role","dialog"),o.tabIndex=-1;let s=S(e,"content");if(o.append(s.element),t.closeButton!==!1){o.classList.add("closable");let l=e.createElement("button");l.type="button",l.className="close",l.setAttribute("aria-label","Close"),l.textContent="\\xD7",l.addEventListener("click",()=>E()),o.append(l)}d.append(o);let g=G(r,t.mount,s.root);s.root.activeElement||o.focus();let x=!1,b=a(()=>{x=!1;let l=t.anchor();if(!l){E();return}let h=o.getBoundingClientRect(),{left:i,top:m}=K(r,h,l,t.side??"right");o.style.left=`${i}px`,o.style.top=`${m}px`},"position"),f=a(()=>{x||(x=!0,r.requestAnimationFrame(b))},"schedule");b();let c=a(l=>{l.key==="Escape"&&(l.preventDefault(),E())},"onKey"),w=a(l=>{l.composedPath().includes(o)||E()},"onOutside");e.addEventListener("keydown",c,!0),r.addEventListener("scroll",f,!0),r.addEventListener("resize",f),t.dismiss==="outside"&&e.addEventListener("pointerdown",w,!0);let v=!1;function E(){if(!v){v=!0,e.removeEventListener("keydown",c,!0),r.removeEventListener("scroll",f,!0),r.removeEventListener("resize",f),e.removeEventListener("pointerdown",w,!0);try{g()}catch{}y(),t.onClose()}}return a(E,"close"),E}a(U,"popover");var q={menu:$,modal:V,popover:U},z=q;return T(Y);})();\n';
|
|
@@ -421,6 +423,26 @@ function install(plugins) {
|
|
|
421
423
|
}
|
|
422
424
|
return answers;
|
|
423
425
|
}
|
|
426
|
+
var isIndex = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
427
|
+
function checkStamp(stamp) {
|
|
428
|
+
if (typeof stamp !== "object" || stamp === null) return void 0;
|
|
429
|
+
const {
|
|
430
|
+
app,
|
|
431
|
+
query,
|
|
432
|
+
id,
|
|
433
|
+
variant
|
|
434
|
+
} = stamp;
|
|
435
|
+
if (!isIndex(app)) return void 0;
|
|
436
|
+
if (typeof query !== "string" || !query || query.length > 512) return void 0;
|
|
437
|
+
if (id !== void 0 && !isIndex(id)) return void 0;
|
|
438
|
+
if (variant !== void 0 && (typeof variant !== "string" || !variant || variant.length > 64)) return void 0;
|
|
439
|
+
return {
|
|
440
|
+
app,
|
|
441
|
+
query,
|
|
442
|
+
...id !== void 0 && { id },
|
|
443
|
+
...variant !== void 0 && { variant }
|
|
444
|
+
};
|
|
445
|
+
}
|
|
424
446
|
function createHost(options) {
|
|
425
447
|
const plugins = [...options.plugins];
|
|
426
448
|
const answers = install(plugins);
|
|
@@ -491,7 +513,7 @@ function createHost(options) {
|
|
|
491
513
|
byShortcut.set(shortcut, command.id);
|
|
492
514
|
}
|
|
493
515
|
let nextMount = 1;
|
|
494
|
-
function dispatch(name, request, callers, mount, signal, asOrigin = false) {
|
|
516
|
+
function dispatch(name, request, callers, mount, signal, asOrigin = false, stamp) {
|
|
495
517
|
const answer = answers.get(name);
|
|
496
518
|
if (!answer) return Promise.reject(invalidRequest(`Nothing on this host answers '${name}'.`));
|
|
497
519
|
const caller = callers[callers.length - 1];
|
|
@@ -508,7 +530,8 @@ function createHost(options) {
|
|
|
508
530
|
origin,
|
|
509
531
|
signal,
|
|
510
532
|
mount,
|
|
511
|
-
trace
|
|
533
|
+
trace,
|
|
534
|
+
...stamp ? { stamp } : {}
|
|
512
535
|
};
|
|
513
536
|
const run = (index, current) => {
|
|
514
537
|
if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Aborted"));
|
|
@@ -608,7 +631,7 @@ function createHost(options) {
|
|
|
608
631
|
}
|
|
609
632
|
});
|
|
610
633
|
endpoint = createEndpoint(post, {
|
|
611
|
-
answer: (name, request, signal) => dispatch(name, request, [{ kind: "frame" }], context, signal),
|
|
634
|
+
answer: (name, request, signal, stamp) => dispatch(name, request, [{ kind: "frame" }], context, signal, false, checkStamp(stamp)),
|
|
612
635
|
hidden: (name, err) => {
|
|
613
636
|
const { message, stack, at } = describeError("host.internal", err);
|
|
614
637
|
reportError({
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as DatasetDescriptor,
|
|
1
|
+
import { ad as QueryStamp, D as DatasetDescriptor, as as User, aq as StructureNode, aj as Row, an as SelectionCondition } from './types-C_-1rgj2.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The bridge: the postMessage protocol between a Data App's frame (`app`'s bootstrap) and the
|
|
@@ -55,6 +55,7 @@ type BridgeMessage =
|
|
|
55
55
|
id: number;
|
|
56
56
|
name: string;
|
|
57
57
|
request: unknown;
|
|
58
|
+
stamp?: QueryStamp;
|
|
58
59
|
} | {
|
|
59
60
|
type: 'anfra:result';
|
|
60
61
|
id: number;
|
|
@@ -2,18 +2,21 @@ import {
|
|
|
2
2
|
changesOf,
|
|
3
3
|
problemsOf,
|
|
4
4
|
queryCounts
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-7I2HXY72.js";
|
|
6
6
|
import {
|
|
7
7
|
controlTargets
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-CLXZMA5D.js";
|
|
9
9
|
import {
|
|
10
10
|
PLUGIN_VERSION
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-7NZOMBYE.js";
|
|
12
12
|
import {
|
|
13
|
-
|
|
13
|
+
isCurrent,
|
|
14
|
+
queryOf,
|
|
14
15
|
stateOf
|
|
15
|
-
} from "./chunk-
|
|
16
|
-
import "./chunk-
|
|
16
|
+
} from "./chunk-UWRQXPPG.js";
|
|
17
|
+
import "./chunk-E3Q3FRKQ.js";
|
|
18
|
+
import "./chunk-GPBYPSWK.js";
|
|
19
|
+
import "./chunk-HELL45MM.js";
|
|
17
20
|
import {
|
|
18
21
|
LEVELS,
|
|
19
22
|
TRUST_LEVELS,
|
|
@@ -29,7 +32,7 @@ import {
|
|
|
29
32
|
note,
|
|
30
33
|
popover,
|
|
31
34
|
trustBars
|
|
32
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-2TTGSNHA.js";
|
|
33
36
|
import "./chunk-K633QHGO.js";
|
|
34
37
|
import {
|
|
35
38
|
QUERIES_TAB,
|
|
@@ -37,7 +40,7 @@ import {
|
|
|
37
40
|
formatTime,
|
|
38
41
|
plural,
|
|
39
42
|
usageOf
|
|
40
|
-
} from "./chunk-
|
|
43
|
+
} from "./chunk-33HI2ODM.js";
|
|
41
44
|
import "./chunk-PKBMQBKP.js";
|
|
42
45
|
|
|
43
46
|
// src/plugins/inspect/tabs/overview.ts
|
|
@@ -209,7 +212,8 @@ function overviewTab(root, context) {
|
|
|
209
212
|
const controls = apps.reduce((n, app) => n + Object.keys(app.controls).length, 0);
|
|
210
213
|
const unapplied = counts.dirtyControls;
|
|
211
214
|
const last = requests.findLast((entry) => entry.call === "core.submitQuery" && entry.status !== "pending");
|
|
212
|
-
const
|
|
215
|
+
const stamped = last && queryOf(last);
|
|
216
|
+
const lastQuery = stamped && isCurrent(stamped, apps) ? stamped : void 0;
|
|
213
217
|
const first = problems[0];
|
|
214
218
|
const queries = [
|
|
215
219
|
`${counts.success} ok`,
|
|
@@ -242,7 +246,7 @@ function overviewTab(root, context) {
|
|
|
242
246
|
"last-request",
|
|
243
247
|
"Last request",
|
|
244
248
|
last ? h(doc, "span", { "data-tip": formatTime(last.at) }, formatAgo(last.at)) : "\u2014",
|
|
245
|
-
last ? lastQuery?.name ?? "no query" : "Nothing has run yet",
|
|
249
|
+
last ? lastQuery?.name ?? (stamped ? `${stamped.name} (removed)` : "no query") : "Nothing has run yet",
|
|
246
250
|
lastQuery && (() => reveal({ entity: "query", ...lastQuery })),
|
|
247
251
|
last?.status === "error" ? "error" : void 0
|
|
248
252
|
),
|
|
@@ -348,19 +352,30 @@ function overviewTab(root, context) {
|
|
|
348
352
|
const { user } = mount;
|
|
349
353
|
const datasets = Object.values(mount.datasets).map((dataset) => dataset.label || dataset.name);
|
|
350
354
|
const label = (index) => apps.length > 1 ? `App ${index + 1}` : "the app";
|
|
351
|
-
const
|
|
355
|
+
const queriesTimezone = (app) => app.queryInput?.timezone ?? app.timezone;
|
|
356
|
+
const mismatched = apps.flatMap((app, index) => {
|
|
357
|
+
const timezone = queriesTimezone(app);
|
|
358
|
+
return timezone && timezone !== user.timezone ? [`${label(index)}'s queries run in ${timezone}`] : [];
|
|
359
|
+
});
|
|
360
|
+
const overridden = apps.flatMap((app, index) => [
|
|
361
|
+
["timezone", app.timezone, app.queryInput?.timezone],
|
|
362
|
+
["weekStartDay", app.weekStartDay, app.queryInput?.weekStartDay]
|
|
363
|
+
].flatMap(([setting, own, queries]) => own && queries && own !== queries ? [`${apps.length > 1 ? `App ${index + 1}'s` : "The app's"} queries use ${queries} (query.default.input.${setting}), not the app's ${own}, so dates in its UI and in its results may differ.`] : []));
|
|
364
|
+
const perApp = (index, what) => apps.length > 1 ? `App ${index + 1} ${what}` : `App ${what}`;
|
|
352
365
|
return collapsible(doc, "environment", "Environment", () => [
|
|
353
366
|
mismatched.length > 0 && h(
|
|
354
367
|
doc,
|
|
355
368
|
"p",
|
|
356
369
|
{ class: "warning", role: "note", "data-testid": "timezone-warning" },
|
|
357
|
-
`The reader is in ${user.timezone}, but ${mismatched.join(", ")}: dates are computed in the
|
|
370
|
+
`The reader is in ${user.timezone}, but ${mismatched.join(", ")}: dates are computed in the queries' timezone.`
|
|
358
371
|
),
|
|
372
|
+
...overridden.map((text) => h(doc, "p", { class: "warning", role: "note", "data-testid": "query-default-warning" }, text)),
|
|
359
373
|
fields(doc, [
|
|
360
374
|
["SDK", PLUGIN_VERSION],
|
|
361
375
|
["Reader", `${user.name} \xB7 ${user.email} \xB7 ${user.role}`],
|
|
362
376
|
["Reader timezone", user.timezone],
|
|
363
|
-
...apps.map((app, index) => [
|
|
377
|
+
...apps.map((app, index) => [perApp(index, "timezone"), app.timezone || "tenant default"]),
|
|
378
|
+
...apps.map((app, index) => [perApp(index, "week start day"), app.weekStartDay || "server default"]),
|
|
364
379
|
["Generated SQL", user.permissions.canViewGeneratedSql ? "can view" : "hidden"],
|
|
365
380
|
["Export", user.permissions.canExportData ? "allowed" : "not allowed"],
|
|
366
381
|
// The log keeps the newest 200, so this stops there.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as MenuTargetKind, c as MenuTarget, e as PluginInfo, h as Theme } from './menu-
|
|
1
|
+
import { M as InspectedApp, R as InspectedStructure, _ as LocateTarget, as as User, D as DatasetDescriptor, ad as QueryStamp } from './types-C_-1rgj2.js';
|
|
2
|
+
import { d as MenuTargetKind, c as MenuTarget, e as PluginInfo, h as Theme } from './menu-CuTKq-dC.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* The panel: one per mounted Data App, the host's devtools over it. The runtime owns its state (open
|
|
@@ -220,6 +220,11 @@ interface CallContext {
|
|
|
220
220
|
readonly mount?: MountContext;
|
|
221
221
|
/** The middleware the call has passed through so far, by name, outermost first. */
|
|
222
222
|
readonly trace: readonly string[];
|
|
223
|
+
/**
|
|
224
|
+
* The query the frame says the call is for: a query's run or page, or its export. The frame's
|
|
225
|
+
* word, checked only for its shape: show a call under it, never decide by it.
|
|
226
|
+
*/
|
|
227
|
+
readonly stamp?: QueryStamp;
|
|
223
228
|
}
|
|
224
229
|
interface HandlerCallOptions extends CallOptions {
|
|
225
230
|
/**
|
package/dist/plugins.d.ts
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
import { Backend } from './app.js';
|
|
2
2
|
import { Plugin } from './host.js';
|
|
3
|
-
import './menu-
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* `core`: running a Data App's queries and suggesting a filter's values. Every host installs it:
|
|
7
|
-
* the app model makes its calls, through the pipeline like any caller, so a host swaps or wraps it
|
|
8
|
-
* as it would any plugin's. No frame half: the kernel is its frame side.
|
|
9
|
-
*/
|
|
3
|
+
import './menu-CuTKq-dC.js';
|
|
10
4
|
|
|
11
5
|
/** What `core` answers with: a Backend's two required methods, `coreApiBackend` on any host. */
|
|
12
6
|
type CoreBackend = Pick<Backend, 'submitQuery' | 'fieldSuggestions'>;
|