diff --git a/README.md b/README.md index ec10b55a6288abb78647bc0316b77379a58aaf3f..85e6707f4171797ca057eb584814f9686de17593 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,12 @@ This Space demonstrates an auditable chain from a recognizable order-management interface to generated TeaQL Q expressions, runtime TraceChain and the actual SQL executed by SQLite/WASM in the browser. +The executable on this page uses the TeaQL TypeScript runtime. TeaQL implements +the same model-driven Q and TraceChain contract across seven runtimes: +TypeScript, Java, Rust, Go, Python, .NET and Swift. The language strip on the +page links to each runtime source and marks TypeScript as the runtime currently +executing in the browser. + The default page is the full order center. Its status cards, colors, order counts, order totals, rows, item previews and pagination are produced by one generated Q request whose search parameters change without changing the query shape. Results @@ -40,7 +46,7 @@ cross-origin isolation. The exact runtime, tests, model, generated Order library and browser application source are retained under [`source/teaql-ts`](./source/teaql-ts). They correspond to -TeaQL TypeScript commit `e87b5d843a1bc2ae5f677f402b6b3177a7d40b50` on `main`. +TeaQL TypeScript commit `9341b0a1fe5f2c090a39a46f9c03c50e55e27341` on `main`. ```bash cd source/teaql-ts @@ -55,7 +61,7 @@ npm run smoke npm run smoke:orders ``` -The validated runtime result was 56 passing suites and 604 passing tests, with six +The validated runtime result was 57 passing suites and 608 passing tests, with six tests skipped by the repository configuration. Both real-browser smoke suites pass. Learn more at [teaql.io](https://teaql.io/) and inspect the upstream source at diff --git a/assets/dynamic-search-BBmdgl4H.js b/assets/dynamic-search-BBmdgl4H.js deleted file mode 100644 index 08ffb8822e2d0b40448ab09bc0b30e38c4ce5d16..0000000000000000000000000000000000000000 --- a/assets/dynamic-search-BBmdgl4H.js +++ /dev/null @@ -1,8 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function t(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=t(r);fetch(r.href,o)}})();const Ae=Object.freeze({success:()=>{},failure:()=>{}}),rt=new Set(["teaql.entity.id","teaql.user.id","teaql.tenant.id","teaql.query.parameters","teaql.field.values","teaql.audit.reason","db.query.parameter_values","http.request.body","url.full"]);function st(i){const e={"teaql.operation.family":i.family,"teaql.operation.name":i.name};for(const[t,n]of Object.entries(i.attributes||{}))rt.has(t)||(e[t]=n);return Object.freeze({...i,attributes:Object.freeze(e)})}function N(i,e){if(!i)return Ae;try{const t=i.start(st(e));let n=!1;return{correlation:()=>{try{return t.correlation?.()}catch{return}},run:t.run?r=>t.run(r):r=>r(),success(r){if(!n){n=!0;try{t?.success(r)}catch{}}},failure(r){if(!n){n=!0;try{t?.failure(r)}catch{}}}}}catch{return Ae}}async function D(i,e,t,n){const r=N(i,e);try{const o=await(r.run?r.run(t):t());return r.success(n?.(o)),o}catch(o){throw r.failure(o),o}}class ot extends Error{constructor(e){super(`Check failed: ${e.map(t=>t.message??`${t.ruleId}:${t.location}`).join("; ")}`),this.violations=e,this.name="CheckException"}}const at="teaql.i18n/v1",ct="en",lt={en:{messages:{"checker.required":"The {location} is required","checker.min":"The {location} should be equal or greater than {system}, but input is {input}","checker.max":"The {location} should be equal or less than {system}, but input is {input}","checker.minLength":"The length of {location} should be equal or greater than {system}, but the length of {input} is {input_len}","checker.maxLength":"The length of {location} should be equal or less than {system}, but the length of {input} is {input_len}"},vocabulary:{}},"zh-CN":{messages:{"checker.required":"{location} 是必填项","checker.min":"{location} 应该大于等于 {system},但输入值为 {input}","checker.max":"{location} 应该小于等于 {system},但输入值为 {input}","checker.minLength":"{location} 的长度应大于等于 {system},但实际长度为 {input_len}","checker.maxLength":"{location} 的长度应小于等于 {system},但实际长度为 {input_len}"},vocabulary:{}},"zh-TW":{messages:{"checker.required":"{location} 是必填的","checker.min":"{location} 應該等於或大於 {system},但輸入為 {input}","checker.max":"{location} 應該等於或小於 {system},但輸入為 {input}","checker.minLength":"{location} 的長度應該等於或大於 {system},但 {input} 的長度是 {input_len}","checker.maxLength":"{location} 的長度應該等於或小於 {system},但 {input} 的長度是 {input_len}"},vocabulary:{}},ja:{messages:{"checker.required":"{location} は必須です","checker.min":"{location} は {system} 以上である必要があります。入力値は {input} です","checker.max":"{location} は {system} 以下である必要があります。入力値は {input} です","checker.minLength":"{location} の長さは {system} 以上である必要があります。実際の長さは {input_len} です","checker.maxLength":"{location} の長さは {system} 以下である必要があります。実際の長さは {input_len} です"},vocabulary:{}},ko:{messages:{"checker.required":"{location}은(는) 필수입니다","checker.min":"{location}은(는) {system} 이상이어야 하지만 입력값은 {input}입니다","checker.max":"{location}은(는) {system} 이하여야 하지만 입력값은 {input}입니다","checker.minLength":"{location}의 길이는 {system} 이상이어야 하지만 실제 길이는 {input_len}입니다","checker.maxLength":"{location}의 길이는 {system} 이하여야 하지만 실제 길이는 {input_len}입니다"},vocabulary:{}},de:{messages:{"checker.required":"{location} ist erforderlich","checker.min":"{location} muss mindestens {system} sein, aber die Eingabe ist {input}","checker.max":"{location} darf höchstens {system} sein, aber die Eingabe ist {input}","checker.minLength":"Die Länge von {location} muss mindestens {system} sein, ist aber {input_len}","checker.maxLength":"Die Länge von {location} darf höchstens {system} sein, ist aber {input_len}"},vocabulary:{}},fr:{messages:{"checker.required":"{location} est obligatoire","checker.min":"{location} doit être supérieur ou égal à {system}, mais la valeur saisie est {input}","checker.max":"{location} doit être inférieur ou égal à {system}, mais la valeur saisie est {input}","checker.minLength":"La longueur de {location} doit être supérieure ou égale à {system}, mais elle est {input_len}","checker.maxLength":"La longueur de {location} doit être inférieure ou égale à {system}, mais elle est {input_len}"},vocabulary:{}},es:{messages:{"checker.required":"{location} es requerido/a","checker.min":"{location} debe ser mayor o igual que {system}, pero el valor ingresado es {input}","checker.max":"{location} debe ser menor o igual que {system}, pero el valor ingresado es {input}","checker.minLength":"La longitud de {location} debe ser mayor o igual que {system}, pero es {input_len}","checker.maxLength":"La longitud de {location} debe ser menor o igual que {system}, pero es {input_len}"},vocabulary:{}},pt:{messages:{"checker.required":"{location} é obrigatório","checker.min":"{location} deve ser maior ou igual a {system}, mas a entrada é {input}","checker.max":"{location} deve ser menor ou igual a {system}, mas a entrada é {input}","checker.minLength":"O comprimento de {location} deve ser maior ou igual a {system}, mas é {input_len}","checker.maxLength":"O comprimento de {location} deve ser menor ou igual a {system}, mas é {input_len}"},vocabulary:{}},ar:{messages:{"checker.required":"{location} مطلوب","checker.min":"يجب أن يكون {location} مساويًا أو أكبر من {system}، لكن المُدخل هو {input}","checker.max":"يجب أن يكون {location} مساويًا أو أصغر من {system}، لكن المُدخل هو {input}","checker.minLength":"يجب أن يكون طول {location} مساويًا أو أكبر من {system}، لكن الطول هو {input_len}","checker.maxLength":"يجب أن يكون طول {location} مساويًا أو أصغر من {system}، لكن الطول هو {input_len}"},vocabulary:{}},th:{messages:{"checker.required":"{location} เป็นสิ่งจำเป็น","checker.min":"{location} ควรจะเท่ากับหรือมากกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.max":"{location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.minLength":"ความยาวของ {location} ควรจะเท่ากับหรือมากกว่า {system} แต่ความยาวคือ {input_len}","checker.maxLength":"ความยาวของ {location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ความยาวคือ {input_len}"},vocabulary:{}},id:{messages:{"checker.required":"{location} wajib diisi","checker.min":"{location} harus sama dengan atau lebih besar dari {system}, tetapi input adalah {input}","checker.max":"{location} harus sama dengan atau lebih kecil dari {system}, tetapi input adalah {input}","checker.minLength":"Panjang {location} harus sama dengan atau lebih besar dari {system}, tetapi panjangnya {input_len}","checker.maxLength":"Panjang {location} harus sama dengan atau lebih kecil dari {system}, tetapi panjangnya {input_len}"},vocabulary:{}},fil:{messages:{"checker.required":"Ang {location} ay kinakailangan","checker.min":"Ang {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang input ay {input}","checker.max":"Ang {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang input ay {input}","checker.minLength":"Ang haba ng {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang haba ay {input_len}","checker.maxLength":"Ang haba ng {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang haba ay {input_len}"},vocabulary:{}},uk:{messages:{"checker.required":"{location} є обов'язковим","checker.min":"{location} повинен бути рівним або більшим за {system}, але ввідне значення {input}","checker.max":"{location} повинен бути рівним або меншим за {system}, але ввідне значення {input}","checker.minLength":"Довжина {location} повинна бути рівною або більшою за {system}, але довжина становить {input_len}","checker.maxLength":"Довжина {location} повинна бути рівною або меншою за {system}, але довжина становить {input_len}"},vocabulary:{}},vi:{messages:{"checker.required":"{location} là bắt buộc","checker.min":"{location} phải lớn hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.max":"{location} phải nhỏ hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.minLength":"Độ dài của {location} phải lớn hơn hoặc bằng {system}, nhưng độ dài là {input_len}","checker.maxLength":"Độ dài của {location} phải nhỏ hơn hoặc bằng {system}, nhưng độ dài là {input_len}"},vocabulary:{}}},ut={schema:at,defaultLocale:ct,locales:lt},ht=["en","zh-CN","zh-TW","ja","ko","de","fr","es","pt","ar","th","id","fil","uk","vi"];class Oe extends Error{constructor(e){super(`Unsupported locale: ${e}`),this.localeCode=e}}const dt={"en-us":"en","en-gb":"en",zh:"zh-CN","zh-hans":"zh-CN","zh-sg":"zh-CN",cn:"zh-CN","zh-hant":"zh-TW","zh-hk":"zh-TW","zh-mo":"zh-TW",tw:"zh-TW","ja-jp":"ja","ko-kr":"ko","de-de":"de","fr-fr":"fr","es-mx":"es","pt-br":"pt","pt-pt":"pt","ar-sa":"ar","th-th":"th","id-id":"id",tl:"fil","fil-ph":"fil","uk-ua":"uk","vi-vn":"vi"};function Be(i){if(typeof i!="string"||!i.trim())throw new Oe(i);const e=i.trim().replace(/_/g,"-").toLowerCase(),t=ht.find(r=>r.toLowerCase()===e);if(t)return t;const n=dt[e];if(!n)throw new Oe(i);return n}const ce=class ce{constructor(e,t){if(this.data=e,this.fallback=t,e.schema!=="teaql.i18n/v1")throw new Error("Unsupported i18n schema");Object.keys(e.locales).forEach(Be)}message(e,t){return this.data.locales[e]?.messages[t]??this.fallback?.data.locales[e]?.messages[t]??this.data.locales.en?.messages[t]??this.fallback?.data.locales.en?.messages[t]??t}translate(e,t){const r={required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"}[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,o=String(e.inputValue),s=typeof e.inputValue=="string"?[...e.inputValue].length:0;return e.message=this.message(t,r).split("{location}").join(e.location.nativePath()).split("{system}").join(String(e.systemValue)).split("{input}").join(o).split("{input_len}").join(String(s)),e}};ce.builtin=new ce(ut);let me=ce;const Qe=Symbol("teaql.context.schema-capability");function C(i){return Object.freeze(i.map(e=>Object.freeze({...e})))}class ft{#e;#t;constructor(e,t){this.#e=e,this.#t=Object.freeze({...t}),Object.freeze(this)}recover(){const e=[];let t=this;for(;t;)e.push(t.#t),t=t.#e;return C(e.reverse())}}function gt(i,e,t,n,r){const o=i?r:n;if(i&&(typeof o!="string"||new RegExp("^\\p{White_Space}*$","u").test(o)))return i;const s=String(t),a=/^(0|[1-9][0-9]*)$/.test(s)&&BigInt(s)<=18446744073709551615n?t:void 0;return new ft(i,{kind:"auditReason",name:e,entityId:a,detail:o})}const pt=new Set(["comment","purpose","auditReason"]),ue=i=>!new RegExp("^\\p{White_Space}*$","u").test(i);function ye(i,e,t){const n=s=>{for(let a=i.length-1;a>=0;a--)if(i[a].kind===s)return i[a].detail??""},r=["operation","provider","sql"].every(s=>i.some(a=>a.kind===s));let o;if(r)o=i.filter(s=>!pt.has(s.kind));else{const s=i.find(c=>ue(c.name))?.name??"unknown";let a=s;if(t!=="select")for(const c of i)c.kind==="entity"&&ue(c.name)&&(a=c.name);o=[{kind:"operation",name:s,detail:t==="select"?"query":"mutation"},{kind:t==="select"?"request":"entity",name:t==="select"?s:a,detail:""},...i.filter(c=>c.kind==="relation"),{kind:"provider",name:ue(e)?e:"unknown",detail:""},{kind:"sql",name:t,detail:""}]}return Object.freeze({tracePath:C(o),comment:n("comment"),purpose:n("purpose"),auditReason:n("auditReason")})}function ze(i,e,t){return C([{kind:"comment",name:i,detail:e},{kind:"purpose",name:i,detail:t}])}function mt(i,e,t,n){if(n&&!i.trim())throw new Error("Missing SQL template");let r=0;const o=new Set,s=u=>{if(u<0||u>=e.length)throw new Error("SQL bind count mismatch");return o.add(u),n?n(u):Ue(e[u],t)};let a="",c="sql";for(let u=0;u=0&&h=0&&ht.toString(16).padStart(2,"0")).join("")}'`:_(typeof i=="object"?JSON.stringify(i):String(i))}function _(i){return`'${i.replace(/'/g,"''")}'`}var yt={};const wt="TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS",bt="I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK",te="[REDACTED]",he="[REDACTED SQL; NOT REPLAYABLE]",St=`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN -`;let Re=!1;function vt(i){const e=Array.from(i);return e.length<8||/^[0-9]+$/.test(i)?"*".repeat(e.length):e.slice(0,2).join("")+"*".repeat(e.length-4)+e.slice(-2).join("")}function Et(){const e=yt?.[wt]===bt;return e&&!Re&&(Re=!0,console.warn("TeaQL: sensitive plaintext logging enabled; application data may be written to disk. Authentication secrets remain redacted.")),e}function W(i){const e=i.toLowerCase().replace(/[^a-z0-9]/g,"");return["password","passwd","passphrase","privatekey","secret","accesstoken","refreshtoken","idtoken","apikey","authorization","credential","sessiontoken","magiclinktoken"].some(t=>e.includes(t))}function we(i){return Array.isArray(i)?i.some(we):i&&typeof i=="object"?Object.entries(i).some(([e,t])=>W(e)||we(t)):!1}function q(i){return i==null||i===""?[]:Array.isArray(i)?i.flatMap(q):i instanceof Date?[i.toISOString()]:typeof i=="object"?Object.values(i).flatMap(q):[String(i)]}function V(i,e){return[...new Set(e)].sort((t,n)=>n.length-t.length).reduce((t,n)=>t?.split(n).join(te),i)}const K=new WeakMap,be=new WeakMap,Ve=new WeakMap;function ke(i,e,t=[]){Ve.set(i,{bindings:e?R(e):void 0,intentValues:Object.freeze(t.map(G))})}function ie(i){const e=i.parameterLogPolicies,t=!!e&&e.length===i.parameters.length,n=W(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!t);return i.parameters.map((r,o)=>{if(n||we(r))return"credential";const s=t?e[o]:void 0;return s==="plain"||s==="masked"||s==="credential"?s:"unknown"})}function Se(i,e){return i==="credential"||i==="unknown"||!e&&i!=="plain"}function Ce(i){if(!i)return[];const e=ie(i);return i.parameters.flatMap((t,n)=>Se(e[n],!1)?q(t):[])}function G(i){return i instanceof Date?new Date(i.getTime()):i instanceof Uint8Array?new Uint8Array(i):Array.isArray(i)?Object.freeze(i.map(G)):i&&typeof i=="object"?Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,G(t)]))):i}function R(i,e){const t=e?[e,i]:[i];return Object.freeze({parameterizedSQL:"",sqlOrigin:"generated",parameters:Object.freeze(t.flatMap(n=>n.parameters.map(G))),parameterLogPolicies:Object.freeze(t.flatMap(ie))})}function ve(i){return i==null?null:Array.isArray(i)?i.map(ve):i&&typeof i=="object"&&"type"in i?ve(i.value):typeof i=="object"&&!(i instanceof Date)?te:vt(i instanceof Date?i.toISOString():String(i))}function Ke(i,e,t=[]){const n=Et()&&i.logMode!=="masked",r=K.get(i);if(r!==void 0&&(!r||n))return i;const o=be.get(i);if(!n&&o)return o;const s=ne(i,n,e,t);if(K.set(s,n),n){const a=ne(i,!1,e,t);K.set(a,!1),be.set(s,a)}return s}function It(i){const e=be.get(i);if(e)return e;if(K.get(i)===!1)return i;const t=ne(i,!1);return K.set(t,!1),t}function ne(i,e,t,n=[]){const r=Ve.get(i);r?.bindings&&(t=R(r.bindings,t)),r&&(n=[...n,...r.intentValues]);const o=i.parameterLogPolicies,s=!o||o.length===i.parameters.length,a=W(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!o||!s),c=ie(i),u=c.map(w=>Se(w,e)),l=i.parameters.flatMap((w,v)=>u[v]?q(w):[]);if(t){const w=ie(t);l.push(...t.parameters.flatMap((v,I)=>Se(w[I],e)?q(v):[]))}const f=[...l,...n.flatMap(q)],g=!e&&i.logMode==="debug-plaintext"&&!t,h=w=>g&&w?te:V(w,f),p=i.parameters.map((w,v)=>u[v]?c[v]==="masked"?ve(w):te:G(w)),m=i.parameterizedSQL.replace(/\$[0-9]+|@p[0-9]+/gi,"?"),y=(!e||a)&&i.sqlOrigin!=="generated"&&/['"`$]|--|\/\*|\b\d+\b|:[A-Za-z_]/.test(m),d=i.databaseKind??"sqlite";let b=he,E=y?"untrusted-literal-sql":s?void 0:"policy-count-mismatch";if(!y&&s)try{b=mt(i.parameterizedSQL,p,d,w=>Ue(p[w],d)+(u[w]?" /* masked */":"")),b=(e?u.some(Boolean)?`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN; PARTIALLY MASKED; NOT REPLAYABLE -`:St:`-- TeaQL MASKED; NOT REPLAYABLE -`)+b}catch{b=he,E="unsupported-or-mismatched-bindings"}return Object.freeze({...i,...i.statements?{statements:Object.freeze(i.statements.map(w=>ne(w,e,R(i,t),n)))}:{},parameterizedSQL:y?he:i.sqlOrigin==="generated"?i.parameterizedSQL:V(i.parameterizedSQL,l),parameters:Object.freeze(p),parameterLogPolicies:Object.freeze(c),maskedParameters:Object.freeze(u),logMode:e?"debug-plaintext":"masked",omissionReason:E,debugSQL:b,comment:h(i.comment),purpose:h(i.purpose),auditReason:h(i.auditReason),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},resultSummary:i.resultCount!==void 0?`${i.resultCount} rows returned`:i.affectedRows!==void 0?`${i.affectedRows} rows affected`:V(i.resultSummary,l),tracePath:Object.freeze(i.tracePath.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I]))))),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},...i.mutationLineage?{mutationLineage:Object.freeze(i.mutationLineage.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{}})}const H=new WeakMap,re=new WeakMap;function _e(i){return re.get(i)}function Lt(i,e){re.set(i,e)}function $t(i){return H.get(i)}function Q(i,e){H.set(e,H.get(i)??M(i))}function M(i,e=new Map){if(!i||typeof i!="object")return i;if(e.has(i))return e.get(i);if(i instanceof Date)return new Date(i.getTime());if(i instanceof Uint8Array)return new Uint8Array(i);const t=Array.isArray(i)?[]:Object.create(Object.getPrototypeOf(i));e.set(i,t);for(const o of Reflect.ownKeys(i)){const s=Object.getOwnPropertyDescriptor(i,o);"value"in s&&s.enumerable&&(s.value=M(s.value,e)),Object.defineProperty(t,o,s)}const n=H.get(i);n&&H.set(t,n);const r=re.get(i);return r&&re.set(t,r),t}const X=new WeakMap;class Le{#e;constructor(e={}){this.#e=M(e),Object.freeze(this)}values(){return M(this.#e)}static captureFor(e,t){const n=new Le(t);return X.set(e,n),n}static forEntity(e){return X.get(e)}static restoreFor(e,t){t?X.set(e,t):X.delete(e)}}const Pe=new WeakMap,de=new WeakMap,Ee=new WeakMap,We=new WeakMap;function Ge(i){if(!["named-count","facet","relation-count","relation-select","aggregate","pagination"].includes(i.kind)||i.method!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i.method)||i.alias!==void 0&&typeof i.alias!="string"||i.relation!==void 0&&typeof i.relation!="string")throw new Error("QUERY_OPERATION_INVALID: invalid generated operation descriptor");return Object.freeze({kind:i.kind,method:i.method,alias:i.alias,relation:i.relation})}function Tt(i){const e=Ge(i),t=n=>"'"+n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+"'";return e.method?e.method+"("+(e.alias!==void 0?t(e.alias):e.kind==="relation-select"?"...":"")+")":"framework: "+e.kind+(e.relation?" "+e.relation:"")+(e.alias!==void 0?" "+t(e.alias):"")}const F=Symbol("runtime request binding");class At extends Error{constructor(e,t,n){super(`${e}: ${n} request requires a non-blank ${t}; supply it at the request entry point`),this.code=e,this.field=t,this.requestKind=n,this.name="RequestIntentError"}}function B(i,e,t){if(typeof i!="string"||new RegExp("^\\p{White_Space}*$","u").test(i))throw new At(e==="comment"?"REQUEST_COMMENT_REQUIRED":"QUERY_PURPOSE_REQUIRED",e,t);return i}class se{#e;#t;constructor(e,t){this.#e=B(e,"comment","query"),this.#t=B(t,"purpose","query"),Object.freeze(this)}get comment(){return this.#e}get purpose(){return this.#t}}class z{#e;constructor(e){this.#e=B(e,"comment","mutation"),Object.freeze(this)}get comment(){return this.#e}get auditReason(){return this.#e}readbackIntent(){return new se(this.#e,"verify persisted mutation result")}}class L{#e;#t;#n;#r;#s;#o;#i;constructor(e,t,n){const r=e,o=_e(e),s=o instanceof L?o:void 0;if(this.#e=t===void 0?s?.intent??new se(r?._comment??r?.commentText,r?._purpose??r?.purposeText):new se(t?.comment,t?.purpose),n&&n[F]!==!0)throw new Error("QUERY_REQUEST_OWNERSHIP_INVALID: request binding is runtime-owned");const a=s&&s.intent.comment===this.#e.comment&&s.purpose===this.#e.purpose?s:void 0;this.#i=n?.invocation??(n?.parent?n.parent.#i:void 0)??(a?a.#i:void 0)??Object.freeze({}),this.#n=n?n.parent:a?.parentRequest,this.#r=B(n?.comment??a?.comment??this.#e.comment,"comment","query"),this.#s=n?.name??a?.requestName??String(r.entity??"query"),this.#o=n?.operation??a?.operation,this.#t=M(e);const c=this.#t;for(const[u,l]of[["commentText",this.comment],["purposeText",this.purpose],["_comment",this.comment],["_purpose",this.purpose]])Object.defineProperty(c,u,{value:l,enumerable:!u.startsWith("_"),configurable:!0,writable:!1});de.set(c,C(n?.source??a?.traceSource??de.get(e)??ze(String(r.entity),this.intent.comment,this.purpose))),Lt(c,this),Object.freeze(this)}get intent(){return this.#e}get query(){return this.#t}get comment(){return this.#r}get purpose(){return this.#e.purpose}get traceSource(){return de.get(this.#t)}get parentRequest(){return this.#n}get rootRequest(){let e=this;for(;e.parentRequest;)e=e.parentRequest;return e}get requestName(){return this.#s}get operation(){return this.#o}get traceChain(){const e=[];for(let t=this;t;t=t.parentRequest)e.push({kind:"comment",name:t.requestName,detail:t.comment});return C([{kind:"purpose",name:this.rootRequest.requestName,detail:this.purpose},...e.reverse()])}withQuery(e){const t=_e(e);if(t instanceof L&&t.#i!==this.#i)throw new Error("QUERY_SCOPE_OWNER_MISMATCH: replacement belongs to another query invocation");return new L(e,this.intent,{[F]:!0,parent:this.parentRequest,comment:this.comment,name:this.requestName,operation:this.operation,source:this.traceSource,invocation:this.#i})}deriveOperation(e,t){const n=Ge(t);return new L(e,this.intent,{[F]:!0,parent:this,comment:Tt(n),name:String(e.entity??this.requestName),operation:n,source:this.traceSource})}deriveHelper(e,t){return new L(e,this.intent,{[F]:!0,parent:this,comment:B(t,"comment","query"),name:String(e.entity??this.requestName),source:this.traceSource})}derive(e,t,n){if(n)return this.deriveOperation(this.query,n).deriveChild(e,t);const r=`${String(this.query.entity)}.${t}`;return this.deriveChild(e,t,void 0,r)}deriveAggregate(e,t,n){const r=this.parentRequest?.operation?.kind==="facet"?this.parentRequest:void 0,o=r?r.deriveHelper(e,"aggregate "+r.operation.relation):this.deriveOperation(e,n),s=[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}],a=new L(e,this.intent,{[F]:!0,parent:o.parentRequest,comment:o.comment,name:o.requestName,operation:o.operation,source:s});return(e._comment??e.commentText)===void 0?a:a.deriveChild(e)}deriveChild(e,t,n,r){const o=e,s=o._comment??o.commentText;return new L(e,this.intent,{[F]:!0,parent:this,comment:s===void 0?n??`load ${String(o.entity)}`:B(s,"comment","query"),name:r??String(o.entity),source:t===void 0?this.traceSource:[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}]})}}class x{#e;#t;constructor(e,t){this.#e=new z(t===void 0?e?.comment:t?.comment),this.#t={...e},Object.defineProperty(this.#t,"comment",{value:this.#e.comment,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get intent(){return this.#e}get mutation(){return this.#t}get comment(){return this.#e.comment}withLoadedSnapshot(e){return Pe.set(this,new Le(e.values())),this}loadedValues(){return Pe.get(this)?.values()??{}}get graphSession(){return Ee.get(this)?.session}scopeFor(e){const t=Ee.get(this),n=gt(t?.parent,e.entity,e.id,this.comment,t?.localComment);return t&&We.set(n,t.session),n}traceFor(e){const t=this.#t,n=t.ledgerRoot?.traceChain(t.ledgerKey??e);return n?.length?C(n):this.scopeFor(e).recover()}auditProjection(e,t,n){const r=[...q(t),...q(this.#t.id),...n?Ce(n):q(this.loadedValues()),...Ce(this.graphSession?.logBindings)];return Object.freeze({reason:V(this.comment,r),mutationLineage:C(this.traceFor(e).map(o=>({...o,detail:V(o.detail,r)})))})}}class Ot{#e;#t;constructor(e){this.#e=new z(e?.comment),Object.freeze(this)}get intent(){return this.#e}request(e,t,n){if(t&&We.get(t)!==this)throw new Error("GRAPH_TRACE_SCOPE_MISMATCH: parent scope belongs to another graph invocation");const r=new x(e,this.#e);return Ee.set(r,{session:this,parent:t,localComment:n}),r}captureLogBindings(e){this.#t=R(e,this.#t)}get logBindings(){return this.#t}}class qe extends Error{constructor(e){super("GRAPH_ALREADY_COMMITTED: post-commit processing failed; do not retry as an uncommitted mutation"),this.cause=e,this.committed=!0,this.name="GraphCommittedError"}}const Rt="MUTATION-POLICY-001",kt="MUTATION-POLICY-002";class k extends Error{constructor(e){super(e),this.name="MutationPolicyError"}}class ci{constructor(e){this.resolver=e}resolve(e){return this.resolver(e)}}class li{constructor(e){this.finder=e}findApproval(e){return this.finder(e)}}class Ct{onWarning(e,t){!t.firstOccurrence||typeof console>"u"||console.warn(`TeaQL mutation policy warning code=${t.warningCode} requestKey=${t.snapshot.requestKey} source=${t.snapshot.source} approval=${t.snapshot.approvalStatus}`)}}let Ne=0;class _t{constructor(){this.profile={warningSink:new Ct},this.emittedWarnings=new Set,this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.remaining=new Map}setRegistry(e){this.profile.registry=e}setApprovalProvider(e){this.profile.approvalProvider=e}setWarningSink(e){this.profile.warningSink=e}beginGraph(){if(this.graphActive)throw new k("mutation policy graph is already active");this.graphActive=!0,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}endGraph(){this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}recordPreflight(e){if(!this.graphActive)return;if(this.graphReviewed)throw new k("mutation preflight cannot change after policy review");const t=xe(e);this.rootEntity??=t.entity,this.auditReason??=J(e),this.preflight.push(t),this.preflightKeys.push(Me(e,t))}enterMutation(e,t){const n=xe(t);if(!this.graphActive)return{snapshot:this.review(e,this.plan(n.entity,J(t),[n]))};if(!this.graphReviewed){if(this.profile.registry&&this.preflight.length===0)throw new k("customer mutation policy requires complete graph preflight before provider mutation");if(!this.profile.registry&&this.preflight.length===0)return{snapshot:this.review(e,this.plan(n.entity,J(t),[n]))};const r=this.preflight.length?this.preflight:[n];this.graphSnapshot=this.review(e,this.plan(this.rootEntity??r[0].entity,this.auditReason??J(t),r)),this.remaining.clear();const o=this.preflight.length?this.preflightKeys:r.map(Ye);for(const s of o)this.remaining.set(s,(this.remaining.get(s)??0)+1);this.graphReviewed=!0}return this.consume(Me(t,n)),{snapshot:this.graphSnapshot}}ensureGraphComplete(){if(this.graphReviewed&&this.remaining.size)throw new k("reviewed mutation plan contains operations that were not executed")}review(e,t){Pt(t);const n=je(t),r=this.profile.registry?.resolve(n.requestKey);let o,s,a,c;if(!r)o="generated_default",a="not_applicable",c=[Rt];else{s=qt(r.identity);const l=r.review(e,n);if(!l||l.verdict!=="allow"&&l.verdict!=="deny")throw new k("customer mutation policy returned an invalid decision");if(l.verdict==="deny")throw new k(`[MUTATION POLICY DENIED] ${l.code||"MUTATION-POLICY-DENIED"}: ${l.message||"mutation rejected"}`);o="customer";const f=this.profile.approvalProvider?.findApproval(s);a=Nt(f,s)?"approved":"missing",c=a==="approved"?[]:[kt]}const u=Object.freeze({executionId:n.executionId,requestKey:n.requestKey,source:o,policy:s,approvalStatus:a,warningCodes:Object.freeze([...c]),operations:Object.freeze(n.operations.map(l=>Object.freeze({kind:l.kind,entity:l.entity,entityId:j(l.entityId),changedFields:Object.freeze(Object.keys(l.changedValues).sort())})))});for(const l of c)this.emitWarning(e,u,l);return u}plan(e,t,n){return Ne+=1,je({executionId:`teaql-mutation-${Ne}`,requestKey:`${e}.saveGraph`,rootEntityType:e,auditReason:new z(t).comment,operations:n})}consume(e){const t=this.remaining.get(e)??0;if(t<1)throw new k("provider mutation is not present in the reviewed graph plan");t===1?this.remaining.delete(e):this.remaining.set(e,t-1)}emitWarning(e,t,n){const r=t.policy?`${t.policy.policyId}:${t.policy.version}:${t.policy.fingerprint}`:"none",o=`${t.requestKey}|${r}|${n}`,s=!this.emittedWarnings.has(o);this.emittedWarnings.add(o);try{this.profile.warningSink.onWarning(e,Object.freeze({snapshot:t,warningCode:n,firstOccurrence:s}))}catch{}}}function xe(i){const e=String(i?.entity??"").trim(),t=String(i?.action??"").toLowerCase(),n={create:"create",update:"update",delete:"delete",recover:"recover"};if(!e||!n[t])throw new k("mutation must contain a supported entity operation");const r=i?.payload&&typeof i.payload=="object"?i.payload:{};return Object.freeze({kind:n[t],entity:e,entityId:j(i?.id??r.id),originalVersion:i?.version??i?.expectedVersion,changedValues:He(r)})}function J(i){return new z(i?.comment).comment}function Pt(i){if(new z(i?.auditReason),!i.executionId?.trim())throw new k("execution id is required");if(!i.requestKey?.trim())throw new k("request key is required");if(!i.rootEntityType?.trim())throw new k("root entity type is required");if(!i.operations.length)throw new k("mutation plan is empty")}function qt(i){if(!i||!i.policyId?.trim()||!i.version?.trim()||!i.fingerprint?.trim())throw new k("customer mutation policy identity is invalid");return Object.freeze({policyId:i.policyId.trim(),version:i.version.trim(),fingerprint:i.fingerprint.trim()})}function Nt(i,e){return!!i&&xt(i.policy,e)&&!!i.approvedBy?.trim()&&i.approvedAt instanceof Date&&Number.isFinite(i.approvedAt.getTime())&&i.approvedAt.getTime()!==0}function xt(i,e){return i.policyId===e.policyId&&i.version===e.version&&i.fingerprint===e.fingerprint}function je(i){return Object.freeze({executionId:i.executionId,requestKey:i.requestKey,rootEntityType:i.rootEntityType,auditReason:i.auditReason,operations:Object.freeze(i.operations.map(e=>Object.freeze({kind:e.kind,entity:e.entity,entityId:j(e.entityId),originalVersion:e.originalVersion,changedValues:He(e.changedValues)})))})}function j(i,e=new WeakSet){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||typeof i=="bigint")return i;if(i instanceof Date)return i.toISOString();if(typeof i=="object"){if(e.has(i))throw new k("mutation policy values must not contain cycles");e.add(i);try{if(Array.isArray(i))return Object.freeze(i.map(n=>j(n,e)));const t=i;return"id"in t&&Object.keys(t).some(n=>n!=="id")?j(t.id,e):Object.freeze(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,j(r,e)])))}finally{e.delete(i)}}return String(i)}function He(i){return Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,j(t)])))}function Ye(i){return oe({kind:i.kind,entity:i.entity,entityId:i.entityId,originalVersion:i.originalVersion,changedValues:i.changedValues})}function Me(i,e){const t=i?.ledgerKey;return t&&typeof t=="object"&&String(t.entity??"").trim()&&t.id!==void 0&&t.id!==null?`ledger:${String(t.entity).trim()}:${oe(t.id)}`:`operation:${Ye(e)}`}function oe(i){return typeof i=="bigint"?JSON.stringify(`${i.toString()}n`):i===void 0?'""':i===null||typeof i!="object"?JSON.stringify(i):Array.isArray(i)?`[${i.map(oe).join(",")}]`:`{${Object.entries(i).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${oe(t)}`).join(",")}}`}const De=new WeakMap;let jt=1;function Mt(i){if(!i||typeof i!="object"&&typeof i!="function")return String(i);const e=i;let t=De.get(e);return t||(t=jt++,De.set(e,t)),String(t)}class Fe extends Error{constructor(e,t,n){super(`context root ${e}: expected ${t}`),this.reason=e,this.expectedType=t,this.activeRoot=n,this.name="ContextRootError"}}class Dt{constructor(){this.mutationPolicy=new _t,this.resources=new Map,this.continuousPageCursors=new Map,this.retainedIdSets=new Map,this.idSetBuilds=new Map,this.continuousPageRuntime={owner:"",get:(e,t)=>this.getContinuousPageCursor(e,t),put:(e,t,n)=>this.putContinuousPageCursor(e,t,n),observe:(e,t)=>{this.continuousPagePlan=e,this.continuousPageCursorId=t}},this.idSetPaginationRuntime={owner:"",scope:"",get:e=>this.idSetStore().get(e),put:(e,t)=>this.idSetStore().put(e,t),build:(e,t)=>this.singleFlightIdSetBuild(e,t),observe:(e,t)=>{this.idSetPaginationPlan=e,this.idSetPaginationCount=t,this.idSetPaginationCountAccuracy=e==="ID_SET_BUILD"||e==="ID_SET_HIT"?"EXACT":e==="ID_SET_FALLBACK_LIMIT_EXCEEDED"?"LOWER_BOUND":"UNKNOWN"}},this.userIdentifier="",this.continuousPagePlan="DISABLED",this.idSetPaginationPlan="ID_SET_DISABLED",this.idSetPaginationCountAccuracy="UNKNOWN",this.locale="en",this.i18nCatalog=me.builtin}async withQueryRequest(e,t){const n=this.requireResource("dataService");return n.withQueryRequest?n.withQueryRequest(e,t):t()}setLocaleCode(e){const t=Be(e);return this.locale=t,this}setLanguageCode(e){return this.setLocaleCode(e)}installI18nCatalog(e){if(!e)throw new Error("catalog is required");return this.i18nCatalog=e,this}installIdSetPaginationStore(e){if(!e)throw new Error("ID set pagination store is required");return this.insertResource("idSetPaginationStore",e)}translateCheckResults(e){return e.map(t=>this.i18nCatalog.translate(t,this.locale))}withMutationPolicyRegistry(e){if(!e||typeof e.resolve!="function")throw new TypeError("mutation policy registry must expose resolve(requestKey)");return this.mutationPolicy.setRegistry(e),this}withMutationPolicyApprovalProvider(e){if(!e||typeof e.findApproval!="function")throw new TypeError("mutation policy approval provider must expose findApproval(identity)");return this.mutationPolicy.setApprovalProvider(e),this}withMutationGovernanceSink(e){if(!e||typeof e.onWarning!="function")throw new TypeError("mutation governance sink must expose onWarning(context, warning)");return this.mutationPolicy.setWarningSink(e),this}reviewMutationPlan(e){return this.mutationPolicy.review(this,e)}beginMutationPolicyGraph(){this.mutationPolicy.beginGraph()}recordMutationPolicyPreflight(e){this.mutationPolicy.recordPreflight(e)}enterMutationPolicy(e){return this.mutationPolicy.enterMutation(this,e).snapshot}ensureMutationPolicyGraphComplete(){this.mutationPolicy.ensureGraphComplete()}endMutationPolicyGraph(){this.mutationPolicy.endGraph()}beginFixEvidence(){return this.insertResource("fixEvidenceCurrent",[])}recordFixEvidence(e){const t=String(e.sourceLabel||""),n=t.toLowerCase();if(!e.entityType||!e.modelPath||!t||n.includes("authorization")||n.includes("cookie")||n.includes("token="))throw new TypeError("Fix evidence must contain only safe framework provenance labels");const r=this.getResource("fixEvidenceCurrent")??[];return this.getResource("fixEvidenceCurrent")||this.insertResource("fixEvidenceCurrent",r),r.push(Object.freeze({...e})),this}finishFixEvidence(){const e=this.getResource("fixEvidenceCurrent")??[];return this.insertResource("fixEvidenceLast",Object.freeze([...e])),this.removeResource("fixEvidenceCurrent")}lastFixEvidence(){return this.getResource("fixEvidenceLast")??[]}insertResource(e,t){return this.resources.set(e,t),this}getResource(e){return this.resources.get(e)}removeResource(e){return this.resources.delete(e),this}requireResource(e){const t=this.getResource(e);if(t===void 0)throw new Error(`Required UserContext resource is missing: ${e}`);return t}ensureSchema(){const e=this.requireResource("dataService"),t=e[Qe];if(!t)throw new Error("Configured dataService is not a schema-aware TeaQL provider");return t.call(e,this)}withActiveRoot(e){if(!e||!e.entity||e.id===void 0||e.id===null)throw new TypeError("active root must be a typed entity reference");return this.insertResource("activeRoot",Object.freeze({...e}))}requireActiveRoot(e){const t=this.getResource("activeRoot");if(!t)throw new Fe("missing",e);if(t.entity!==e)throw new Fe("type_mismatch",e,t);return t}prepareQuery(e){this.continuousPageRuntime.owner=this.userIdentifier,this.idSetPaginationRuntime.owner=this.userIdentifier;const t=this.getResource("activeRoot");return this.idSetPaginationRuntime.scope=[this.userIdentifier,t?`${t.entity}:${String(t.id)}`:"-",Mt(this.getResource("dataService"))].join("|"),e.bindContinuousPageRuntime(this.continuousPageRuntime).bindIdSetPaginationRuntime(this.idSetPaginationRuntime)}getContinuousPageCursor(e,t){const n=`${e}:${t}`,r=this.continuousPageCursors.get(n);if(r&&r.expiresAt<=Date.now()){this.continuousPageCursors.delete(n);return}return r}putContinuousPageCursor(e,t,n){if(this.continuousPageCursors.size>=4096){const r=[...this.continuousPageCursors.entries()].sort((o,s)=>o[1].expiresAt-s[1].expiresAt)[0];r&&this.continuousPageCursors.delete(r[0])}this.continuousPageCursors.set(`${e}:${t}`,n)}getRetainedIdSet(e){const t=this.retainedIdSets.get(e);if(t&&t.expiresAt<=Date.now()){this.retainedIdSets.delete(e);return}return t}idSetStore(){return this.getResource("idSetPaginationStore")??{get:e=>this.getRetainedIdSet(e),put:(e,t)=>this.putRetainedIdSet(e,t),invalidate:e=>{this.retainedIdSets.delete(e)}}}putRetainedIdSet(e,t){if(t.ids.byteLength>268435456)throw new Error("ID set exceeds the process-local store memory ceiling");const r=()=>[...this.retainedIdSets.values()].reduce((o,s)=>o+s.ids.byteLength,0);for(;this.retainedIdSets.size>=64||r()+t.ids.byteLength>268435456;){const o=[...this.retainedIdSets.entries()].sort((s,a)=>s[1].expiresAt-a[1].expiresAt)[0];if(!o)break;this.retainedIdSets.delete(o[0])}this.retainedIdSets.set(e,t)}async singleFlightIdSetBuild(e,t){const n=this.idSetBuilds.get(e);if(n)return{value:await n,built:!1};const r=t();this.idSetBuilds.set(e,r);try{return{value:await r,built:!0}}finally{this.idSetBuilds.delete(e)}}}function Xe(i,e){const t=i.defaultDomainRoot,n=e.defaultDomainRoot;if(t&&n&&(t.entity!==n.entity||t.id!==n.id))throw new Error("Cannot compose Runtime Modules with different Default Domain Roots");const r=new Map;for(const o of[...i.constants??[],...e.constants??[]])r.set(`${o.entity}:${o.id}`,o);return{defaultDomainRoot:n??t,constants:[...r.values()],ensure:i.ensure&&e.ensure?async o=>{await i.ensure(o),await e.ensure(o)}:e.ensure??i.ensure}}class Je{constructor(e={},t={},n={}){this.schemas=Object.freeze({...e}),this.checkers=Object.freeze({...t}),this.bootstrap=Object.freeze({defaultDomainRoot:n.defaultDomainRoot,constants:Object.freeze([...n.constants??[]]),ensure:n.ensure})}and(e){return new Je({...this.schemas,...e.schemas},{...this.checkers,...e.checkers},Xe(this.bootstrap,e.bootstrap))}}class P{constructor(e,t,n){this.field=e,this.expr=t,this.direction=n}static new(e,t){return new P(e,null,t)}static expr(e,t){return new P("",e,t)}static asc(e){return P.new(e,"Asc")}static desc(e){return P.new(e,"Desc")}}class ae{constructor(e,t,n,r){this.enabledValue=e,this.cacheExpiredMillis=t,this.propagateValue=n,this.propagateCacheExpiredMillis=r}static enabled(e){return new ae(!0,e,!1,0)}propagate(e){return this.propagateValue=!0,this.propagateCacheExpiredMillis=e,this}}let Ft=class Ze{constructor(e){this.hardLimitValue=1e4,this.filterCondition=null,this.limitValue=0,this.offsetValue=0,this.orderItems=[],this.selectItems=[],this.properties=[],this.joins=[],this.groupByItems=[],this.aggregateItems=[],this.facets=[],this.relations=[],this.relationAggregates=[],this.entity=e,Object.defineProperty(this,"hardLimitValue",{enumerable:!1,writable:!0,value:1e4}),Object.defineProperty(this,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"topNProbeThreshold",{enumerable:!1,writable:!0,value:void 0})}comment(e){return this.commentText=e,this}purpose(e){return this.purposeText=e,this}facetBy(e,t,n,r=!0,o){return this.facets.push({facetName:e,relationName:t,query:n.toQuery(),includeAllFacets:r,operation:o}),this}clone(){const e=M(this);for(const t of["commentText","purposeText","_comment","_purpose"]){const n=Object.getOwnPropertyDescriptor(e,t);n&&"value"in n&&n.configurable&&Object.defineProperty(e,t,{...n,writable:!0})}return e}filter(e){return this.filterCondition=e,this}limit(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.limitValue=e,this}optimizeForContinuousPageFetch(){return this.optimizeForContinuousPageFetchWith("default",600)}optimizeForContinuousPageFetchWith(e,t){if(!e?.trim())throw new Error("continuous page namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("continuous page ttlSeconds must be a positive integer");return this.continuousPageFetchOptions={namespace:e,ttlSeconds:t},this}bindContinuousPageRuntime(e){return this.continuousPageRuntimeContext=e,this}localContinuousPageOptions(){return this.continuousPageFetchOptions}localContinuousPageRuntime(){return this.continuousPageRuntimeContext}clearContinuousPageRuntime(){return this.continuousPageRuntimeContext=void 0,this}optimizePaginationWithIdSet(){return this.optimizePaginationWithIdSetConfig("default",600,3e6)}optimizePaginationWithIdSetConfig(e,t,n){if(!e?.trim())throw new Error("ID set namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("ID set ttlSeconds must be a positive integer");if(!Number.isSafeInteger(n)||n<=0)throw new Error("ID set maxIds must be a positive integer");return this.idSetPaginationOptions={namespace:e,ttlSeconds:t,maxIds:n},this}bindIdSetPaginationRuntime(e){return this.idSetPaginationRuntimeContext=e,this}localIdSetPaginationOptions(){return this.idSetPaginationOptions}localIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext}clearIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext=void 0,this}topNProbeParentThreshold(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("topNProbeParentThreshold must be a non-negative safe integer");return this.topNProbeThreshold=e,this}localTopNProbeParentThreshold(){return this.topNProbeThreshold}prepareForList(){if(!Number.isSafeInteger(this.offsetValue)||this.offsetValue<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");if(this.limitValue&&(!Number.isSafeInteger(this.limitValue)||this.limitValue<1))throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.applyListLimit(this.hardLimitValue),this}forExactCount(e="__teaql_total"){const t=new Ze(this.entity);return t.filterCondition=M(this.filterCondition),t.commentText=this.commentText,t.purposeText=this.purposeText,t.aggregate("Count","id",e),Q(this,t),t}applyListLimit(e){if(this.limitValue||(this.limitValue=e),this.limitValue>e)throw new Error(`QUERY_HARD_LIMIT_EXCEEDED: requested limit ${this.limitValue} exceeds hard limit ${e}`);for(const t of this.relations)t.query?.applyListLimit(1e4)}offset(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");return this.offsetValue=e,this}relation(e){return this.relations.push({name:e}),this}relationQuery(e,t,n="id",r="id",o=!0,s){return this.relations.push({name:e,query:t,localKey:n,foreignKey:r,many:o,operation:s}),this}relationAggregate(e,t,n,r=!0,o){return this.relationAggregates.push({relationName:e,alias:t,query:n,singleResult:r,operation:o}),this}order(e){return this.orderItems.push(e),this}select(e){return this.selectItems.push(...e),this}enableAggregationCacheFor(e){return this.aggregationCache=ae.enabled(e),this}propagateAggregationCache(e){return this.aggregationCache||(this.aggregationCache=ae.enabled(0)),this.aggregationCache.propagate(e),this}aggregate(e,t,n){return this.aggregateItems.push({function:e,field:t,alias:n}),this}groupBy(e){return this.groupByItems.push(e),this}};function Bt(i,e){if(i.logMode!=="masked")throw new Error("Telemetry requires safe SQL projection");const t=(n=[])=>JSON.stringify(n.map(r=>({kind:r.kind,name:r.name,detail:r.detail??""})));return Object.freeze({body:"TeaQL SQL execution",correlation:e,attributes:Object.freeze({"teaql.trace_chain":t(i.traceChain),"teaql.trace_path":t(i.tracePath),"teaql.mutation_lineage":t(i.mutationLineage),"teaql.intent.comment":i.comment??i.auditReason??"","teaql.intent.purpose":i.purpose??"","teaql.sql.debug":i.debugSQL,"teaql.sql.log_mode":i.logMode,"teaql.sql.operation":i.operation,"teaql.sql.outcome":i.executionOutcome??"unknown","teaql.sql.elapsed_us":i.elapsedMicros,...i.resultCount===void 0?{}:{"teaql.sql.result_count":i.resultCount},...i.affectedRows===void 0?{}:{"teaql.sql.affected_rows":i.affectedRows}})})}function fe(i,e=!1){try{e?console.warn(i):console.info(i)}catch{}}class Y extends Array{static get[Symbol.species](){return Array}constructor(e=[],t={}){typeof e=="number"?super(e):super(...e),Object.setPrototypeOf(this,Y.prototype),this.totalCount=t.totalCount,this.aggregations=t.aggregations??{},this.summary=t.summary??{},this.facets=t.facets??{},this.isLoaded=t.isLoaded??!0}static empty(){return new Y([],{isLoaded:!1})}get data(){return this}withTotalCount(e){return this.totalCount=e,this}withFacet(e,t){return this.facets[e]=t,this}facet(e){return this.facets[e]}totalCountOrLength(){return this.totalCount??this.length}}function Qt(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Ie(i){if(i&&typeof i=="object"){const e=i;return e.id??e.Id}return i}function zt(i,e){const t=Qt(e);for(const n of[e,`${e}Id`,t,`${t}_id`]){const r=Ie(i[n]);if(r!=null)return r}}function Ut(i){const e=i.function.toLowerCase();return e==="count"||e==="sum"?0:null}function Vt(i,e){return typeof i=="number"&&typeof e=="number"?i-e:i instanceof Date&&e instanceof Date?i.getTime()-e.getTime():String(i).localeCompare(String(e))}async function Kt(i,e,t,n,r,o){const s=n.clone();s.facets=[],s.relations=[],s.relationAggregates=[],s.orderItems=[],s.aggregateItems=[],s.groupByItems=[],s.offsetValue=0,s.limitValue=0,s.selectItems=[...new Set([r,...o.map(l=>l.field)])],s.comment(`aggregate ${r}`),Q(n,s);const a=await i.executeQuery(t.deriveHelper(e(s),`aggregate ${r}`).query),c=new Map,u=new Map;for(const l of a){const f=zt(l,r);if(f==null)continue;const g=String(f),h=c.get(g)??{},p=u.get(g)??{};for(const m of o){const y=m.function.toLowerCase(),d=l[m.field];if(y==="count")d!=null&&(h[m.alias]=Number(h[m.alias]??0)+1);else if(y==="sum"||y==="avg"){if(d!=null){const b=Number(d);if(!Number.isFinite(b))throw new Error(`Facet aggregate ${m.alias} requires numeric values`);h[m.alias]=Number(h[m.alias]??0)+b,y==="avg"&&(p[m.alias]=(p[m.alias]??0)+1)}}else if(y==="min"||y==="max"){if(d!=null){const b=h[m.alias],E=b==null?0:Vt(d,b);(b==null||y==="min"&&E<0||y==="max"&&E>0)&&(h[m.alias]=d)}}else throw new Error(`Unsupported facet aggregate: ${m.function}`)}c.set(g,h),u.set(g,p)}for(const[l,f]of c){const g=u.get(l)??{};for(const h of o){if(h.function.toLowerCase()!=="avg")continue;const p=g[h.alias]??0;f[h.alias]=p?Number(f[h.alias]??0)/p:null}}return c}async function et(i,e,t,n){const r=new L(t);t=r.query;const o={};for(const s of n){const a=r.deriveOperation(t,s.operation??{kind:"facet",relation:s.relationName,alias:s.facetName}),c=a.deriveChild(s.query.clone(),s.relationName),u=c.query,l=u.facets;u.facets=[];const f=u.aggregateItems.map(d=>({function:String(d.function),field:String(d.field),alias:String(d.alias)})),g=f.length?f:[{function:"Count",field:"id",alias:"__teaql_facet_membership_count"}];let h;if(i.executeFacetAggregates)h=await i.executeFacetAggregates(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName,g);else if(i.executeFacetMembership&&g.every(d=>d.function.toLowerCase()==="count")){const d=await i.executeFacetMembership(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName);h=new Map([...d].map(([b,E])=>[b,Object.fromEntries(g.map(S=>[S.alias,E]))]))}else h=await Kt(i,e,a,t,s.relationName,g);u.aggregateItems=[],u.groupByItems=[];for(const d of u.relationAggregates){if(d.query.entity!==t.entity)continue;const b=t.clone();b.selectItems=["id"],b.properties=[],b.relations=[],b.relationAggregates=[],b.facets=[],b.aggregateItems=[],b.groupByItems=[],b.orderItems=[],b.offsetValue=0,b.limitValue=0;const E={id:{$inSubquery:{query:b,field:"id"}}};d.query.filterCondition=d.query.filterCondition?{$and:[d.query.filterCondition,E]}:E,Q(t,d.query)}if(!s.includeAllFacets){const d={id:{$in:[...h.keys()]}};u.filterCondition=u.filterCondition?{$and:[u.filterCondition,d]}:d}Q(t,u);const m=(await i.executeQuery(c.withQuery(e(u)).query)).map(d=>{const b=String(Ie(d.id??d.Id)),E=h.get(b),S={...d};for(const w of f)S[w.alias]=E?.[w.alias]??Ut(w);return S}).filter(d=>s.includeAllFacets||h.has(String(Ie(d.id??d.Id)))),y=new Y(m);l.length&&(y.facets=await et(i,e,c.withQuery(u).query,l)),o[s.facetName]=y}return o}function Wt(i){const e=new Map;for(const t of Object.values(i))for(const n of Object.values(t.relations||{})){if(!n.many)continue;const r=i[n.targetEntity],o=r?.columns[n.foreignKey]?.columnName,s=r?.columns.id?.columnName;if(!r||!o||!s)continue;const a=`idx_${r.table}_${o}_${s}`;let c=2166136261;for(let f=0;f>>0).toString(36),l=a.length<=30?a:`${a.slice(0,Math.max(1,29-u.length))}_${u}`;e.set(l,{name:l,table:r.table,foreignColumn:o,idColumn:s})}return[...e.values()]}async function Gt(i,e,t,n){const r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ID space floor ${n} for ${t}`);for(let o=1;o<=100;o+=1){const s=await i.query(`SELECT current_level AS id FROM teaql_id_space WHERE type_name = ${e(1)}`,[t]);if(!s.rowCount){try{if((await i.query(`INSERT INTO teaql_id_space(type_name, current_level) VALUES (${e(1)}, ${e(2)})`,[t,r])).rowCount===1)return}catch(u){if(!(await i.query(`SELECT current_level FROM teaql_id_space WHERE type_name = ${e(1)}`,[t])).rowCount)throw u}continue}const a=Number(s.rows[0].id);if(a>=r)return;const c=await i.query(`UPDATE teaql_id_space SET current_level = ${e(1)} WHERE type_name = ${e(2)} AND current_level = ${e(3)}`,[r,t,a]);if(c.rowCount===1)return;if(c.rowCount!==0)throw new Error(`ID space floor update for ${t} changed ${c.rowCount} rows on attempt ${o}`)}throw new Error(`Unable to synchronize ID space floor for ${t} after 100 optimistic-lock attempts`)}function Ht(i,e){return i===e?!0:(i instanceof Date&&(i=i.getTime()),e instanceof Date&&(e=e.getTime()),i!=null&&e!==null&&e!==void 0&&String(i)===String(e))}function ee(i){return Object.freeze(i.map((e,t)=>Object.freeze({...e,level:t})))}function ge(i,e,t,n,r,o){const s=i.traceFor({entity:String(e.entity),id:r}),a=ye([...s,{kind:"entity",name:String(e.entity),entityId:r,detail:""}],t,n);return{auditReason:i.comment,tracePath:ee(a.tracePath),mutationLineage:s,targetID:r,inheritedBindings:R(o,i.graphSession?.logBindings)}}class Yt{constructor(e=t=>console.debug(t)){this.writer=e}write(e){e=Ke(e),this.writer(`[TeaQL SQL][${e.operation}][${e.elapsedMicros}us] ${e.resultSummary}${e.executionOutcome?` outcome=${e.executionOutcome}`:""} -comment=${e.comment??""} purpose=${e.purpose??""} auditReason=${e.auditReason??""} tracePath=${pe(e.tracePath)} traceChain=${pe(e.traceChain??[])} mutationLineage=${pe(e.mutationLineage??[])} -`+(e.omissionReason?`SQL omitted: ${e.omissionReason} -`:"")+`Debug SQL: ${e.debugSQL}`)}}function pe(i){return JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString():t)}class ui{constructor(){this.mode="all",this.entries=[]}record(e){const t=e.operation==="select";this.mode==="disabled"||this.mode==="select"&&!t||this.mode==="mutation"&&t||this.entries.push(Object.freeze({...e,...e.traceChain?{traceChain:C(e.traceChain)}:{},parameters:Object.freeze([...e.parameters])}))}setMode(e){return this.mode=e,this.entries=[],this}enableAll(){return this.setMode("all")}enableSelect(){return this.setMode("select")}enableMutation(){return this.setMode("mutation")}disable(){return this.setMode("disabled")}snapshot(){return[...this.entries]}}class Xt{constructor(e,t){this.driver=e,this.bootstrapTail=Promise.resolve(),this.sqlTrace=[],this.internalQueryToken=Symbol("teaql-internal-query"),this.bindLogPolicies=new WeakMap,this.bindOperandSources=new WeakMap,this.derivedQueryBindings=new WeakMap,this.derivedRelationAssembly=new WeakMap,this.auditEvents=[],this.diagnosticSQLLogSink=new Yt,this.queryLoggingEnabled=!0,this.mutationLoggingEnabled=!0,this.customTelemetry=!1,this.checkers={},this.userContext=new Dt,this.bootstrap={},this.graphAuditActions=[],this.graphCommitActions=[],this.graphRollbackActions=[],this.graphSaveTail=Promise.resolve(),this.schemas={...t}}fieldLogPolicy(e,t){const n=e.columns[t],r=n?.modelName??n?.columnName??t;return W(r)||W(t)?"credential":e.auditMaskFields?e.auditMaskFields?.includes(r)||e.auditMaskFields?.includes(t)?"masked":n?.logPolicy??"unknown":"unknown"}bindValue(e,t,n,r){const o=this.bindLogPolicies.get(e)??e.map(()=>"unknown");e.push(t),o.push(n),this.bindLogPolicies.set(e,o),r!==void 0&&this.bindOperandSources.set(e,R({parameterizedSQL:"",parameters:[r],parameterLogPolicies:[n],sqlOrigin:"generated"},this.bindOperandSources.get(e)))}queryLogBindings(e,t){return R({parameterizedSQL:e,parameters:t,parameterLogPolicies:this.bindLogPolicies.get(t),sqlOrigin:"generated"},this.bindOperandSources.get(t))}install(e){return Object.assign(this.schemas,e.schemas),Object.assign(this.checkers,e.checkers),this.bootstrap=Xe(this.bootstrap,e.bootstrap),this}setUserContext(e){return this.userContext=e,this}schema(e){const t=this.schemas[e];if(!t)throw new Error(`Unknown TeaQL entity: ${e}`);return t}toRuntimeMutationRecord(e,t){const n={};for(const[r,o]of Object.entries(t)){const s=e.columns[r]?r:Object.keys(e.columns).find(a=>e.columns[a].modelName===r||e.columns[a].columnName===r);s&&(n[s]=o)}return n}encode(e,t){const n=e?.id??e;if(n!==void 0)return this.driver.encode(n,t)}decodeRow(e,t,n=[]){const r=this.schema(e),o={...t};for(const[s,a]of Object.entries(r.columns)){const c=o[s];c!=null&&(a.decode==="number"&&(o[s]=Number(c)),a.decode==="string"&&(o[s]=String(c)),a.decode==="date"&&c instanceof Date&&(o[s]=c.toISOString()),a.logicalType==="boolean"&&(o[s]=!!c))}for(const s of n)o[s]!==null&&o[s]!==void 0&&(o[s]=Number(o[s]));return o}get auditTrace(){return[...this.auditEvents]}setAuditSink(e){return this.auditSink=e,this}setRuntimeTelemetrySink(e){return this.telemetrySink=e,this}setDiagnosticSQLLogSink(e){return this.diagnosticSQLLogSink=e,this}setQueryLoggingEnabled(e){return this.queryLoggingEnabled=e,this}setMutationLoggingEnabled(e){return this.mutationLoggingEnabled=e,this}setRuntimeTelemetry(e){return this.customTelemetry=!0,this.runtimeTelemetry=e,this}attachStandardTelemetryStartup(e){this.telemetryStartup=e.then(async t=>{if(t){if(this.customTelemetry){await t.release();return}this.standardTelemetryHandle=t,this.runtimeTelemetry=t.telemetry}}).catch(()=>{fe("TeaQL telemetry: initialization failed; business continues without export.",!0)})}async flushTelemetry(){await this.telemetryStartup;try{await this.standardTelemetryHandle?.flush()}catch{fe("TeaQL telemetry: export flush failed; business outcome unchanged.",!0)}}async withQueryRequest(e,t){return new L(e),await this.telemetryStartup,D(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.request`,attributes:{"teaql.entity.type":String(e.entity)}},t)}recordSQL(e,t,n,r,o,s,a={},c="success",u,l){const g=e==="select"?this.queryLoggingEnabled:this.mutationLoggingEnabled,{targetID:h,inheritedBindings:p,...m}=a,y=Object.freeze({operation:e,...m,executionOutcome:c,traceChain:C(a.traceChain??[]),tracePath:ee(a.tracePath??[]),...a.traceChain?{traceChain:C(a.traceChain)}:{},...a.mutationLineage?{mutationLineage:C(a.mutationLineage)}:{},parameterizedSQL:t,parameters:Object.freeze([...n]),debugSQL:"",databaseKind:this.driver.databaseKind,sqlOrigin:"generated",parameterLogPolicies:Object.freeze([...this.bindLogPolicies.get(n)??n.map(()=>"unknown")]),elapsedMicros:Math.max(0,(Date.now()-r)*1e3),resultCount:o,affectedRows:s,resultSummary:o!==void 0?`${o} rows returned`:s!==void 0?`${s} rows affected`:`statement ${c}; row count unknown`}),d=p&&u?R(u,p):p??u,b=this.bindOperandSources.get(n),E=b?R(b,d):d;if(ke(y,E,h===void 0?[]:[h]),this.runtimeTelemetry?.recordDiagnostic)try{this.runtimeTelemetry.recordsSQLDiagnostics?.()!==!1&&this.runtimeTelemetry.recordDiagnostic(Bt(It(y),l))}catch{fe("TeaQL telemetry: SQL diagnostic rejected; business outcome unchanged.",!0)}if(!this.telemetrySink&&!(g&&this.diagnosticSQLLogSink))return y;try{const S=Ke(y);try{this.telemetrySink?.record(S)}catch{}if(g)try{this.diagnosticSQLLogSink?.write(S)}catch{}}catch{}return y}queryLogIntent(e){const t=new L(e),n=ye(t.traceSource,this.driver.databaseKind,"select");return{comment:t.intent.comment,purpose:t.purpose,traceChain:t.traceChain,tracePath:ee(n.tracePath)}}async executeLoggedSQL(e,t,n,r,o,s,a){await this.telemetryStartup;const c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.${e}`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":e==="select"?"query":e}}),u=c.correlation?.(),l=Date.now();let f;try{f=await(c.run?c.run(o):o())}catch(h){try{const p=this.recordSQL(e,t,n,l,void 0,void 0,r,"failure",s,u);a?.push(p)}finally{throw c.failure(h),h}}const g=this.recordSQL(e,t,n,l,e==="select"?f.rowCount:void 0,e==="select"?void 0:f.rowCount,r,"success",s,u);return a?.push(g),c.success({attributes:{"teaql.result.cardinality":f.rowCount}}),f}async[Qe](e){await this.telemetryStartup,this.schemaReady||(this.schemaReady=this.driver.ensureSchema(this.schemas)),await this.schemaReady;const t=this.bootstrapTail;let n;this.bootstrapTail=new Promise(s=>{n=s}),await t,this.userContext=e;const r=e.getResource("bootstrapActor"),o=e.getResource("bootstrapCategory");e.insertResource("bootstrapActor","teaql-generated-bootstrap"),e.insertResource("bootstrapCategory","runtime-bootstrap");try{this.bootstrap.ensure?await this.bootstrap.ensure(e):await this.ensureBootstrapData()}finally{r===void 0?e.removeResource("bootstrapActor"):e.insertResource("bootstrapActor",r),o===void 0?e.removeResource("bootstrapCategory"):e.insertResource("bootstrapCategory",o),n()}}invalidateSchemaState(){this.schemaReady=void 0}async ensureBootstrapData(){const e=[...this.bootstrap.defaultDomainRoot?[this.bootstrap.defaultDomainRoot]:[],...this.bootstrap.constants??[]];e.length&&await this.executeGraphSave(new z("reconcile model bootstrap data"),async t=>{const n=this.graphMutationSession,r=[];for(const o of e){const s=await this.planBootstrapMutation(n,o);s&&r.push({record:o,request:t.request(s)})}for(const{request:o}of r)this.preflightMutation(o);for(const{request:o}of r)await this.executeMutation(o);for(const o of e)await this.driver.ensureIdFloor(n,o.entity,o.id)})}async planBootstrapMutation(e,t){const n=this.schema(t.entity),r=Object.entries(t.values??{}).map(([g,h])=>{const p=n.columns[g];if(!p)throw new Error(`Unknown bootstrap field ${t.entity}.${g}`);return{column:p.columnName,value:this.driver.encode(h,p)}}),o=new Ft(t.entity).filter({id:{$eq:t.id}}).limit(1).comment("inspect model bootstrap record").purpose("ensure model-defined root and constants");o.prepareForList();const s=new L(o),a=`SELECT * FROM ${this.driver.identifier(n.table)} WHERE ${this.driver.identifier(n.columns.id?.columnName??"id")} = ${this.driver.placeholder(1)}`,c=[t.id];this.bindLogPolicies.set(c,[this.fieldLogPolicy(n,"id")]);const u=await this.executeLoggedSQL("select",a,c,this.queryLogIntent(s.query),()=>e.query(a,c));if(!u.rowCount)return{entity:t.entity,action:"Create",id:t.id,version:0,payload:{...t.values}};const l=u.rows[0];if(r.filter(g=>!Ht(l[g.column],g.value)).length)return{entity:t.entity,action:"Update",id:t.id,version:Number(l[n.columns.version?.columnName??"version"]),payload:{...this.decodeRowForSchema(n,l),...t.values}}}async executeGraphSave(e,t){const n=new Ot(e);await this.telemetryStartup;const r=async()=>{const o=this.graphSaveTail;let s;this.graphSaveTail=new Promise(l=>{s=l}),await o;let a=!1,c=!1,u=!1;try{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],this.userContext.insertResource("fixTime",new Date),this.userContext.beginFixEvidence(),a=!0,this.userContext.beginMutationPolicyGraph(),c=!0;const l=await this.driver.transaction(async h=>{this.graphMutationSession=h,this.activeGraph=n;try{const p=await t(n);return this.userContext.ensureMutationPolicyGraphComplete(),p}finally{this.graphMutationSession=void 0,this.activeGraph=void 0}});u=!0;let f,g=!1;for(const h of[...this.graphCommitActions,...this.graphAuditActions])try{await h()}catch(p){g||(f=p),g=!0}if(g)throw new qe(f);return l}catch(l){if(!u)for(const f of[...this.graphRollbackActions].reverse())try{f()}catch{}throw l}finally{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],c&&this.userContext.endMutationPolicyGraph(),this.userContext.removeResource("fixTime"),a&&this.userContext.finishFixEvidence(),s()}};return D(this.runtimeTelemetry,{family:"mutation",name:"graph.save",attributes:{"teaql.entity.type":"graph","teaql.mutation.kind":"graph"}},r)}afterGraphCommit(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphCommitActions.push(e)}afterGraphRollback(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphRollbackActions.push(e)}requireGraphOwnership(e){if(e.graphSession!==this.activeGraph||this.graphMutationSession!==void 0&&e.graphSession===void 0)throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability")}async withMutationSession(e,t){return this.requireGraphOwnership(e),e.graphSession?t(this.graphMutationSession):this.driver.transaction(t)}preflightMutation(e){const t=e instanceof x?e:new x(e);if(this.requireGraphOwnership(t),e=this.checkAndFixMutation(t),t.graphSession){const n=this.schema(e.entity);t.graphSession.captureLogBindings(this.mutationLogBindings(t,e,n))}return this.userContext.recordMutationPolicyPreflight(e),e}mutationLogBindings(e,t,n){const r=o=>{const s=this.toRuntimeMutationRecord(n,o),a=Object.keys(s);return{parameterizedSQL:"",sqlOrigin:"generated",parameters:a.map(c=>s[c]),parameterLogPolicies:a.map(c=>this.fieldLogPolicy(n,c))}};return R(r(t.payload||{}),r(e.loadedValues()))}checkAndFixMutation(e){const t=e instanceof x?e:new x(e);this.requireGraphOwnership(t),e=t.mutation,e={...e,payload:{...e?.payload??{}}},Object.defineProperty(e,"comment",{value:t.comment,enumerable:!0});const n=this.checkers[String(e.entity)];if(!n)return e;const r=[],o=this.userContext.getResource("fixTime")===void 0;o&&this.userContext.insertResource("fixTime",new Date).beginFixEvidence();try{if(n.checkAndFix(this.userContext,e,r),e.ledgerKey&&e.ledgerRoot)for(const[s,a]of Object.entries(e.payload||{}))e.ledgerRoot.set(e.ledgerKey,s,a);if(this.userContext.translateCheckResults(r),r.length)throw new ot(r);return e}finally{o&&this.userContext.removeResource("fixTime").finishFixEvidence()}}async executeMutation(e){await this.telemetryStartup;const t=e instanceof x?e:new x(e);this.requireGraphOwnership(t),e=t.mutation;const n=N(this.runtimeTelemetry,{family:"mutation",name:`${String(e?.entity||"unknown")}.${String(e?.action||"unknown").toLowerCase()}`,attributes:{"teaql.entity.type":String(e?.entity||"unknown"),"teaql.mutation.kind":String(e?.action||"unknown").toLowerCase()}}),r=async()=>{try{e=this.checkAndFixMutation(t);const o=this.userContext.enterMutationPolicy(e),s=this.schema(e.entity),a=this.toRuntimeMutationRecord(s,e.payload||{}),c=this.mutationLogBindings(t,e,s),u=this.driver.identifier(s.table),l=[],f=await D(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.mutation`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":String(e.action).toLowerCase()}},()=>this.withMutationSession(t,async y=>{if(e.action==="Create"){const d=e.id?String(e.id):await this.driver.nextId(y,e.entity);e.id&&await this.driver.ensureIdFloor(y,e.entity,d);const b=Number(e.version||0)+1,E={...a,id:d,version:b},S=Object.keys(s.columns).filter($=>E[$]!==void 0),w=S.map($=>this.driver.identifier(s.columns[$].columnName)).join(", "),v=S.map(($,A)=>this.driver.placeholder(A+1)).join(", "),I=S.map($=>this.encode(E[$],s.columns[$]));this.bindLogPolicies.set(I,S.map($=>this.fieldLogPolicy(s,$)));const T=`INSERT INTO ${u} (${w}) VALUES (${v})`,O=ge(t,e,this.driver.databaseKind,"insert",d,c);return await this.executeLoggedSQL("insert",T,I,O,()=>y.query(T,I),void 0,l),{success:!0,id:d,version:b,persistedRecord:await this.readPersistedRecord(y,s,d,O,T,I,l)}}if(e.action==="Update"){const d=Object.keys(s.columns).filter($=>$!=="id"&&$!=="version"&&a[$]!==void 0),b=d.map($=>this.encode(a[$],s.columns[$]));this.bindLogPolicies.set(b,d.map($=>this.fieldLogPolicy(s,$)));const E=d.map(($,A)=>`${this.driver.identifier(s.columns[$].columnName)} = `+this.driver.placeholder(A+1)),S=this.driver.identifier("version");E.push(`${S} = ${S} + 1`),this.bindValue(b,String(e.id),this.fieldLogPolicy(s,"id"));const w=[`${this.driver.identifier("id")} = ${this.driver.placeholder(b.length)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),w.push(`${S} = ${this.driver.placeholder(b.length)}`));const v=`UPDATE ${u} SET ${E.join(", ")} WHERE ${w.join(" AND ")}`,I=ge(t,e,this.driver.databaseKind,"update",String(e.id),c);if((await this.executeLoggedSQL("update",v,b,I,()=>y.query(v,b),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const O=await this.readPersistedRecord(y,s,String(e.id),I,v,b,l);return{success:!0,id:String(e.id),version:Number(O.version),persistedRecord:O}}if(e.action==="Delete"){const d=this.driver.identifier("version"),b=[String(e.id)];this.bindLogPolicies.set(b,[this.fieldLogPolicy(s,"id")]);const E=[`${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),E.push(`${this.driver.identifier("version")} = `+this.driver.placeholder(b.length)));const S=`UPDATE ${u} SET ${d} = -(${d} + 1) WHERE ${E.join(" AND ")}`,w=ge(t,e,this.driver.databaseKind,"delete",String(e.id),c);if((await this.executeLoggedSQL("delete",S,b,w,()=>y.query(S,b),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const I=await this.readPersistedRecord(y,s,String(e.id),w,S,b,l);return{success:!0,id:String(e.id),version:Number(I.version),deleted:!0,persistedRecord:I}}throw new Error(`Unsupported mutation action: ${e.action}`)})),g=t.auditProjection({entity:String(e.entity),id:f.id},e.payload,c),h=Object.freeze({entity:e.entity,action:e.action,id:String(f.id),...g,recordedAt:new Date().toISOString(),actor:this.userContext.getResource("bootstrapActor"),category:this.userContext.getResource("bootstrapCategory"),changedFields:Object.freeze(Object.keys(e.payload||{}).sort()),version:f.version,mutationGovernance:o}),p=async()=>{this.auditEvents.push(h),this.auditSink&&await D(this.runtimeTelemetry,{family:"audit",name:`${e.entity}.audit`,attributes:{"teaql.entity.type":String(e.entity),"teaql.mutation.kind":String(e.action).toLowerCase(),"teaql.audit.changed_field_count":Object.keys(e.payload||{}).length}},async()=>this.auditSink(h))};if(t.graphSession)this.graphAuditActions.push(p);else try{await p()}catch(y){throw new qe(y)}n.success();const m=Object.freeze({...l[0],statements:Object.freeze([...l])});return ke(m,R(c,t.graphSession?.logBindings),[f.id]),{...f,metadata:m}}catch(o){throw n.failure(o),o}};return n.run?n.run(r):r()}async readPersistedRecord(e,t,n,r,o,s,a){const u=`SELECT ${Object.entries(t.columns).map(([S,w])=>`${this.driver.identifier(w.columnName)} AS ${this.driver.identifier(S)}`).join(", ")} FROM ${this.driver.identifier(t.table)} WHERE ${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`,l=[n];this.bindLogPolicies.set(l,[this.fieldLogPolicy(t,"id")]);const f=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.readback`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}}),g=Date.now();let h;const p={parameterizedSQL:o,parameters:s,parameterLogPolicies:this.bindLogPolicies.get(s),sqlOrigin:"generated"},m=r.tracePath?.find(S=>S.kind==="operation")?.name??"unknown",y=ye([...ze(m,r.auditReason,"verify persisted mutation result"),...(r.tracePath??[]).filter(S=>S.kind==="relation")],this.driver.databaseKind,"select"),d={...r,tracePath:ee(y.tracePath),comment:r.auditReason,purpose:"verify persisted mutation result"},b=S=>a.push(this.recordSQL("select",u,l,g,h?.rowCount,void 0,d,S,p,f.correlation?.()));let E;try{if(h=await(f.run?f.run(()=>e.query(u,l)):e.query(u,l)),f.success({attributes:{"teaql.result.cardinality":h.rowCount}}),h.rowCount!==1)throw new Error(`Persisted ${t.table}(${n}) could not be read back`);E=this.decodeRowForSchema(t,h.rows[0])}catch(S){h||f.failure(S);const w=h?"success":S instanceof Error&&(S.name==="AbortError"||S.name==="TimeoutError")?"cancelled":"failure";try{b(w)}finally{throw S}}return b("success"),E}decodeRowForSchema(e,t){const n={...t};for(const[r,o]of Object.entries(e.columns)){const s=n[r];s!=null&&(o.decode==="number"&&(n[r]=Number(s)),o.decode==="string"&&(n[r]=String(s)),o.decode==="date"&&s instanceof Date&&(n[r]=s.toISOString()),o.logicalType==="boolean"&&(n[r]=!!s))}return n}compileExpression(e,t,n){if(Array.isArray(e?.$and))return`(${e.$and.map(s=>this.compileExpression(s,t,n)).join(" AND ")})`;const r=Object.entries(e||{}).map(([o,s])=>{const a=t.columns[o];if(!a)throw new Error(`Unknown field ${o} for SQL query`);const c=this.driver.identifier(a.columnName),u=this.fieldLogPolicy(t,o);if(s?.$eq!==void 0){const l=s.$eq?.id??s.$eq;return l===null?`${c} IS NULL`:(this.bindValue(n,this.encode(l,a),u),`${c} = ${this.driver.placeholder(n.length)}`)}if(s?.$ne!==void 0){const l=s.$ne?.id??s.$ne;return l===null?`${c} IS NOT NULL`:(this.bindValue(n,this.encode(l,a),u),`${c} <> ${this.driver.placeholder(n.length)}`)}if(s?.$soundLike!==void 0)return this.bindValue(n,String(s.$soundLike),u),`SOUNDEX(${c}) = SOUNDEX(${this.driver.placeholder(n.length)})`;if(s?.$contains!==void 0)return this.bindValue(n,String(s.$contains),u),this.driver.contains(c,this.driver.placeholder(n.length));if(s?.$notContains!==void 0)return this.bindValue(n,String(s.$notContains),u),`NOT (${this.driver.contains(c,this.driver.placeholder(n.length))})`;for(const[l,f,g,h]of[["$startsWith","","%",!1],["$notStartsWith","","%",!0],["$endsWith","%","",!1],["$notEndsWith","%","",!0]])if(s?.[l]!==void 0){const p=String(s[l]);this.bindValue(n,`${f}${p}${g}`,u,p);const m=`${c} LIKE ${this.driver.placeholder(n.length)}`;return h?`NOT (${m})`:m}if(Array.isArray(s?.$in)){if(!s.$in.length)return"FALSE";const l=s.$in.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),u),this.driver.placeholder(n.length)));return`${c} IN (${l.join(", ")})`}if(Array.isArray(s?.$notIn)){if(!s.$notIn.length)return"TRUE";const l=s.$notIn.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),u),this.driver.placeholder(n.length)));return`${c} NOT IN (${l.join(", ")})`}for(const[l,f]of[["$inSubquery",!1],["$notInSubquery",!0]]){const g=s?.[l];if(g!==void 0){const h=g.query,p=this.schema(h?.entity),m=String(g.field),y=p.columns[m];if(!y)throw new Error(`Unknown subquery projection ${m} for ${h?.entity}`);const d=this.filters(h).map(S=>this.compileExpression(S,p,n));p.columns.version&&d.push(`${this.driver.identifier(p.columns.version.columnName)} > 0`),f&&d.push(`${this.driver.identifier(y.columnName)} IS NOT NULL`);const b=d.length?` WHERE ${d.join(" AND ")}`:"",E=`SELECT ${this.driver.identifier(y.columnName)} FROM ${this.driver.identifier(p.table)}${b}`;return`${c} ${f?"NOT IN":"IN"} (${E})`}}if(Array.isArray(s?.$between)&&s.$between.length===2){this.bindValue(n,this.encode(s.$between[0],a),u);const l=this.driver.placeholder(n.length);this.bindValue(n,this.encode(s.$between[1],a),u);const f=this.driver.placeholder(n.length);return`${c} BETWEEN ${l} AND ${f}`}if(s?.$isNull===!0)return`${c} IS NULL`;if(s?.$isNull===!1)return`${c} IS NOT NULL`;if(s?.$gte!==void 0)return this.bindValue(n,this.encode(s.$gte,a),u),`${c} >= ${this.driver.placeholder(n.length)}`;if(s?.$lte!==void 0)return this.bindValue(n,this.encode(s.$lte,a),u),`${c} <= ${this.driver.placeholder(n.length)}`;if(s?.$gt!==void 0)return this.bindValue(n,this.encode(s.$gt,a),u),`${c} > ${this.driver.placeholder(n.length)}`;if(s?.$lt!==void 0)return this.bindValue(n,this.encode(s.$lt,a),u),`${c} < ${this.driver.placeholder(n.length)}`;throw new Error(`Unsupported query predicate for ${o}: ${JSON.stringify(s)}`)});return r.length?`(${r.join(" AND ")})`:"TRUE"}filters(e){return Array.isArray(e._filters)&&e._filters.length?e._filters:e.filterCondition?[e.filterCondition]:[]}groupBy(e){return e._groupBy||e.groupByItems||[]}aggregates(e){return Array.isArray(e._aggregates)?e._aggregates:(e.aggregateItems||[]).map(t=>({func:t.function,field:t.field,retName:t.alias}))}orders(e){return Array.isArray(e._orderBy)?e._orderBy.map(t=>({field:t.f,direction:t.d})):(e.orderItems||[]).map(t=>({field:t.field,direction:t.direction}))}async compileQuery(e,t=!0,n=[]){new se(e?.commentText??e?._comment,e?.purposeText??e?._purpose);const r=this.schema(e.entity),o=[],s=this.groupBy(e),a=s.map(w=>{if(!r.columns[w])throw new Error(`Unknown group field: ${w}`);return this.driver.identifier(r.columns[w].columnName)}),c=s.map(w=>`${this.driver.identifier(r.columns[w].columnName)} AS `+this.driver.identifier(w)),u=[],l=Array.isArray(e.selectItems)&&e.selectItems.length?[...new Set(["id","version",...e.selectItems])]:Object.keys(r.columns);if(!s.length&&!this.aggregates(e).length){for(const v of n)l.includes(v)||l.push(v);const w=[...(e.relations??[]).map(v=>v.name),...(e.relationAggregates??[]).map(v=>v.relationName)];for(const v of w){const I=r.relations?.[v];if(!I)throw new Error(`Missing relation ${e.entity}.${v}`);l.includes(I.localKey)||l.push(I.localKey)}}for(const w of l)if(!r.columns[w])throw new Error(`Unknown selected field: ${w}`);let f=l.map(w=>{const v=r.columns[w];return`${this.driver.identifier(v.columnName)} AS ${this.driver.identifier(w)}`}).join(", ");const g=this.aggregates(e);if(g.length){const w=g.map(v=>{if(!r.columns[v.field])throw new Error(`Unknown aggregate field: ${v.field}`);return u.push(v.retName),`${this.driver.aggregateFunction(v.func)}(${this.driver.identifier(r.columns[v.field].columnName)}) AS `+this.driver.identifier(v.retName)});f=[...c,...w].join(", ")}const h=e.__teaqlPartitionBy,p=this.orders(e),m=p.map(w=>{if(!r.columns[w.field])throw new Error(`Unknown order field: ${w.field}`);const v=String(w.direction).toLowerCase()==="desc"?"DESC":"ASC";return`${this.driver.identifier(r.columns[w.field].columnName)} ${v}`});if(h){const w=r.columns[h];if(!w)throw new Error(`Unknown partition field: ${h}`);const v=m.length?` ORDER BY ${m.join(", ")}`:"";f+=`, ROW_NUMBER() OVER (PARTITION BY ${this.driver.identifier(w.columnName)}${v}) AS `+this.driver.identifier("__teaql_partition_rank")}let y=`SELECT ${f} FROM ${this.driver.identifier(r.table)}`;const b=this.filters(e).map(w=>this.compileExpression(w,r,o));r.columns.version&&b.push(`${this.driver.identifier(r.columns.version.columnName)} > 0`),b.length&&(y+=` WHERE ${b.join(" AND ")}`),a.length&&(y+=` GROUP BY ${a.join(", ")}`);const E=e._limit!==void 0?Number(e._limit):Number(e.limitValue||0),S=e._offset!==void 0?Number(e._offset):Number(e.offsetValue||0);if(h){const w=this.driver.identifier("__teaql_partition_rank"),v=[];this.bindValue(o,S,"plain"),v.push(`${w} > ${this.driver.placeholder(o.length)}`),E>0&&(this.bindValue(o,S+E,"plain"),v.push(`${w} <= ${this.driver.placeholder(o.length)}`)),y=`SELECT * FROM (${y}) AS ${this.driver.identifier("__teaql_partitioned")} WHERE ${v.join(" AND ")} ORDER BY ${w}`}else p.length&&(y+=` ORDER BY ${m.join(", ")}`);return!h&&E>0&&(this.bindValue(o,E,"plain"),y+=` LIMIT ${this.driver.placeholder(o.length)}`),!h&&S>0&&(this.bindValue(o,S,"plain"),y+=` OFFSET ${this.driver.placeholder(o.length)}`),t&&this.sqlTrace.push(y),{sql:y,values:o,aggregateNames:u}}async executeQuery(e){const t=e instanceof L?e:new L(e);return!(e instanceof L)&&e?.[this.internalQueryToken]!==!0&&typeof e?.prepareForList=="function"&&e.prepareForList(),this.executeQueryWithIntent(t.query,this.derivedQueryBindings.get(e),this.derivedRelationAssembly.get(e))}async executeDerivedQuery(e,t,n,r){const o=new L(e,n).query;t&&this.derivedQueryBindings.set(o,t),r&&this.derivedRelationAssembly.set(o,r);try{return await this.executeQuery(o)}finally{this.derivedQueryBindings.delete(o),this.derivedRelationAssembly.delete(o)}}descendantBindings(e,t,n,r){if(!(!e.relations?.length&&!e.relationAggregates?.length))return R(this.queryLogBindings(t,n),r)}async queryTreeBindings(e,t,n,r){let o=R(this.queryLogBindings(t,n),r);const s=new L(e).intent,a=[e],c=new Set;for(;a.length;){const u=a.pop();if(!u||c.has(u))continue;if(c.add(u),u!==e){const f=await this.compileQuery(new L(u,s).query,!1);o=R(this.queryLogBindings(f.sql,f.values),o)}const l=$t(u);l&&a.push(l);for(const f of[...u.relations??[],...u.relationAggregates??[]])f.query&&a.push(f.query);for(const f of u.facets??[]){if(!f.query)continue;const g=f.query.clone();g.aggregateItems=[],g.groupByItems=[],a.push(g)}}return o}async executeQueryWithIntent(e,t,n){await this.telemetryStartup;const r=N(this.runtimeTelemetry,{family:"query",name:`${String(e?.entity||"unknown")}.list`,attributes:{"teaql.entity.type":String(e?.entity||"unknown")}}),o=async()=>{try{const s=e?.[this.internalQueryToken]===!0;if(!s){if(typeof e?.prepareForList!="function")throw new Error("TeaQL list execution requires the formal runtime SelectQuery");e.prepareForList()}const a=s?{query:e,execution:void 0}:await this.prepareIdSetPage(e,t),c=s?a:await this.prepareContinuousPage(a.query);e=new L(e).withQuery(c.query).query;const{sql:u,values:l,aggregateNames:f}=await this.compileQuery(e,!0,n?[n.field]:[]);t=await this.queryTreeBindings(e,u,l,t);const h=(await this.executeLoggedSQL("select",u,l,this.queryLogIntent(e),()=>this.driver.query(u,l),t)).rows.map(m=>this.decodeRow(e.entity,m,f));if(a.execution?.pageIds){const m=new Map(a.execution.pageIds.map((y,d)=>[String(y),d]));h.sort((y,d)=>(m.get(String(y.id))??Number.MAX_SAFE_INTEGER)-(m.get(String(d.id))??Number.MAX_SAFE_INTEGER))}const p=this.descendantBindings(e,u,l,t);if(n)for(const m of h)n.keys.set(m,m[n.field]);if(await this.enhanceQueryRows(h,e,p),n&&Array.isArray(e.selectItems)&&e.selectItems.length&&!["id","version",...e.selectItems,...this.groupBy(e)].includes(n.field)){const m=this.schema(e.entity);if(![...(e.relations??[]).map(d=>d.name),...(e.relationAggregates??[]).map(d=>d.relationName)].some(d=>m.relations?.[d]?.localKey===n.field))for(const d of h)delete d[n.field]}return s||await this.registerContinuousPage(e,c.execution,h),r.success({attributes:{"teaql.result.cardinality":h.length}}),h}catch(s){throw r.failure(s),s}};return r.run?r.run(o):o()}async prepareIdSetPage(e,t){const n=e.localIdSetPaginationOptions?.(),r=e.localIdSetPaginationRuntime?.();if(!n||!r)return r?.observe("ID_SET_DISABLED"),{query:e};const o=this.queryLimit(e);if(!o||e.localContinuousPageOptions?.()||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return r.observe("ID_SET_FALLBACK_UNSUPPORTED_SHAPE"),{query:e};if((e.orderItems||[]).some(m=>m.expr!=null))return r.observe("ID_SET_FALLBACK_NON_DETERMINISTIC_ORDER"),{query:e};this.orders(e).some(m=>m.field==="id")||(e=e.clone().order(P.asc("id")));const s=e.clone();s.offsetValue=0,s.limitValue=0,s.selectItems=[],s.relations=[],s.commentText=void 0,s.purposeText=void 0,s.clearIdSetPaginationRuntime(),s.clearContinuousPageRuntime();const a=`${n.namespace}|${r.scope}|${JSON.stringify(s)}`;let c=2166136261;for(let m=0;m>>0).toString(16)}`;let l,f=!1;try{l=r.get(u)}catch{return r.observe("ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l)f=!0,r.observe("ID_SET_HIT",l.ids.length);else{let m;try{m=await r.build(u,async()=>{const y=r.get(u);if(y)return y;const d=e.clone();d.selectItems=["id"],d.relations=[],d.relationAggregates=[],d.facets=[],d.offsetValue=0,d.limitValue=n.maxIds+1,d.clearIdSetPaginationRuntime(),d.clearContinuousPageRuntime(),d[this.internalQueryToken]=!0;const b=new L(e).deriveHelper(d,`collect ${e.entity} IDs for pagination`),E=await this.compileQuery(e,!1),S=await this.queryTreeBindings(e,E.sql,E.values,t),w=await this.executeDerivedQuery(b.query,S,b.intent);if(w.length>n.maxIds)return;let v;try{v=BigUint64Array.from(w.map(T=>BigInt(T.id)))}catch{throw new Error("ID_SET_UNSUPPORTED_ID")}const I={ids:v,expiresAt:Date.now()+n.ttlSeconds*1e3};return r.put(u,I),I})}catch(y){return r.observe(y instanceof Error&&y.message==="ID_SET_UNSUPPORTED_ID"?"ID_SET_FALLBACK_UNSUPPORTED_SHAPE":"ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l=m.value,!l)return r.observe("ID_SET_FALLBACK_LIMIT_EXCEEDED",n.maxIds+1),{query:e};f=!m.built,r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length)}const g=Number(e.offsetValue||e._offset||0),h=Array.from(l.ids.slice(g,g+o)),p=e.clone();return p.offsetValue=0,p.limitValue=Math.max(h.length,1),p.filterCondition=p.filterCondition?{$and:[p.filterCondition,{id:{$in:h}}]}:{id:{$in:h}},p.clearIdSetPaginationRuntime(),r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length),{query:p,execution:{pageIds:h,totalCount:l.ids.length}}}async executeFacetMembership(e,t,n=[]){const r=await this.executeFacetAggregates(e,t,[{function:"Count",field:"id",alias:"__teaql_facet_count"}]);return new Map([...r].map(([o,s])=>[o,Number(s.__teaql_facet_count??0)]))}async executeFacetAggregates(e,t,n){const r=new L(e);e=r.query;const o=r.withQuery(e.clone()).query;Q(e,o),o.facets=[],o.relations=[],o.relationAggregates=[],o.orderItems=[],o.offsetValue=0,o.limitValue=0,o.selectItems=[],o.groupByItems=[t],o.aggregateItems=n.map(a=>({...a})),o[this.internalQueryToken]=!0;const s=await this.executeQuery(o);return new Map(s.flatMap(a=>{const c=a[t];if(c==null)return[];const u={};for(const l of n)u[l.alias]=a[l.alias];return[[String(c),u]]}))}async executeCount(e,t,n){const r=e instanceof L?e:new L(e);if(e=r.query,typeof e?.forExactCount!="function")throw new Error("TeaQL exact count requires the formal runtime SelectQuery");const o=t??"__teaql_total",s=r.deriveOperation(e.forExactCount(o),n??{kind:"named-count",...t!==void 0?{alias:t}:{}}),c=(await this.executeQuery(s.query))[0]?.[o];if(typeof c!="number"||!Number.isFinite(c))throw new Error(`TeaQL provider did not return exact count alias ${o}`);return c}async prepareContinuousPage(e){const t=e.localContinuousPageOptions?.(),n=e.localContinuousPageRuntime?.();if(!t||!n)return n?.observe("DISABLED"),{query:e};const r=this.orders(e),o=this.queryLimit(e);if(!o||r.length!==1||r[0].field!=="id"||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return n.observe("OFFSET_FALLBACK:UNSUPPORTED_QUERY_SHAPE"),{query:e};const s=Object.assign(Object.create(Object.getPrototypeOf(e)),e);s.orderItems=[...e.orderItems||[]],s.relations=[...e.relations||[]],Object.defineProperty(s,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:t}),Object.defineProperty(s,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:n});const a=Number(e.offsetValue||e._offset||0),c={...JSON.parse(JSON.stringify(s)),offsetValue:0,_offset:0,commentText:void 0,purposeText:void 0},u=`${t.namespace}|${n.owner}|${JSON.stringify(c)}`;let l=2166136261;for(let m=0;m>>0).toString(16)}`,g={queryKey:f,offset:a,limit:o,direction:String(r[0].direction).toLowerCase(),ttlSeconds:t.ttlSeconds,runtime:n,optimized:!1};if(a===0)return n.observe("OFFSET_FALLBACK:FIRST_PAGE"),{query:s,execution:g};let h;try{h=await D(this.runtimeTelemetry,{family:"cache",name:"continuous_page.get",attributes:{"teaql.cache.operation":"get"}},()=>n.get(f,a))}catch{return n.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE"),{query:s,execution:g}}if(!h)return n.observe("OFFSET_FALLBACK:CACHE_MISS"),{query:s,execution:g};const p={id:{[g.direction==="desc"?"$lt":"$gt"]:h.boundary}};return s.filterCondition=s.filterCondition?{$and:[s.filterCondition,p]}:p,s.offsetValue=0,s._offset!==void 0&&(s._offset=0),g.optimized=!0,g.cursorId=h.cursorId,n.observe("CURSOR_SEEK",h.cursorId),{query:s,execution:g}}async registerContinuousPage(e,t,n){if(!(!t||n.length!==t.limit||!n.length||n[n.length-1].id===void 0)){try{await D(this.runtimeTelemetry,{family:"cache",name:"continuous_page.put",attributes:{"teaql.cache.operation":"put"}},()=>t.runtime.put(t.queryKey,t.offset+n.length,{cursorId:`cpg_${Date.now().toString(16)}_${Math.random().toString(16).slice(2)}`,boundary:n[n.length-1].id,expiresAt:Date.now()+t.ttlSeconds*1e3}))}catch{t.runtime.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE");return}t.optimized&&t.runtime.observe("CURSOR_SEEK",t.cursorId)}}executeForStream(e,t=1e3){try{const n=e instanceof L?new L(e.query,e.intent):new L(e);return this.executeCapturedStream(n.query,t)}catch(n){return(async function*(){throw n})()}}async*executeCapturedStream(e,t){if(await this.telemetryStartup,!Number.isInteger(t)||t<=0)throw new Error("stream chunk size must be a positive integer");if(Array.isArray(e.facets)&&e.facets.length>0)throw new Error("QRY-F01_STREAM_UNSUPPORTED: execute facets with executeForList");const{sql:n,values:r,aggregateNames:o}=await this.compileQuery(e),s=await this.queryTreeBindings(e,n,r),a=N(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.stream`,attributes:{"teaql.entity.type":String(e.entity)}});let c;const u=async()=>{c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.stream`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}})};await(a.run?a.run(u):u());const l=c.correlation?.(),f=this.driver.stream(n,r)[Symbol.asyncIterator](),g=Date.now();let h="cancelled",p=0,m=[];const y=this.descendantBindings(e,n,r,s);try{for(;;){const d=await(c.run?c.run(()=>f.next()):f.next());if(d.done)break;m.push(this.decodeRow(e.entity,d.value,o)),m.length===t&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m,m=[])}m.length&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m),h="success"}catch(d){throw h="failure",c.failure(d),a.failure(d),d}finally{try{await f.return?.()}catch(d){if(h!=="failure")throw h="failure",c.failure(d),a.failure(d),d}finally{if(h==="failure")try{this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,l)}catch{}else this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,l),c.success({attributes:{"teaql.result.cardinality":p}}),a.success({attributes:{"teaql.result.cardinality":p}})}}}async enhanceQueryRows(e,t,n){if(!e.length)return;const r=[...(t.relations??[]).map(a=>a.name),...(t.relationAggregates??[]).map(a=>a.relationName)];if(!r.length)return;const o=this.schema(t.entity),s=new Map;for(const a of r){const c=o.relations?.[a];if(!c)throw new Error(`Missing relation ${t.entity}.${a}`);s.has(c.localKey)||s.set(c.localKey,e.map(u=>u[c.localKey]))}await this.enhanceRelationAggregates(e,t,s,n),await this.enhanceRelations(e,t,s,n)}async enhanceRelations(e,t,n,r){if(!e.length||!Array.isArray(t.relations)||!t.relations.length)return;const o=this.schema(t.entity),s=new L(t).intent;for(const a of t.relations){const c=o.relations?.[a.name];if(!c)throw new Error(`Missing relation ${t.entity}.${a.name}`);const u=n.get(c.localKey),l=u.filter(S=>S!=null),f=a.query?this.queryLimit(a.query):void 0,g=a.query?.localTopNProbeParentThreshold?.(),h=c.many&&f!==void 0,p=Array.isArray(a.query?.selectItems)?a.query.selectItems:[],m=p.length>0&&!p.includes(c.foreignKey),y=this.driver.topNRelationPlanPolicy==="alwaysProbe",d=h&&(g===void 0?y:g>0&&l.length<=g),b=d?"bounded_probes":"window",E=N(this.runtimeTelemetry,{family:"relation_load",name:`${t.entity}.${String(a.name)}`,attributes:{"teaql.entity.type":String(t.entity),"teaql.relation.name":String(a.name),"teaql.relation.parent_count":l.length,"teaql.relation.per_parent_limit":f??0,"teaql.relation.configured_probe_threshold":g??"provider-default","teaql.relation.selected_plan":b,"teaql.relation.probe_count":d?l.length:0}});try{if(!l.length&&!(c.many&&a.query?.facets?.length)){for(const T of e)T[a.name]=c.many?[]:null;E.success({attributes:{"teaql.result.cardinality":0}});continue}const S={...a.query||{},entity:c.targetEntity,selectItems:m?[...p,c.foreignKey]:p,_filters:[...this.filters(a.query||{})],relations:[...a.query?.relations||[]],orderItems:[...a.query?.orderItems||[]],__teaqlPartitionBy:h&&!d?c.foreignKey:void 0};if(h){const T=this.groupBy(S),O=T.length||this.aggregates(S).length?T:["id"];for(const $ of O)S.orderItems.some(A=>A.field===$)||S.orderItems.push(P.asc($))}typeof S.clearContinuousPageRuntime=="function"&&S.clearContinuousPageRuntime(),S[this.internalQueryToken]=!0;const w=[],v={field:c.foreignKey,keys:new WeakMap};if(d)for(const T of l){const O={...S,_filters:[...S._filters,{[c.foreignKey]:{$eq:T}}],__teaqlPartitionBy:void 0};w.push(...await this.executeDerivedQuery(new L(t).derive(O,a.name,a.operation).query,r,s,v))}else S._filters.push({[c.foreignKey]:{$in:l}}),w.push(...await this.executeDerivedQuery(new L(t).derive(S,a.name,a.operation).query,r,s,v));for(const T of w)delete T.__teaql_partition_rank;const I=new Map;for(const T of w){if(!v.keys.has(T))throw new Error("Relation assembly lost its captured row identity");const O=v.keys.get(T),$=I.get(O)||[];$.push(T),I.set(O,$)}if(m)for(const T of w)delete T[c.foreignKey];for(const[T,O]of e.entries()){const $=I.get(u[T])||[];if(c.many&&a.query?.facets?.length){const A=a.query.clone();A.entity=c.targetEntity;const le=u[T],Te={[c.foreignKey]:le==null?{$in:[]}:{$eq:le}};A.filterCondition=A.filterCondition?{$and:[A.filterCondition,Te]}:Te,Q(t,A);const it=new L(t).derive(A,a.name,a.operation).query;O[a.name]=new Y($,{facets:await et(this,nt=>nt,it,A.facets)})}else{const A=u[T];O[a.name]=c.many?$:$[0]??(A==null?null:{[c.foreignKey]:A})}}E.success({attributes:{"teaql.result.cardinality":w.length}})}catch(S){throw E.failure(S),S}}}async enhanceRelationAggregates(e,t,n,r){const o=t.relationAggregates;if(!e.length||!Array.isArray(o)||!o.length)return;const s=this.schema(t.entity),a=new L(t).intent;for(const c of o){const u=s.relations?.[c.relationName];if(!u)throw new Error(`Missing relation ${t.entity}.${c.relationName}`);const l=n.get(u.localKey),f=l.filter(y=>y!=null);if(!f.length){for(const y of e)y[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{};continue}const g=c.query.clone();g.entity=u.targetEntity,g.selectItems=[],g.properties=[],g.orderItems=[],g.limitValue=0,g.offsetValue=0,g.relations=[],g.relationAggregates=[],g.aggregateItems.length||g.aggregate("Count","id",c.alias),g.groupByItems.includes(u.foreignKey)||g.groupBy(u.foreignKey);const h={[u.foreignKey]:{$in:f}};g.filterCondition=g.filterCondition?{$and:[g.filterCondition,h]}:h,g[this.internalQueryToken]=!0;const p=await this.executeDerivedQuery(new L(t).deriveAggregate(g,c.relationName,c.operation??{kind:"relation-count",relation:c.relationName,alias:c.alias}).query,r,a),m=new Map;for(const y of p)m.set(y[u.foreignKey],y);for(const[y,d]of e.entries()){const b=m.get(l[y]);b?c.singleResult?d[c.alias]=b[g.aggregateItems[0].alias]??null:d[c.alias]=Object.fromEntries(Object.entries(b).filter(([E])=>E!==u.foreignKey)):d[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{}}}}emptyAggregateValue(e){const t=e.aggregateItems[0];return!t||String(t.function).toLowerCase()==="count"?0:null}queryLimit(e){if(e._limit!==void 0)return Number(e._limit);if(e.limitValue!==void 0&&Number(e.limitValue)>0)return Number(e.limitValue)}async close(){try{await this.driver.close()}finally{await this.telemetryStartup,await this.standardTelemetryHandle?.release(),this.standardTelemetryHandle=void 0}}}function Jt(i){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))throw new Error(`Unsafe SQL identifier: ${i}`);return i}function Zt(i){const t={count:"COUNT",sum:"SUM",avg:"AVG",min:"MIN",max:"MAX"}[String(i).toLowerCase()];if(!t)throw new Error(`Unsupported aggregate: ${i}`);return t}class ei{constructor(e){this.worker=e,this.nextRequestId=1,this.pending=new Map,this.closed=!1,this.onMessage=t=>{const n=t.data;if(!n||n.type!=="teaql-browser-sqlite-response")return;const r=this.pending.get(n.requestId);if(r)if(this.pending.delete(n.requestId),n.error){const o=new Error(n.error.message);o.name=n.error.name,n.error.code&&(o.code=n.error.code),r.reject(o)}else r.resolve(n.result)},this.onError=t=>{const n=new Error(t.message||"Browser SQLite worker failed");n.name="BrowserSQLiteWorkerError";for(const r of this.pending.values())r.reject(n);this.pending.clear()},e.addEventListener("message",this.onMessage),e.addEventListener("error",this.onError)}request(e,t){if(this.closed)return Promise.reject(new Error("Browser SQLite worker is closed"));const n=this.nextRequestId++;return new Promise((r,o)=>{this.pending.set(n,{resolve:s=>r(s),reject:o}),this.worker.postMessage({type:"teaql-browser-sqlite-request",requestId:n,operation:e,payload:t})})}async close(e){if(!this.closed)try{await this.request("close")}finally{this.closed=!0,this.worker.removeEventListener("message",this.onMessage),this.worker.removeEventListener("error",this.onError),e&&this.worker.terminate?.();const t=new Error("Browser SQLite worker is closed");for(const n of this.pending.values())n.reject(t);this.pending.clear()}}}class ti{constructor(e){this.transport=e}query(e,t=[]){return this.transport.request("query",{sql:e,values:t})}}class $e{constructor(e,t){this.transport=e,this.options=t,this.databaseKind="sqlite",this.accessTail=Promise.resolve()}static async open(e,t={}){const n={storage:t.storage??"memory",databaseName:ni(t.databaseName??"teaql-browser.sqlite3"),terminateWorkerOnClose:t.terminateWorkerOnClose??!0},r=new ei(e);return await r.request("open",n),new $e(r,n)}identifier(e){return`"${Jt(e)}"`}placeholder(e){return"?"}contains(e,t){return`CAST(${e} AS TEXT) LIKE '%' || ${t} || '%'`}aggregateFunction(e){return Zt(e)}encode(e,t){return e==null?e:t?.logicalType==="json"&&typeof e!="string"?JSON.stringify(e):t?.logicalType==="boolean"?e?1:0:e instanceof Date?e.toISOString():e}async exclusive(e){const t=this.accessTail;let n;this.accessTail=new Promise(r=>{n=r}),await t;try{return await e()}finally{n()}}query(e,t=[]){return this.exclusive(()=>this.transport.request("query",{sql:e,values:t}))}async*stream(e,t=[]){const n=await this.query(e,t);for(const r of n.rows)yield r}transaction(e){return this.exclusive(async()=>{const t=new ti(this.transport);await t.query("BEGIN IMMEDIATE");try{const n=await e(t);return await t.query("COMMIT"),n}catch(n){try{await t.query("ROLLBACK")}catch{}throw n}})}async ensureSchema(e){for(const t of Object.values(e)){const n=this.identifier(t.table);await this.query(`CREATE TABLE IF NOT EXISTS ${n} ("id" INTEGER PRIMARY KEY, "version" INTEGER NOT NULL)`);const r=await this.query(`PRAGMA table_info(${n})`),o=new Set(r.rows.map(s=>String(s.name)));for(const[s,a]of Object.entries(t.columns))s==="id"||s==="version"||o.has(a.columnName)||await this.query(`ALTER TABLE ${n} ADD COLUMN ${this.identifier(a.columnName)} ${ii(a.logicalType)}${a.nullable===!1?" NOT NULL":""}`)}for(const t of Wt(e))await this.query(`CREATE INDEX IF NOT EXISTS ${this.identifier(t.name)} ON ${this.identifier(t.table)} (${this.identifier(t.foreignColumn)}, ${this.identifier(t.idColumn)} DESC)`);await this.query("CREATE TABLE IF NOT EXISTS teaql_id_space (type_name TEXT PRIMARY KEY, current_level INTEGER NOT NULL)")}async nextId(e,t){for(let n=1;n<=100;n+=1){const r=await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t]);if(!r.rowCount){try{if((await e.query("INSERT INTO teaql_id_space(type_name, current_level) VALUES (?, 1)",[t])).rowCount===1)return"1"}catch(c){if(!(await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t])).rowCount)throw c}continue}const o=Number(r.rows[0].id),s=o+1,a=await e.query("UPDATE teaql_id_space SET current_level = ? WHERE type_name = ? AND current_level = ?",[s,t,o]);if(a.rowCount===1)return String(s);if(a.rowCount!==0)throw new Error(`ID space update for ${t} changed ${a.rowCount} rows`)}throw new Error(`Unable to allocate ID for ${t} after 100 optimistic-lock attempts`)}ensureIdFloor(e,t,n){return Gt(e,r=>this.placeholder(r),t,n)}reset(){return this.exclusive(()=>this.transport.request("reset",this.options))}close(){return this.exclusive(()=>this.transport.close(this.options.terminateWorkerOnClose))}}class tt extends Xt{constructor(e,t){super(e,t),this.browserDriver=e}static async open(e,t,n={}){return new tt(await $e.open(e,n),t)}get storage(){return this.browserDriver.options.storage}async reset(e){await this.browserDriver.reset(),this.invalidateSchemaState(),await e.ensureSchema()}}function ii(i){return{boolean:"INTEGER",double:"REAL",decimal:"NUMERIC",date:"TEXT",datetime:"TEXT",json:"TEXT",integer:"INTEGER",text:"TEXT"}[i]}function ni(i){const e=i.trim();if(!e||e.includes("/")||e.includes("\\")||e==="."||e==="..")throw new TypeError("Browser SQLite databaseName must be a simple file name");return e}function hi(i,e,t,n){const r=o=>{if(o.includes("."))throw new Error("Dynamic search requires a trusted relation binding");const s=t[i.entity]?.queryFields;if(!s||!Object.prototype.hasOwnProperty.call(s,o))throw new Error("Missing generated scalar search binding");return s[o]};return ri(i,e,t,{filter:(o,s)=>{const[a,c]=Object.entries(s)[0];if(c===null&&a!=="$eq"&&a!=="$ne")throw new Error("Null supports only equality predicates");return{[r(o)]:s}},order:(o,s)=>s==="asc"?P.asc(r(o)):P.desc(r(o))},n)}function ri(i,e,t,n,r=o=>console.warn({...o,fieldPath:""})){const o=ai(e,i.entity,t,()=>{}),s=Object.entries(o.search.filter??{}).map(([f,g])=>n.filter(f,g)),a=(o.search.orderBy??[]).map(f=>n.order(f.field,f.direction));if(s.some(f=>!U(f)))throw new Error("Invalid trusted search filter binding");if(a.some(f=>!(f instanceof P)))throw new Error("Invalid trusted search order binding");const c=i.clone(),u=i._filters??[],l=[...u,...i.filterCondition?[i.filterCondition]:[]];return(s.length||u.length)&&c.filter({$and:[...l,...s]}),c.orderItems.push(...a),o.warnings.forEach(f=>r({...f})),{query:c,warnings:o.warnings}}const Z=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),U=i=>typeof i=="object"&&i!==null&&!Array.isArray(i),si=new Set(["__proto__","prototype","constructor"]),oi=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$notIn","$contains"]);function ai(i,e,t,n=o=>console.warn({...o,fieldPath:""}),r=100){if(!Number.isSafeInteger(r)||r<1)throw new Error("Invalid search limit");if(!Z(t,e))throw new Error("Unknown search entity");let o;try{o=typeof i=="string"?JSON.parse(i):i}catch{throw new Error("Dynamic search requires valid JSON")}if(!U(o)||Object.keys(o).some(h=>!["filter","orderBy"].includes(h)))throw new Error("Unsupported dynamic search input or control");if(o.filter!==void 0&&!U(o.filter))throw new Error("Invalid search filter");if(o.orderBy!==void 0&&!Array.isArray(o.orderBy))throw new Error("Invalid search ordering");const s=Object.entries(o.filter??{}),a=o.orderBy??[];if(s.length+a.length>r)throw new Error("Dynamic search exceeds clause limit");const c=[],u={filter:Object.create(null),orderBy:[]};function l(h){const p=h.split(".");if(p.length>16||p.some(d=>!d||d.startsWith("$")||si.has(d)))throw new Error("Invalid dynamic search field path");let m=t[e];for(const d of p.slice(0,-1)){if(!Z(m.relations,d))return;const b=m.relations[d];if(!Z(t,b))throw new Error("Invalid trusted search relation metadata");m=t[b]}const y=p[p.length-1];return Z(m.fields,y)?m.fields[y]:void 0}function f(h,p){c.push({code:"DYNAMIC_SEARCH_UNKNOWN_FIELD",entity:e,clause:p,fieldPath:h})}function g(h,p){if(h===null)return;if(!(p==="date"?typeof h=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(h)&&!h.startsWith("0000-")&&Number.isFinite(Date.parse(h+"T00:00:00Z"))&&new Date(h+"T00:00:00Z").toISOString().slice(0,10)===h:p==="decimal"?typeof h=="string"&&/^[+-]?\d+(?:\.\d+)?$/.test(h)||typeof h=="number"&&Number.isFinite(h):p==="integer"||p==="timestamp"?typeof h=="number"&&Number.isSafeInteger(h):p==="number"?typeof h=="number"&&Number.isFinite(h):typeof h===p))throw new Error("Invalid value for known search field")}for(const[h,p]of s){const m=U(p)?Object.entries(p):[["$eq",p]];if(m.length!==1||!oi.has(m[0][0]))throw new Error("Unsupported or malformed dynamic search operator");const[y,d]=m[0];if((y==="$in"||y==="$notIn")&&(!Array.isArray(d)||d.length>1e3))throw new Error("Invalid or oversized search value list");const b=l(h);if(b===void 0){f(h,"FILTER");continue}if(b==="unsupported")throw new Error("Known search field has no supported scalar binding");if(y==="$contains"&&b!=="string")throw new Error("String operator requires a string field");if(Array.isArray(d)){if(y!=="$in"&&y!=="$notIn")throw new Error("Unexpected search value list");d.forEach(E=>g(E,b))}else g(d,b);u.filter[h]={[y]:Array.isArray(d)?[...d]:d}}for(const h of a){if(!U(h)||Object.keys(h).some(m=>!["field","direction"].includes(m))||typeof h.field!="string"||!["asc","desc"].includes(h.direction))throw new Error("Invalid dynamic search ordering");const p=l(h.field);if(p===void 0){f(h.field,"ORDER_BY");continue}if(p==="unsupported")throw new Error("Known search field has no supported scalar binding");u.orderBy.push({field:h.field,direction:h.direction})}return c.forEach(h=>n({...h})),{search:u,warnings:c}}export{tt as B,ot as C,ci as D,Le as L,z as M,P as O,se as Q,Je as R,Ft as S,Dt as U,Y as a,ui as b,li as c,hi as d,et as e,C as f,ri as m}; diff --git a/assets/dynamic-search-Ch_QcWVU.js b/assets/dynamic-search-Ch_QcWVU.js new file mode 100644 index 0000000000000000000000000000000000000000..8aa6295624fcd4cc13d4a4e38c05a81cc8a45ca9 --- /dev/null +++ b/assets/dynamic-search-Ch_QcWVU.js @@ -0,0 +1,8 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function t(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=t(r);fetch(r.href,o)}})();const Re=Object.freeze({success:()=>{},failure:()=>{}}),ut=new Set(["teaql.entity.id","teaql.user.id","teaql.tenant.id","teaql.query.parameters","teaql.field.values","teaql.audit.reason","db.query.parameter_values","http.request.body","url.full"]);function ht(i){const e={"teaql.operation.family":i.family,"teaql.operation.name":i.name};for(const[t,n]of Object.entries(i.attributes||{}))ut.has(t)||(e[t]=n);return Object.freeze({...i,attributes:Object.freeze(e)})}function N(i,e){if(!i)return Re;try{const t=i.start(ht(e));let n=!1;return{correlation:()=>{try{return t.correlation?.()}catch{return}},run:t.run?r=>t.run(r):r=>r(),success(r){if(!n){n=!0;try{t?.success(r)}catch{}}},failure(r){if(!n){n=!0;try{t?.failure(r)}catch{}}}}}catch{return Re}}async function F(i,e,t,n){const r=N(i,e);try{const o=await(r.run?r.run(t):t());return r.success(n?.(o)),o}catch(o){throw r.failure(o),o}}class dt extends Error{constructor(e){super(`Check failed: ${e.map(t=>t.message??`${t.ruleId}:${t.location}`).join("; ")}`),this.violations=e,this.name="CheckException"}}class C extends Error{constructor(e){super(`Object storage: ${e}`),this.code=e,this.name="StorageError"}}const Ke=Symbol.for("nodejs.util.inspect.custom"),G=()=>{throw new C("InvalidInput")};function ft(i){return(typeof i!="string"||!i||/[^\x20-\x7e]/.test(i))&&G(),i}class gt{#e;#t;constructor(e=300,t,n){(!Number.isInteger(e)||e<=0||e>604800||t!==void 0&&!["inline","attachment"].includes(t))&&G(),n!==void 0&&(ft(n),(!t||/[\/\\"]/.test(n))&&G()),this.#e=e,this.#t=t+(n===void 0?"":`; filename="${n}"`),t===void 0&&(this.#t=void 0)}get seconds(){return this.#e}get contentDisposition(){return this.#t}toString(){return"ObjectReadUrlOptions[details=masked]"}[Ke](){return this.toString()}}function ke(i){return i instanceof C?i:new C("Unavailable")}const Ce=i=>String(i??"").replace(/[\x00-\x1f\x7f-\x9f]/g," ");class _e{constructor(e,t){this.invocation=e,this.operation=t,this.scope=N(e.context.getResource("runtimeTelemetry"),{family:"object_storage",name:t})}#e=!1;#t=performance.now();finish(e){if(this.#e)return;this.#e=!0,e==="success"?this.scope.success():this.scope.failure(new C(e==="cancelled"?"Io":e));const t=Object.freeze({operation:this.operation,comment:Ce(this.invocation.comment),traceId:Ce(this.invocation.context.getResource("traceId")),outcome:e,elapsedMs:performance.now()-this.#t});try{const n=this.invocation.context.getResource("objectStorageObserver");n?n(t):console.info(`ObjectStorage operation=${t.operation} comment=${t.comment} trace=${t.traceId} outcome=${t.outcome} elapsedMs=${t.elapsedMs.toFixed(3)}`)}catch{}}}class pt{#e;#t;#i;constructor(e,t,n){this.#e=e,this.#t=t,this.#i=n}get metadata(){return this.#e}get stream(){return this.#t}close(){return this.#i()}toString(){return"ObjectContent[masked]"}[Ke](){return this.toString()}}class mt{#e;#t;constructor(e,t){(typeof t!="string"||!t.trim())&&G();const n=e.getResource("objectStorageProvider");if(!n)throw new C("NotConfigured");this.#e=Object.freeze({context:e,comment:t}),this.#t=n}async#i(e,t){const n=new _e(this.#e,e);try{const r=await(n.scope.run?n.scope.run(t):t());return n.finish("success"),r}catch(r){const o=ke(r);throw n.finish(o.code),o}}async put(e,t,n){const r=t[Symbol.asyncIterator]();let o=!1;const s={next:async()=>{const a=await r.next();return a.done&&(o=!0),a},return:async()=>(o||(o=!0,await r.return?.()),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}};return this.#i("put",async()=>{try{return await this.#t.put(this.#e,e,s,n)}finally{await s.return()}})}async putBytes(e,t,n){return this.put(e,(async function*(){yield t})(),n)}async get(e){const t=new _e(this.#e,"get");let n;try{n=await(t.scope.run?t.scope.run(()=>this.#t.get(this.#e,e)):this.#t.get(this.#e,e))}catch(c){const l=ke(c);throw t.finish(l.code),l}let r=!1,o=!1;const s=async()=>{if(!r){r=!0;try{await n.close(),t.finish("cancelled")}catch{throw t.finish("Io"),new C("Io")}}},a={[Symbol.asyncIterator]:async function*(){if(o||r)throw new C("Io");o=!0;let c=n.metadata.size;try{for await(const l of n.stream){if(!(l instanceof Uint8Array)||l.byteLength>c)throw new C("Io");c-=l.byteLength,yield l}if(c!==0)throw new C("Io");t.finish("success")}catch{throw t.finish("Io"),new C("Io")}finally{await s()}}};return new pt(n.metadata,a,s)}async getBytes(e,t){(!Number.isSafeInteger(t)||t<0)&&G();const n=await this.get(e);try{if(n.metadata.size>t)throw new C("TooLarge");const r=[];let o=0;for await(const c of n.stream){if(c.byteLength>t-o)throw new C("TooLarge");o+=c.byteLength,r.push(c)}const s=new Uint8Array(o);let a=0;for(const c of r)s.set(c,a),a+=c.byteLength;return s}finally{await n.close()}}head(e){return this.#i("head",()=>this.#t.head(this.#e,e))}async exists(e){return await this.head(e)!==void 0}delete(e){return this.#i("delete",()=>this.#t.delete(this.#e,e))}getReadUrl(e,t=new gt){return this.#i("read_url",()=>this.#t.getReadUrl(this.#e,e,t))}}const yt="teaql.i18n/v1",wt="en",bt={en:{messages:{"checker.required":"The {location} is required","checker.min":"The {location} should be equal or greater than {system}, but input is {input}","checker.max":"The {location} should be equal or less than {system}, but input is {input}","checker.minLength":"The length of {location} should be equal or greater than {system}, but the length of {input} is {input_len}","checker.maxLength":"The length of {location} should be equal or less than {system}, but the length of {input} is {input_len}"},vocabulary:{}},"zh-CN":{messages:{"checker.required":"{location} 是必填项","checker.min":"{location} 应该大于等于 {system},但输入值为 {input}","checker.max":"{location} 应该小于等于 {system},但输入值为 {input}","checker.minLength":"{location} 的长度应大于等于 {system},但实际长度为 {input_len}","checker.maxLength":"{location} 的长度应小于等于 {system},但实际长度为 {input_len}"},vocabulary:{}},"zh-TW":{messages:{"checker.required":"{location} 是必填的","checker.min":"{location} 應該等於或大於 {system},但輸入為 {input}","checker.max":"{location} 應該等於或小於 {system},但輸入為 {input}","checker.minLength":"{location} 的長度應該等於或大於 {system},但 {input} 的長度是 {input_len}","checker.maxLength":"{location} 的長度應該等於或小於 {system},但 {input} 的長度是 {input_len}"},vocabulary:{}},ja:{messages:{"checker.required":"{location} は必須です","checker.min":"{location} は {system} 以上である必要があります。入力値は {input} です","checker.max":"{location} は {system} 以下である必要があります。入力値は {input} です","checker.minLength":"{location} の長さは {system} 以上である必要があります。実際の長さは {input_len} です","checker.maxLength":"{location} の長さは {system} 以下である必要があります。実際の長さは {input_len} です"},vocabulary:{}},ko:{messages:{"checker.required":"{location}은(는) 필수입니다","checker.min":"{location}은(는) {system} 이상이어야 하지만 입력값은 {input}입니다","checker.max":"{location}은(는) {system} 이하여야 하지만 입력값은 {input}입니다","checker.minLength":"{location}의 길이는 {system} 이상이어야 하지만 실제 길이는 {input_len}입니다","checker.maxLength":"{location}의 길이는 {system} 이하여야 하지만 실제 길이는 {input_len}입니다"},vocabulary:{}},de:{messages:{"checker.required":"{location} ist erforderlich","checker.min":"{location} muss mindestens {system} sein, aber die Eingabe ist {input}","checker.max":"{location} darf höchstens {system} sein, aber die Eingabe ist {input}","checker.minLength":"Die Länge von {location} muss mindestens {system} sein, ist aber {input_len}","checker.maxLength":"Die Länge von {location} darf höchstens {system} sein, ist aber {input_len}"},vocabulary:{}},fr:{messages:{"checker.required":"{location} est obligatoire","checker.min":"{location} doit être supérieur ou égal à {system}, mais la valeur saisie est {input}","checker.max":"{location} doit être inférieur ou égal à {system}, mais la valeur saisie est {input}","checker.minLength":"La longueur de {location} doit être supérieure ou égale à {system}, mais elle est {input_len}","checker.maxLength":"La longueur de {location} doit être inférieure ou égale à {system}, mais elle est {input_len}"},vocabulary:{}},es:{messages:{"checker.required":"{location} es requerido/a","checker.min":"{location} debe ser mayor o igual que {system}, pero el valor ingresado es {input}","checker.max":"{location} debe ser menor o igual que {system}, pero el valor ingresado es {input}","checker.minLength":"La longitud de {location} debe ser mayor o igual que {system}, pero es {input_len}","checker.maxLength":"La longitud de {location} debe ser menor o igual que {system}, pero es {input_len}"},vocabulary:{}},pt:{messages:{"checker.required":"{location} é obrigatório","checker.min":"{location} deve ser maior ou igual a {system}, mas a entrada é {input}","checker.max":"{location} deve ser menor ou igual a {system}, mas a entrada é {input}","checker.minLength":"O comprimento de {location} deve ser maior ou igual a {system}, mas é {input_len}","checker.maxLength":"O comprimento de {location} deve ser menor ou igual a {system}, mas é {input_len}"},vocabulary:{}},ar:{messages:{"checker.required":"{location} مطلوب","checker.min":"يجب أن يكون {location} مساويًا أو أكبر من {system}، لكن المُدخل هو {input}","checker.max":"يجب أن يكون {location} مساويًا أو أصغر من {system}، لكن المُدخل هو {input}","checker.minLength":"يجب أن يكون طول {location} مساويًا أو أكبر من {system}، لكن الطول هو {input_len}","checker.maxLength":"يجب أن يكون طول {location} مساويًا أو أصغر من {system}، لكن الطول هو {input_len}"},vocabulary:{}},th:{messages:{"checker.required":"{location} เป็นสิ่งจำเป็น","checker.min":"{location} ควรจะเท่ากับหรือมากกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.max":"{location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.minLength":"ความยาวของ {location} ควรจะเท่ากับหรือมากกว่า {system} แต่ความยาวคือ {input_len}","checker.maxLength":"ความยาวของ {location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ความยาวคือ {input_len}"},vocabulary:{}},id:{messages:{"checker.required":"{location} wajib diisi","checker.min":"{location} harus sama dengan atau lebih besar dari {system}, tetapi input adalah {input}","checker.max":"{location} harus sama dengan atau lebih kecil dari {system}, tetapi input adalah {input}","checker.minLength":"Panjang {location} harus sama dengan atau lebih besar dari {system}, tetapi panjangnya {input_len}","checker.maxLength":"Panjang {location} harus sama dengan atau lebih kecil dari {system}, tetapi panjangnya {input_len}"},vocabulary:{}},fil:{messages:{"checker.required":"Ang {location} ay kinakailangan","checker.min":"Ang {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang input ay {input}","checker.max":"Ang {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang input ay {input}","checker.minLength":"Ang haba ng {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang haba ay {input_len}","checker.maxLength":"Ang haba ng {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang haba ay {input_len}"},vocabulary:{}},uk:{messages:{"checker.required":"{location} є обов'язковим","checker.min":"{location} повинен бути рівним або більшим за {system}, але ввідне значення {input}","checker.max":"{location} повинен бути рівним або меншим за {system}, але ввідне значення {input}","checker.minLength":"Довжина {location} повинна бути рівною або більшою за {system}, але довжина становить {input_len}","checker.maxLength":"Довжина {location} повинна бути рівною або меншою за {system}, але довжина становить {input_len}"},vocabulary:{}},vi:{messages:{"checker.required":"{location} là bắt buộc","checker.min":"{location} phải lớn hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.max":"{location} phải nhỏ hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.minLength":"Độ dài của {location} phải lớn hơn hoặc bằng {system}, nhưng độ dài là {input_len}","checker.maxLength":"Độ dài của {location} phải nhỏ hơn hoặc bằng {system}, nhưng độ dài là {input_len}"},vocabulary:{}}},St={schema:yt,defaultLocale:wt,locales:bt},vt=["en","zh-CN","zh-TW","ja","ko","de","fr","es","pt","ar","th","id","fil","uk","vi"];class Pe extends Error{constructor(e){super(`Unsupported locale: ${e}`),this.localeCode=e}}const Et={"en-us":"en","en-gb":"en",zh:"zh-CN","zh-hans":"zh-CN","zh-sg":"zh-CN",cn:"zh-CN","zh-hant":"zh-TW","zh-hk":"zh-TW","zh-mo":"zh-TW",tw:"zh-TW","ja-jp":"ja","ko-kr":"ko","de-de":"de","fr-fr":"fr","es-mx":"es","pt-br":"pt","pt-pt":"pt","ar-sa":"ar","th-th":"th","id-id":"id",tl:"fil","fil-ph":"fil","uk-ua":"uk","vi-vn":"vi"};function We(i){if(typeof i!="string"||!i.trim())throw new Pe(i);const e=i.trim().replace(/_/g,"-").toLowerCase(),t=vt.find(r=>r.toLowerCase()===e);if(t)return t;const n=Et[e];if(!n)throw new Pe(i);return n}const ue=class ue{constructor(e,t){if(this.data=e,this.fallback=t,e.schema!=="teaql.i18n/v1")throw new Error("Unsupported i18n schema");Object.keys(e.locales).forEach(We)}message(e,t){return this.data.locales[e]?.messages[t]??this.fallback?.data.locales[e]?.messages[t]??this.data.locales.en?.messages[t]??this.fallback?.data.locales.en?.messages[t]??t}translate(e,t){const r={required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"}[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,o=String(e.inputValue),s=typeof e.inputValue=="string"?[...e.inputValue].length:0;return e.message=this.message(t,r).split("{location}").join(e.location.nativePath()).split("{system}").join(String(e.systemValue)).split("{input}").join(o).split("{input_len}").join(String(s)),e}};ue.builtin=new ue(St);let we=ue;const Ge=Symbol("teaql.context.schema-capability");function _(i){return Object.freeze(i.map(e=>Object.freeze({...e})))}class It{#e;#t;constructor(e,t){this.#e=e,this.#t=Object.freeze({...t}),Object.freeze(this)}recover(){const e=[];let t=this;for(;t;)e.push(t.#t),t=t.#e;return _(e.reverse())}}function Lt(i,e,t,n,r){const o=i?r:n;if(i&&(typeof o!="string"||new RegExp("^\\p{White_Space}*$","u").test(o)))return i;const s=String(t),a=/^(0|[1-9][0-9]*)$/.test(s)&&BigInt(s)<=18446744073709551615n?t:void 0;return new It(i,{kind:"auditReason",name:e,entityId:a,detail:o})}const $t=new Set(["comment","purpose","auditReason"]),de=i=>!new RegExp("^\\p{White_Space}*$","u").test(i);function be(i,e,t){const n=s=>{for(let a=i.length-1;a>=0;a--)if(i[a].kind===s)return i[a].detail??""},r=["operation","provider","sql"].every(s=>i.some(a=>a.kind===s));let o;if(r)o=i.filter(s=>!$t.has(s.kind));else{const s=i.find(c=>de(c.name))?.name??"unknown";let a=s;if(t!=="select")for(const c of i)c.kind==="entity"&&de(c.name)&&(a=c.name);o=[{kind:"operation",name:s,detail:t==="select"?"query":"mutation"},{kind:t==="select"?"request":"entity",name:t==="select"?s:a,detail:""},...i.filter(c=>c.kind==="relation"),{kind:"provider",name:de(e)?e:"unknown",detail:""},{kind:"sql",name:t,detail:""}]}return Object.freeze({tracePath:_(o),comment:n("comment"),purpose:n("purpose"),auditReason:n("auditReason")})}function He(i,e,t){return _([{kind:"comment",name:i,detail:e},{kind:"purpose",name:i,detail:t}])}function Ot(i,e,t,n){if(n&&!i.trim())throw new Error("Missing SQL template");let r=0;const o=new Set,s=l=>{if(l<0||l>=e.length)throw new Error("SQL bind count mismatch");return o.add(l),n?n(l):Ye(e[l],t)};let a="",c="sql";for(let l=0;l=0&&h=0&&ht.toString(16).padStart(2,"0")).join("")}'`:P(typeof i=="object"?JSON.stringify(i):String(i))}function P(i){return`'${i.replace(/'/g,"''")}'`}var Tt={};const At="TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS",Rt="I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK",ne="[REDACTED]",fe="[REDACTED SQL; NOT REPLAYABLE]",kt=`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN +`;let qe=!1;function Ct(i){const e=Array.from(i);return e.length<8||/^[0-9]+$/.test(i)?"*".repeat(e.length):e.slice(0,2).join("")+"*".repeat(e.length-4)+e.slice(-2).join("")}function _t(){const e=Tt?.[At]===Rt;return e&&!qe&&(qe=!0,console.warn("TeaQL: sensitive plaintext logging enabled; application data may be written to disk. Authentication secrets remain redacted.")),e}function H(i){const e=i.toLowerCase().replace(/[^a-z0-9]/g,"");return["password","passwd","passphrase","privatekey","secret","accesstoken","refreshtoken","idtoken","apikey","authorization","credential","sessiontoken","magiclinktoken"].some(t=>e.includes(t))}function Se(i){return Array.isArray(i)?i.some(Se):i&&typeof i=="object"?Object.entries(i).some(([e,t])=>H(e)||Se(t)):!1}function x(i){return i==null||i===""?[]:Array.isArray(i)?i.flatMap(x):i instanceof Date?[i.toISOString()]:typeof i=="object"?Object.values(i).flatMap(x):[String(i)]}function K(i,e){return[...new Set(e)].sort((t,n)=>n.length-t.length).reduce((t,n)=>t?.split(n).join(ne),i)}const W=new WeakMap,ve=new WeakMap,Xe=new WeakMap;function Ne(i,e,t=[]){Xe.set(i,{bindings:e?R(e):void 0,intentValues:Object.freeze(t.map(Y))})}function re(i){const e=i.parameterLogPolicies,t=!!e&&e.length===i.parameters.length,n=H(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!t);return i.parameters.map((r,o)=>{if(n||Se(r))return"credential";const s=t?e[o]:void 0;return s==="plain"||s==="masked"||s==="credential"?s:"unknown"})}function Ee(i,e){return i==="credential"||i==="unknown"||!e&&i!=="plain"}function xe(i){if(!i)return[];const e=re(i);return i.parameters.flatMap((t,n)=>Ee(e[n],!1)?x(t):[])}function Y(i){return i instanceof Date?new Date(i.getTime()):i instanceof Uint8Array?new Uint8Array(i):Array.isArray(i)?Object.freeze(i.map(Y)):i&&typeof i=="object"?Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,Y(t)]))):i}function R(i,e){const t=e?[e,i]:[i];return Object.freeze({parameterizedSQL:"",sqlOrigin:"generated",parameters:Object.freeze(t.flatMap(n=>n.parameters.map(Y))),parameterLogPolicies:Object.freeze(t.flatMap(re))})}function Ie(i){return i==null?null:Array.isArray(i)?i.map(Ie):i&&typeof i=="object"&&"type"in i?Ie(i.value):typeof i=="object"&&!(i instanceof Date)?ne:Ct(i instanceof Date?i.toISOString():String(i))}function Je(i,e,t=[]){const n=_t()&&i.logMode!=="masked",r=W.get(i);if(r!==void 0&&(!r||n))return i;const o=ve.get(i);if(!n&&o)return o;const s=se(i,n,e,t);if(W.set(s,n),n){const a=se(i,!1,e,t);W.set(a,!1),ve.set(s,a)}return s}function Pt(i){const e=ve.get(i);if(e)return e;if(W.get(i)===!1)return i;const t=se(i,!1);return W.set(t,!1),t}function se(i,e,t,n=[]){const r=Xe.get(i);r?.bindings&&(t=R(r.bindings,t)),r&&(n=[...n,...r.intentValues]);const o=i.parameterLogPolicies,s=!o||o.length===i.parameters.length,a=H(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!o||!s),c=re(i),l=c.map(w=>Ee(w,e)),u=i.parameters.flatMap((w,v)=>l[v]?x(w):[]);if(t){const w=re(t);u.push(...t.parameters.flatMap((v,I)=>Ee(w[I],e)?x(v):[]))}const f=[...u,...n.flatMap(x)],g=!e&&i.logMode==="debug-plaintext"&&!t,h=w=>g&&w?ne:K(w,f),p=i.parameters.map((w,v)=>l[v]?c[v]==="masked"?Ie(w):ne:Y(w)),m=i.parameterizedSQL.replace(/\$[0-9]+|@p[0-9]+/gi,"?"),y=(!e||a)&&i.sqlOrigin!=="generated"&&/['"`$]|--|\/\*|\b\d+\b|:[A-Za-z_]/.test(m),d=i.databaseKind??"sqlite";let b=fe,E=y?"untrusted-literal-sql":s?void 0:"policy-count-mismatch";if(!y&&s)try{b=Ot(i.parameterizedSQL,p,d,w=>Ye(p[w],d)+(l[w]?" /* masked */":"")),b=(e?l.some(Boolean)?`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN; PARTIALLY MASKED; NOT REPLAYABLE +`:kt:`-- TeaQL MASKED; NOT REPLAYABLE +`)+b}catch{b=fe,E="unsupported-or-mismatched-bindings"}return Object.freeze({...i,...i.statements?{statements:Object.freeze(i.statements.map(w=>se(w,e,R(i,t),n)))}:{},parameterizedSQL:y?fe:i.sqlOrigin==="generated"?i.parameterizedSQL:K(i.parameterizedSQL,u),parameters:Object.freeze(p),parameterLogPolicies:Object.freeze(c),maskedParameters:Object.freeze(l),logMode:e?"debug-plaintext":"masked",omissionReason:E,debugSQL:b,comment:h(i.comment),purpose:h(i.purpose),auditReason:h(i.auditReason),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},resultSummary:i.resultCount!==void 0?`${i.resultCount} rows returned`:i.affectedRows!==void 0?`${i.affectedRows} rows affected`:K(i.resultSummary,u),tracePath:Object.freeze(i.tracePath.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I]))))),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},...i.mutationLineage?{mutationLineage:Object.freeze(i.mutationLineage.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{}})}const X=new WeakMap,oe=new WeakMap;function je(i){return oe.get(i)}function qt(i,e){oe.set(i,e)}function Nt(i){return X.get(i)}function Q(i,e){X.set(e,X.get(i)??D(i))}function D(i,e=new Map){if(!i||typeof i!="object")return i;if(e.has(i))return e.get(i);if(i instanceof Date)return new Date(i.getTime());if(i instanceof Uint8Array)return new Uint8Array(i);const t=Array.isArray(i)?[]:Object.create(Object.getPrototypeOf(i));e.set(i,t);for(const o of Reflect.ownKeys(i)){const s=Object.getOwnPropertyDescriptor(i,o);"value"in s&&s.enumerable&&(s.value=D(s.value,e)),Object.defineProperty(t,o,s)}const n=X.get(i);n&&X.set(t,n);const r=oe.get(i);return r&&oe.set(t,r),t}const Z=new WeakMap;class Oe{#e;constructor(e={}){this.#e=D(e),Object.freeze(this)}values(){return D(this.#e)}static captureFor(e,t){const n=new Oe(t);return Z.set(e,n),n}static forEntity(e){return Z.get(e)}static restoreFor(e,t){t?Z.set(e,t):Z.delete(e)}}const Me=new WeakMap,ge=new WeakMap,Le=new WeakMap,Ze=new WeakMap;function et(i){if(!["named-count","facet","relation-count","relation-select","aggregate","pagination"].includes(i.kind)||i.method!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i.method)||i.alias!==void 0&&typeof i.alias!="string"||i.relation!==void 0&&typeof i.relation!="string")throw new Error("QUERY_OPERATION_INVALID: invalid generated operation descriptor");return Object.freeze({kind:i.kind,method:i.method,alias:i.alias,relation:i.relation})}function xt(i){const e=et(i),t=n=>"'"+n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+"'";return e.method?e.method+"("+(e.alias!==void 0?t(e.alias):e.kind==="relation-select"?"...":"")+")":"framework: "+e.kind+(e.relation?" "+e.relation:"")+(e.alias!==void 0?" "+t(e.alias):"")}const B=Symbol("runtime request binding");class jt extends Error{constructor(e,t,n){super(`${e}: ${n} request requires a non-blank ${t}; supply it at the request entry point`),this.code=e,this.field=t,this.requestKind=n,this.name="RequestIntentError"}}function z(i,e,t){if(typeof i!="string"||new RegExp("^\\p{White_Space}*$","u").test(i))throw new jt(e==="comment"?"REQUEST_COMMENT_REQUIRED":"QUERY_PURPOSE_REQUIRED",e,t);return i}class ae{#e;#t;constructor(e,t){this.#e=z(e,"comment","query"),this.#t=z(t,"purpose","query"),Object.freeze(this)}get comment(){return this.#e}get purpose(){return this.#t}}class U{#e;constructor(e){this.#e=z(e,"comment","mutation"),Object.freeze(this)}get comment(){return this.#e}get auditReason(){return this.#e}readbackIntent(){return new ae(this.#e,"verify persisted mutation result")}}class L{#e;#t;#i;#r;#s;#o;#n;constructor(e,t,n){const r=e,o=je(e),s=o instanceof L?o:void 0;if(this.#e=t===void 0?s?.intent??new ae(r?._comment??r?.commentText,r?._purpose??r?.purposeText):new ae(t?.comment,t?.purpose),n&&n[B]!==!0)throw new Error("QUERY_REQUEST_OWNERSHIP_INVALID: request binding is runtime-owned");const a=s&&s.intent.comment===this.#e.comment&&s.purpose===this.#e.purpose?s:void 0;this.#n=n?.invocation??(n?.parent?n.parent.#n:void 0)??(a?a.#n:void 0)??Object.freeze({}),this.#i=n?n.parent:a?.parentRequest,this.#r=z(n?.comment??a?.comment??this.#e.comment,"comment","query"),this.#s=n?.name??a?.requestName??String(r.entity??"query"),this.#o=n?.operation??a?.operation,this.#t=D(e);const c=this.#t;for(const[l,u]of[["commentText",this.comment],["purposeText",this.purpose],["_comment",this.comment],["_purpose",this.purpose]])Object.defineProperty(c,l,{value:u,enumerable:!l.startsWith("_"),configurable:!0,writable:!1});ge.set(c,_(n?.source??a?.traceSource??ge.get(e)??He(String(r.entity),this.intent.comment,this.purpose))),qt(c,this),Object.freeze(this)}get intent(){return this.#e}get query(){return this.#t}get comment(){return this.#r}get purpose(){return this.#e.purpose}get traceSource(){return ge.get(this.#t)}get parentRequest(){return this.#i}get rootRequest(){let e=this;for(;e.parentRequest;)e=e.parentRequest;return e}get requestName(){return this.#s}get operation(){return this.#o}get traceChain(){const e=[];for(let t=this;t;t=t.parentRequest)e.push({kind:"comment",name:t.requestName,detail:t.comment});return _([{kind:"purpose",name:this.rootRequest.requestName,detail:this.purpose},...e.reverse()])}withQuery(e){const t=je(e);if(t instanceof L&&t.#n!==this.#n)throw new Error("QUERY_SCOPE_OWNER_MISMATCH: replacement belongs to another query invocation");return new L(e,this.intent,{[B]:!0,parent:this.parentRequest,comment:this.comment,name:this.requestName,operation:this.operation,source:this.traceSource,invocation:this.#n})}deriveOperation(e,t){const n=et(t);return new L(e,this.intent,{[B]:!0,parent:this,comment:xt(n),name:String(e.entity??this.requestName),operation:n,source:this.traceSource})}deriveHelper(e,t){return new L(e,this.intent,{[B]:!0,parent:this,comment:z(t,"comment","query"),name:String(e.entity??this.requestName),source:this.traceSource})}derive(e,t,n){if(n)return this.deriveOperation(this.query,n).deriveChild(e,t);const r=`${String(this.query.entity)}.${t}`;return this.deriveChild(e,t,void 0,r)}deriveAggregate(e,t,n){const r=this.parentRequest?.operation?.kind==="facet"?this.parentRequest:void 0,o=r?r.deriveHelper(e,"aggregate "+r.operation.relation):this.deriveOperation(e,n),s=[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}],a=new L(e,this.intent,{[B]:!0,parent:o.parentRequest,comment:o.comment,name:o.requestName,operation:o.operation,source:s});return(e._comment??e.commentText)===void 0?a:a.deriveChild(e)}deriveChild(e,t,n,r){const o=e,s=o._comment??o.commentText;return new L(e,this.intent,{[B]:!0,parent:this,comment:s===void 0?n??`load ${String(o.entity)}`:z(s,"comment","query"),name:r??String(o.entity),source:t===void 0?this.traceSource:[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}]})}}class j{#e;#t;constructor(e,t){this.#e=new U(t===void 0?e?.comment:t?.comment),this.#t={...e},Object.defineProperty(this.#t,"comment",{value:this.#e.comment,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get intent(){return this.#e}get mutation(){return this.#t}get comment(){return this.#e.comment}withLoadedSnapshot(e){return Me.set(this,new Oe(e.values())),this}loadedValues(){return Me.get(this)?.values()??{}}get graphSession(){return Le.get(this)?.session}scopeFor(e){const t=Le.get(this),n=Lt(t?.parent,e.entity,e.id,this.comment,t?.localComment);return t&&Ze.set(n,t.session),n}traceFor(e){const t=this.#t,n=t.ledgerRoot?.traceChain(t.ledgerKey??e);return n?.length?_(n):this.scopeFor(e).recover()}auditProjection(e,t,n){const r=[...x(t),...x(this.#t.id),...n?xe(n):x(this.loadedValues()),...xe(this.graphSession?.logBindings)];return Object.freeze({reason:K(this.comment,r),mutationLineage:_(this.traceFor(e).map(o=>({...o,detail:K(o.detail,r)})))})}}class Mt{#e;#t;constructor(e){this.#e=new U(e?.comment),Object.freeze(this)}get intent(){return this.#e}request(e,t,n){if(t&&Ze.get(t)!==this)throw new Error("GRAPH_TRACE_SCOPE_MISMATCH: parent scope belongs to another graph invocation");const r=new j(e,this.#e);return Le.set(r,{session:this,parent:t,localComment:n}),r}captureLogBindings(e){this.#t=R(e,this.#t)}get logBindings(){return this.#t}}class De extends Error{constructor(e){super("GRAPH_ALREADY_COMMITTED: post-commit processing failed; do not retry as an uncommitted mutation"),this.cause=e,this.committed=!0,this.name="GraphCommittedError"}}const Dt="MUTATION-POLICY-001",Ft="MUTATION-POLICY-002";class k extends Error{constructor(e){super(e),this.name="MutationPolicyError"}}class wi{constructor(e){this.resolver=e}resolve(e){return this.resolver(e)}}class bi{constructor(e){this.finder=e}findApproval(e){return this.finder(e)}}class Bt{onWarning(e,t){!t.firstOccurrence||typeof console>"u"||console.warn(`TeaQL mutation policy warning code=${t.warningCode} requestKey=${t.snapshot.requestKey} source=${t.snapshot.source} approval=${t.snapshot.approvalStatus}`)}}let Fe=0;class zt{constructor(){this.profile={warningSink:new Bt},this.emittedWarnings=new Set,this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.remaining=new Map}setRegistry(e){this.profile.registry=e}setApprovalProvider(e){this.profile.approvalProvider=e}setWarningSink(e){this.profile.warningSink=e}beginGraph(){if(this.graphActive)throw new k("mutation policy graph is already active");this.graphActive=!0,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}endGraph(){this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}recordPreflight(e){if(!this.graphActive)return;if(this.graphReviewed)throw new k("mutation preflight cannot change after policy review");const t=Be(e);this.rootEntity??=t.entity,this.auditReason??=ee(e),this.preflight.push(t),this.preflightKeys.push(Qe(e,t))}enterMutation(e,t){const n=Be(t);if(!this.graphActive)return{snapshot:this.review(e,this.plan(n.entity,ee(t),[n]))};if(!this.graphReviewed){if(this.profile.registry&&this.preflight.length===0)throw new k("customer mutation policy requires complete graph preflight before provider mutation");if(!this.profile.registry&&this.preflight.length===0)return{snapshot:this.review(e,this.plan(n.entity,ee(t),[n]))};const r=this.preflight.length?this.preflight:[n];this.graphSnapshot=this.review(e,this.plan(this.rootEntity??r[0].entity,this.auditReason??ee(t),r)),this.remaining.clear();const o=this.preflight.length?this.preflightKeys:r.map(it);for(const s of o)this.remaining.set(s,(this.remaining.get(s)??0)+1);this.graphReviewed=!0}return this.consume(Qe(t,n)),{snapshot:this.graphSnapshot}}ensureGraphComplete(){if(this.graphReviewed&&this.remaining.size)throw new k("reviewed mutation plan contains operations that were not executed")}review(e,t){Qt(t);const n=ze(t),r=this.profile.registry?.resolve(n.requestKey);let o,s,a,c;if(!r)o="generated_default",a="not_applicable",c=[Dt];else{s=Ut(r.identity);const u=r.review(e,n);if(!u||u.verdict!=="allow"&&u.verdict!=="deny")throw new k("customer mutation policy returned an invalid decision");if(u.verdict==="deny")throw new k(`[MUTATION POLICY DENIED] ${u.code||"MUTATION-POLICY-DENIED"}: ${u.message||"mutation rejected"}`);o="customer";const f=this.profile.approvalProvider?.findApproval(s);a=Vt(f,s)?"approved":"missing",c=a==="approved"?[]:[Ft]}const l=Object.freeze({executionId:n.executionId,requestKey:n.requestKey,source:o,policy:s,approvalStatus:a,warningCodes:Object.freeze([...c]),operations:Object.freeze(n.operations.map(u=>Object.freeze({kind:u.kind,entity:u.entity,entityId:M(u.entityId),changedFields:Object.freeze(Object.keys(u.changedValues).sort())})))});for(const u of c)this.emitWarning(e,l,u);return l}plan(e,t,n){return Fe+=1,ze({executionId:`teaql-mutation-${Fe}`,requestKey:`${e}.saveGraph`,rootEntityType:e,auditReason:new U(t).comment,operations:n})}consume(e){const t=this.remaining.get(e)??0;if(t<1)throw new k("provider mutation is not present in the reviewed graph plan");t===1?this.remaining.delete(e):this.remaining.set(e,t-1)}emitWarning(e,t,n){const r=t.policy?`${t.policy.policyId}:${t.policy.version}:${t.policy.fingerprint}`:"none",o=`${t.requestKey}|${r}|${n}`,s=!this.emittedWarnings.has(o);this.emittedWarnings.add(o);try{this.profile.warningSink.onWarning(e,Object.freeze({snapshot:t,warningCode:n,firstOccurrence:s}))}catch{}}}function Be(i){const e=String(i?.entity??"").trim(),t=String(i?.action??"").toLowerCase(),n={create:"create",update:"update",delete:"delete",recover:"recover"};if(!e||!n[t])throw new k("mutation must contain a supported entity operation");const r=i?.payload&&typeof i.payload=="object"?i.payload:{};return Object.freeze({kind:n[t],entity:e,entityId:M(i?.id??r.id),originalVersion:i?.version??i?.expectedVersion,changedValues:tt(r)})}function ee(i){return new U(i?.comment).comment}function Qt(i){if(new U(i?.auditReason),!i.executionId?.trim())throw new k("execution id is required");if(!i.requestKey?.trim())throw new k("request key is required");if(!i.rootEntityType?.trim())throw new k("root entity type is required");if(!i.operations.length)throw new k("mutation plan is empty")}function Ut(i){if(!i||!i.policyId?.trim()||!i.version?.trim()||!i.fingerprint?.trim())throw new k("customer mutation policy identity is invalid");return Object.freeze({policyId:i.policyId.trim(),version:i.version.trim(),fingerprint:i.fingerprint.trim()})}function Vt(i,e){return!!i&&Kt(i.policy,e)&&!!i.approvedBy?.trim()&&i.approvedAt instanceof Date&&Number.isFinite(i.approvedAt.getTime())&&i.approvedAt.getTime()!==0}function Kt(i,e){return i.policyId===e.policyId&&i.version===e.version&&i.fingerprint===e.fingerprint}function ze(i){return Object.freeze({executionId:i.executionId,requestKey:i.requestKey,rootEntityType:i.rootEntityType,auditReason:i.auditReason,operations:Object.freeze(i.operations.map(e=>Object.freeze({kind:e.kind,entity:e.entity,entityId:M(e.entityId),originalVersion:e.originalVersion,changedValues:tt(e.changedValues)})))})}function M(i,e=new WeakSet){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||typeof i=="bigint")return i;if(i instanceof Date)return i.toISOString();if(typeof i=="object"){if(e.has(i))throw new k("mutation policy values must not contain cycles");e.add(i);try{if(Array.isArray(i))return Object.freeze(i.map(n=>M(n,e)));const t=i;return"id"in t&&Object.keys(t).some(n=>n!=="id")?M(t.id,e):Object.freeze(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,M(r,e)])))}finally{e.delete(i)}}return String(i)}function tt(i){return Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,M(t)])))}function it(i){return ce({kind:i.kind,entity:i.entity,entityId:i.entityId,originalVersion:i.originalVersion,changedValues:i.changedValues})}function Qe(i,e){const t=i?.ledgerKey;return t&&typeof t=="object"&&String(t.entity??"").trim()&&t.id!==void 0&&t.id!==null?`ledger:${String(t.entity).trim()}:${ce(t.id)}`:`operation:${it(e)}`}function ce(i){return typeof i=="bigint"?JSON.stringify(`${i.toString()}n`):i===void 0?'""':i===null||typeof i!="object"?JSON.stringify(i):Array.isArray(i)?`[${i.map(ce).join(",")}]`:`{${Object.entries(i).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${ce(t)}`).join(",")}}`}const Ue=new WeakMap;let Wt=1;function Gt(i){if(!i||typeof i!="object"&&typeof i!="function")return String(i);const e=i;let t=Ue.get(e);return t||(t=Wt++,Ue.set(e,t)),String(t)}class Ve extends Error{constructor(e,t,n){super(`context root ${e}: expected ${t}`),this.reason=e,this.expectedType=t,this.activeRoot=n,this.name="ContextRootError"}}class Ht{constructor(){this.mutationPolicy=new zt,this.resources=new Map,this.continuousPageCursors=new Map,this.retainedIdSets=new Map,this.idSetBuilds=new Map,this.continuousPageRuntime={owner:"",get:(e,t)=>this.getContinuousPageCursor(e,t),put:(e,t,n)=>this.putContinuousPageCursor(e,t,n),observe:(e,t)=>{this.continuousPagePlan=e,this.continuousPageCursorId=t}},this.idSetPaginationRuntime={owner:"",scope:"",get:e=>this.idSetStore().get(e),put:(e,t)=>this.idSetStore().put(e,t),build:(e,t)=>this.singleFlightIdSetBuild(e,t),observe:(e,t)=>{this.idSetPaginationPlan=e,this.idSetPaginationCount=t,this.idSetPaginationCountAccuracy=e==="ID_SET_BUILD"||e==="ID_SET_HIT"?"EXACT":e==="ID_SET_FALLBACK_LIMIT_EXCEEDED"?"LOWER_BOUND":"UNKNOWN"}},this.userIdentifier="",this.continuousPagePlan="DISABLED",this.idSetPaginationPlan="ID_SET_DISABLED",this.idSetPaginationCountAccuracy="UNKNOWN",this.locale="en",this.i18nCatalog=we.builtin}withObjectStorage(e){return this.insertResource("objectStorageProvider",e)}withObjectStorageObserver(e){return this.insertResource("objectStorageObserver",e)}objectStorage(e){return new mt(this,e)}async withQueryRequest(e,t){const n=this.requireResource("dataService");return n.withQueryRequest?n.withQueryRequest(e,t):t()}setLocaleCode(e){const t=We(e);return this.locale=t,this}setLanguageCode(e){return this.setLocaleCode(e)}installI18nCatalog(e){if(!e)throw new Error("catalog is required");return this.i18nCatalog=e,this}installIdSetPaginationStore(e){if(!e)throw new Error("ID set pagination store is required");return this.insertResource("idSetPaginationStore",e)}translateCheckResults(e){return e.map(t=>this.i18nCatalog.translate(t,this.locale))}withMutationPolicyRegistry(e){if(!e||typeof e.resolve!="function")throw new TypeError("mutation policy registry must expose resolve(requestKey)");return this.mutationPolicy.setRegistry(e),this}withMutationPolicyApprovalProvider(e){if(!e||typeof e.findApproval!="function")throw new TypeError("mutation policy approval provider must expose findApproval(identity)");return this.mutationPolicy.setApprovalProvider(e),this}withMutationGovernanceSink(e){if(!e||typeof e.onWarning!="function")throw new TypeError("mutation governance sink must expose onWarning(context, warning)");return this.mutationPolicy.setWarningSink(e),this}reviewMutationPlan(e){return this.mutationPolicy.review(this,e)}beginMutationPolicyGraph(){this.mutationPolicy.beginGraph()}recordMutationPolicyPreflight(e){this.mutationPolicy.recordPreflight(e)}enterMutationPolicy(e){return this.mutationPolicy.enterMutation(this,e).snapshot}ensureMutationPolicyGraphComplete(){this.mutationPolicy.ensureGraphComplete()}endMutationPolicyGraph(){this.mutationPolicy.endGraph()}beginFixEvidence(){return this.insertResource("fixEvidenceCurrent",[])}recordFixEvidence(e){const t=String(e.sourceLabel||""),n=t.toLowerCase();if(!e.entityType||!e.modelPath||!t||n.includes("authorization")||n.includes("cookie")||n.includes("token="))throw new TypeError("Fix evidence must contain only safe framework provenance labels");const r=this.getResource("fixEvidenceCurrent")??[];return this.getResource("fixEvidenceCurrent")||this.insertResource("fixEvidenceCurrent",r),r.push(Object.freeze({...e})),this}finishFixEvidence(){const e=this.getResource("fixEvidenceCurrent")??[];return this.insertResource("fixEvidenceLast",Object.freeze([...e])),this.removeResource("fixEvidenceCurrent")}lastFixEvidence(){return this.getResource("fixEvidenceLast")??[]}insertResource(e,t){return this.resources.set(e,t),this}getResource(e){return this.resources.get(e)}removeResource(e){return this.resources.delete(e),this}requireResource(e){const t=this.getResource(e);if(t===void 0)throw new Error(`Required UserContext resource is missing: ${e}`);return t}ensureSchema(){const e=this.requireResource("dataService"),t=e[Ge];if(!t)throw new Error("Configured dataService is not a schema-aware TeaQL provider");return t.call(e,this)}withActiveRoot(e){if(!e||!e.entity||e.id===void 0||e.id===null)throw new TypeError("active root must be a typed entity reference");return this.insertResource("activeRoot",Object.freeze({...e}))}requireActiveRoot(e){const t=this.getResource("activeRoot");if(!t)throw new Ve("missing",e);if(t.entity!==e)throw new Ve("type_mismatch",e,t);return t}prepareQuery(e){this.continuousPageRuntime.owner=this.userIdentifier,this.idSetPaginationRuntime.owner=this.userIdentifier;const t=this.getResource("activeRoot");return this.idSetPaginationRuntime.scope=[this.userIdentifier,t?`${t.entity}:${String(t.id)}`:"-",Gt(this.getResource("dataService"))].join("|"),e.bindContinuousPageRuntime(this.continuousPageRuntime).bindIdSetPaginationRuntime(this.idSetPaginationRuntime)}getContinuousPageCursor(e,t){const n=`${e}:${t}`,r=this.continuousPageCursors.get(n);if(r&&r.expiresAt<=Date.now()){this.continuousPageCursors.delete(n);return}return r}putContinuousPageCursor(e,t,n){if(this.continuousPageCursors.size>=4096){const r=[...this.continuousPageCursors.entries()].sort((o,s)=>o[1].expiresAt-s[1].expiresAt)[0];r&&this.continuousPageCursors.delete(r[0])}this.continuousPageCursors.set(`${e}:${t}`,n)}getRetainedIdSet(e){const t=this.retainedIdSets.get(e);if(t&&t.expiresAt<=Date.now()){this.retainedIdSets.delete(e);return}return t}idSetStore(){return this.getResource("idSetPaginationStore")??{get:e=>this.getRetainedIdSet(e),put:(e,t)=>this.putRetainedIdSet(e,t),invalidate:e=>{this.retainedIdSets.delete(e)}}}putRetainedIdSet(e,t){if(t.ids.byteLength>268435456)throw new Error("ID set exceeds the process-local store memory ceiling");const r=()=>[...this.retainedIdSets.values()].reduce((o,s)=>o+s.ids.byteLength,0);for(;this.retainedIdSets.size>=64||r()+t.ids.byteLength>268435456;){const o=[...this.retainedIdSets.entries()].sort((s,a)=>s[1].expiresAt-a[1].expiresAt)[0];if(!o)break;this.retainedIdSets.delete(o[0])}this.retainedIdSets.set(e,t)}async singleFlightIdSetBuild(e,t){const n=this.idSetBuilds.get(e);if(n)return{value:await n,built:!1};const r=t();this.idSetBuilds.set(e,r);try{return{value:await r,built:!0}}finally{this.idSetBuilds.delete(e)}}}function nt(i,e){const t=i.defaultDomainRoot,n=e.defaultDomainRoot;if(t&&n&&(t.entity!==n.entity||t.id!==n.id))throw new Error("Cannot compose Runtime Modules with different Default Domain Roots");const r=new Map;for(const o of[...i.constants??[],...e.constants??[]])r.set(`${o.entity}:${o.id}`,o);return{defaultDomainRoot:n??t,constants:[...r.values()],ensure:i.ensure&&e.ensure?async o=>{await i.ensure(o),await e.ensure(o)}:e.ensure??i.ensure}}class rt{constructor(e={},t={},n={}){this.schemas=Object.freeze({...e}),this.checkers=Object.freeze({...t}),this.bootstrap=Object.freeze({defaultDomainRoot:n.defaultDomainRoot,constants:Object.freeze([...n.constants??[]]),ensure:n.ensure})}and(e){return new rt({...this.schemas,...e.schemas},{...this.checkers,...e.checkers},nt(this.bootstrap,e.bootstrap))}}class q{constructor(e,t,n){this.field=e,this.expr=t,this.direction=n}static new(e,t){return new q(e,null,t)}static expr(e,t){return new q("",e,t)}static asc(e){return q.new(e,"Asc")}static desc(e){return q.new(e,"Desc")}}class le{constructor(e,t,n,r){this.enabledValue=e,this.cacheExpiredMillis=t,this.propagateValue=n,this.propagateCacheExpiredMillis=r}static enabled(e){return new le(!0,e,!1,0)}propagate(e){return this.propagateValue=!0,this.propagateCacheExpiredMillis=e,this}}let Yt=class st{constructor(e){this.hardLimitValue=1e4,this.filterCondition=null,this.limitValue=0,this.offsetValue=0,this.orderItems=[],this.selectItems=[],this.properties=[],this.joins=[],this.groupByItems=[],this.aggregateItems=[],this.facets=[],this.relations=[],this.relationAggregates=[],this.entity=e,Object.defineProperty(this,"hardLimitValue",{enumerable:!1,writable:!0,value:1e4}),Object.defineProperty(this,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"topNProbeThreshold",{enumerable:!1,writable:!0,value:void 0})}comment(e){return this.commentText=e,this}purpose(e){return this.purposeText=e,this}facetBy(e,t,n,r=!0,o){return this.facets.push({facetName:e,relationName:t,query:n.toQuery(),includeAllFacets:r,operation:o}),this}clone(){const e=D(this);for(const t of["commentText","purposeText","_comment","_purpose"]){const n=Object.getOwnPropertyDescriptor(e,t);n&&"value"in n&&n.configurable&&Object.defineProperty(e,t,{...n,writable:!0})}return e}filter(e){return this.filterCondition=e,this}limit(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.limitValue=e,this}optimizeForContinuousPageFetch(){return this.optimizeForContinuousPageFetchWith("default",600)}optimizeForContinuousPageFetchWith(e,t){if(!e?.trim())throw new Error("continuous page namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("continuous page ttlSeconds must be a positive integer");return this.continuousPageFetchOptions={namespace:e,ttlSeconds:t},this}bindContinuousPageRuntime(e){return this.continuousPageRuntimeContext=e,this}localContinuousPageOptions(){return this.continuousPageFetchOptions}localContinuousPageRuntime(){return this.continuousPageRuntimeContext}clearContinuousPageRuntime(){return this.continuousPageRuntimeContext=void 0,this}optimizePaginationWithIdSet(){return this.optimizePaginationWithIdSetConfig("default",600,3e6)}optimizePaginationWithIdSetConfig(e,t,n){if(!e?.trim())throw new Error("ID set namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("ID set ttlSeconds must be a positive integer");if(!Number.isSafeInteger(n)||n<=0)throw new Error("ID set maxIds must be a positive integer");return this.idSetPaginationOptions={namespace:e,ttlSeconds:t,maxIds:n},this}bindIdSetPaginationRuntime(e){return this.idSetPaginationRuntimeContext=e,this}localIdSetPaginationOptions(){return this.idSetPaginationOptions}localIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext}clearIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext=void 0,this}topNProbeParentThreshold(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("topNProbeParentThreshold must be a non-negative safe integer");return this.topNProbeThreshold=e,this}localTopNProbeParentThreshold(){return this.topNProbeThreshold}prepareForList(){if(!Number.isSafeInteger(this.offsetValue)||this.offsetValue<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");if(this.limitValue&&(!Number.isSafeInteger(this.limitValue)||this.limitValue<1))throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.applyListLimit(this.hardLimitValue),this}forExactCount(e="__teaql_total"){const t=new st(this.entity);return t.filterCondition=D(this.filterCondition),t.commentText=this.commentText,t.purposeText=this.purposeText,t.aggregate("Count","id",e),Q(this,t),t}applyListLimit(e){if(this.limitValue||(this.limitValue=e),this.limitValue>e)throw new Error(`QUERY_HARD_LIMIT_EXCEEDED: requested limit ${this.limitValue} exceeds hard limit ${e}`);for(const t of this.relations)t.query?.applyListLimit(1e4)}offset(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");return this.offsetValue=e,this}relation(e){return this.relations.push({name:e}),this}relationQuery(e,t,n="id",r="id",o=!0,s){return this.relations.push({name:e,query:t,localKey:n,foreignKey:r,many:o,operation:s}),this}relationAggregate(e,t,n,r=!0,o){return this.relationAggregates.push({relationName:e,alias:t,query:n,singleResult:r,operation:o}),this}order(e){return this.orderItems.push(e),this}select(e){return this.selectItems.push(...e),this}enableAggregationCacheFor(e){return this.aggregationCache=le.enabled(e),this}propagateAggregationCache(e){return this.aggregationCache||(this.aggregationCache=le.enabled(0)),this.aggregationCache.propagate(e),this}aggregate(e,t,n){return this.aggregateItems.push({function:e,field:t,alias:n}),this}groupBy(e){return this.groupByItems.push(e),this}};function Xt(i,e){if(i.logMode!=="masked")throw new Error("Telemetry requires safe SQL projection");const t=(n=[])=>JSON.stringify(n.map(r=>({kind:r.kind,name:r.name,detail:r.detail??""})));return Object.freeze({body:"TeaQL SQL execution",correlation:e,attributes:Object.freeze({"teaql.trace_chain":t(i.traceChain),"teaql.trace_path":t(i.tracePath),"teaql.mutation_lineage":t(i.mutationLineage),"teaql.intent.comment":i.comment??i.auditReason??"","teaql.intent.purpose":i.purpose??"","teaql.sql.debug":i.debugSQL,"teaql.sql.log_mode":i.logMode,"teaql.sql.operation":i.operation,"teaql.sql.outcome":i.executionOutcome??"unknown","teaql.sql.elapsed_us":i.elapsedMicros,...i.resultCount===void 0?{}:{"teaql.sql.result_count":i.resultCount},...i.affectedRows===void 0?{}:{"teaql.sql.affected_rows":i.affectedRows}})})}function pe(i,e=!1){try{e?console.warn(i):console.info(i)}catch{}}class J extends Array{static get[Symbol.species](){return Array}constructor(e=[],t={}){typeof e=="number"?super(e):super(...e),Object.setPrototypeOf(this,J.prototype),this.totalCount=t.totalCount,this.aggregations=t.aggregations??{},this.summary=t.summary??{},this.facets=t.facets??{},this.isLoaded=t.isLoaded??!0}static empty(){return new J([],{isLoaded:!1})}get data(){return this}withTotalCount(e){return this.totalCount=e,this}withFacet(e,t){return this.facets[e]=t,this}facet(e){return this.facets[e]}totalCountOrLength(){return this.totalCount??this.length}}function Jt(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function $e(i){if(i&&typeof i=="object"){const e=i;return e.id??e.Id}return i}function Zt(i,e){const t=Jt(e);for(const n of[e,`${e}Id`,t,`${t}_id`]){const r=$e(i[n]);if(r!=null)return r}}function ei(i){const e=i.function.toLowerCase();return e==="count"||e==="sum"?0:null}function ti(i,e){return typeof i=="number"&&typeof e=="number"?i-e:i instanceof Date&&e instanceof Date?i.getTime()-e.getTime():String(i).localeCompare(String(e))}async function ii(i,e,t,n,r,o){const s=n.clone();s.facets=[],s.relations=[],s.relationAggregates=[],s.orderItems=[],s.aggregateItems=[],s.groupByItems=[],s.offsetValue=0,s.limitValue=0,s.selectItems=[...new Set([r,...o.map(u=>u.field)])],s.comment(`aggregate ${r}`),Q(n,s);const a=await i.executeQuery(t.deriveHelper(e(s),`aggregate ${r}`).query),c=new Map,l=new Map;for(const u of a){const f=Zt(u,r);if(f==null)continue;const g=String(f),h=c.get(g)??{},p=l.get(g)??{};for(const m of o){const y=m.function.toLowerCase(),d=u[m.field];if(y==="count")d!=null&&(h[m.alias]=Number(h[m.alias]??0)+1);else if(y==="sum"||y==="avg"){if(d!=null){const b=Number(d);if(!Number.isFinite(b))throw new Error(`Facet aggregate ${m.alias} requires numeric values`);h[m.alias]=Number(h[m.alias]??0)+b,y==="avg"&&(p[m.alias]=(p[m.alias]??0)+1)}}else if(y==="min"||y==="max"){if(d!=null){const b=h[m.alias],E=b==null?0:ti(d,b);(b==null||y==="min"&&E<0||y==="max"&&E>0)&&(h[m.alias]=d)}}else throw new Error(`Unsupported facet aggregate: ${m.function}`)}c.set(g,h),l.set(g,p)}for(const[u,f]of c){const g=l.get(u)??{};for(const h of o){if(h.function.toLowerCase()!=="avg")continue;const p=g[h.alias]??0;f[h.alias]=p?Number(f[h.alias]??0)/p:null}}return c}async function ot(i,e,t,n){const r=new L(t);t=r.query;const o={};for(const s of n){const a=r.deriveOperation(t,s.operation??{kind:"facet",relation:s.relationName,alias:s.facetName}),c=a.deriveChild(s.query.clone(),s.relationName),l=c.query,u=l.facets;l.facets=[];const f=l.aggregateItems.map(d=>({function:String(d.function),field:String(d.field),alias:String(d.alias)})),g=f.length?f:[{function:"Count",field:"id",alias:"__teaql_facet_membership_count"}];let h;if(i.executeFacetAggregates)h=await i.executeFacetAggregates(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName,g);else if(i.executeFacetMembership&&g.every(d=>d.function.toLowerCase()==="count")){const d=await i.executeFacetMembership(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName);h=new Map([...d].map(([b,E])=>[b,Object.fromEntries(g.map(S=>[S.alias,E]))]))}else h=await ii(i,e,a,t,s.relationName,g);l.aggregateItems=[],l.groupByItems=[];for(const d of l.relationAggregates){if(d.query.entity!==t.entity)continue;const b=t.clone();b.selectItems=["id"],b.properties=[],b.relations=[],b.relationAggregates=[],b.facets=[],b.aggregateItems=[],b.groupByItems=[],b.orderItems=[],b.offsetValue=0,b.limitValue=0;const E={id:{$inSubquery:{query:b,field:"id"}}};d.query.filterCondition=d.query.filterCondition?{$and:[d.query.filterCondition,E]}:E,Q(t,d.query)}if(!s.includeAllFacets){const d={id:{$in:[...h.keys()]}};l.filterCondition=l.filterCondition?{$and:[l.filterCondition,d]}:d}Q(t,l);const m=(await i.executeQuery(c.withQuery(e(l)).query)).map(d=>{const b=String($e(d.id??d.Id)),E=h.get(b),S={...d};for(const w of f)S[w.alias]=E?.[w.alias]??ei(w);return S}).filter(d=>s.includeAllFacets||h.has(String($e(d.id??d.Id)))),y=new J(m);u.length&&(y.facets=await ot(i,e,c.withQuery(l).query,u)),o[s.facetName]=y}return o}function ni(i){const e=new Map;for(const t of Object.values(i))for(const n of Object.values(t.relations||{})){if(!n.many)continue;const r=i[n.targetEntity],o=r?.columns[n.foreignKey]?.columnName,s=r?.columns.id?.columnName;if(!r||!o||!s)continue;const a=`idx_${r.table}_${o}_${s}`;let c=2166136261;for(let f=0;f>>0).toString(36),u=a.length<=30?a:`${a.slice(0,Math.max(1,29-l.length))}_${l}`;e.set(u,{name:u,table:r.table,foreignColumn:o,idColumn:s})}return[...e.values()]}async function ri(i,e,t,n){const r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ID space floor ${n} for ${t}`);for(let o=1;o<=100;o+=1){const s=await i.query(`SELECT current_level AS id FROM teaql_id_space WHERE type_name = ${e(1)}`,[t]);if(!s.rowCount){try{if((await i.query(`INSERT INTO teaql_id_space(type_name, current_level) VALUES (${e(1)}, ${e(2)})`,[t,r])).rowCount===1)return}catch(l){if(!(await i.query(`SELECT current_level FROM teaql_id_space WHERE type_name = ${e(1)}`,[t])).rowCount)throw l}continue}const a=Number(s.rows[0].id);if(a>=r)return;const c=await i.query(`UPDATE teaql_id_space SET current_level = ${e(1)} WHERE type_name = ${e(2)} AND current_level = ${e(3)}`,[r,t,a]);if(c.rowCount===1)return;if(c.rowCount!==0)throw new Error(`ID space floor update for ${t} changed ${c.rowCount} rows on attempt ${o}`)}throw new Error(`Unable to synchronize ID space floor for ${t} after 100 optimistic-lock attempts`)}function si(i,e){return i===e?!0:(i instanceof Date&&(i=i.getTime()),e instanceof Date&&(e=e.getTime()),i!=null&&e!==null&&e!==void 0&&String(i)===String(e))}function ie(i){return Object.freeze(i.map((e,t)=>Object.freeze({...e,level:t})))}function me(i,e,t,n,r,o){const s=i.traceFor({entity:String(e.entity),id:r}),a=be([...s,{kind:"entity",name:String(e.entity),entityId:r,detail:""}],t,n);return{auditReason:i.comment,tracePath:ie(a.tracePath),mutationLineage:s,targetID:r,inheritedBindings:R(o,i.graphSession?.logBindings)}}class oi{constructor(e=t=>console.debug(t)){this.writer=e}write(e){e=Je(e),this.writer(`[TeaQL SQL][${e.operation}][${e.elapsedMicros}us] ${e.resultSummary}${e.executionOutcome?` outcome=${e.executionOutcome}`:""} +comment=${e.comment??""} purpose=${e.purpose??""} auditReason=${e.auditReason??""} tracePath=${ye(e.tracePath)} traceChain=${ye(e.traceChain??[])} mutationLineage=${ye(e.mutationLineage??[])} +`+(e.omissionReason?`SQL omitted: ${e.omissionReason} +`:"")+`Debug SQL: ${e.debugSQL}`)}}function ye(i){return JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString():t)}class Si{constructor(){this.mode="all",this.entries=[]}record(e){const t=e.operation==="select";this.mode==="disabled"||this.mode==="select"&&!t||this.mode==="mutation"&&t||this.entries.push(Object.freeze({...e,...e.traceChain?{traceChain:_(e.traceChain)}:{},parameters:Object.freeze([...e.parameters])}))}setMode(e){return this.mode=e,this.entries=[],this}enableAll(){return this.setMode("all")}enableSelect(){return this.setMode("select")}enableMutation(){return this.setMode("mutation")}disable(){return this.setMode("disabled")}snapshot(){return[...this.entries]}}class ai{constructor(e,t){this.driver=e,this.bootstrapTail=Promise.resolve(),this.sqlTrace=[],this.internalQueryToken=Symbol("teaql-internal-query"),this.bindLogPolicies=new WeakMap,this.bindOperandSources=new WeakMap,this.derivedQueryBindings=new WeakMap,this.derivedRelationAssembly=new WeakMap,this.auditEvents=[],this.diagnosticSQLLogSink=new oi,this.queryLoggingEnabled=!0,this.mutationLoggingEnabled=!0,this.customTelemetry=!1,this.checkers={},this.userContext=new Ht,this.bootstrap={},this.graphAuditActions=[],this.graphCommitActions=[],this.graphRollbackActions=[],this.graphSaveTail=Promise.resolve(),this.schemas={...t}}fieldLogPolicy(e,t){const n=e.columns[t],r=n?.modelName??n?.columnName??t;return H(r)||H(t)?"credential":e.auditMaskFields?e.auditMaskFields?.includes(r)||e.auditMaskFields?.includes(t)?"masked":n?.logPolicy??"unknown":"unknown"}bindValue(e,t,n,r){const o=this.bindLogPolicies.get(e)??e.map(()=>"unknown");e.push(t),o.push(n),this.bindLogPolicies.set(e,o),r!==void 0&&this.bindOperandSources.set(e,R({parameterizedSQL:"",parameters:[r],parameterLogPolicies:[n],sqlOrigin:"generated"},this.bindOperandSources.get(e)))}queryLogBindings(e,t){return R({parameterizedSQL:e,parameters:t,parameterLogPolicies:this.bindLogPolicies.get(t),sqlOrigin:"generated"},this.bindOperandSources.get(t))}install(e){return Object.assign(this.schemas,e.schemas),Object.assign(this.checkers,e.checkers),this.bootstrap=nt(this.bootstrap,e.bootstrap),this}setUserContext(e){return this.userContext=e,this}schema(e){const t=this.schemas[e];if(!t)throw new Error(`Unknown TeaQL entity: ${e}`);return t}toRuntimeMutationRecord(e,t){const n={};for(const[r,o]of Object.entries(t)){const s=e.columns[r]?r:Object.keys(e.columns).find(a=>e.columns[a].modelName===r||e.columns[a].columnName===r);s&&(n[s]=o)}return n}encode(e,t){const n=e?.id??e;if(n!==void 0)return this.driver.encode(n,t)}decodeRow(e,t,n=[]){const r=this.schema(e),o={...t};for(const[s,a]of Object.entries(r.columns)){const c=o[s];c!=null&&(a.decode==="number"&&(o[s]=Number(c)),a.decode==="string"&&(o[s]=String(c)),a.decode==="date"&&c instanceof Date&&(o[s]=c.toISOString()),a.logicalType==="boolean"&&(o[s]=!!c))}for(const s of n)o[s]!==null&&o[s]!==void 0&&(o[s]=Number(o[s]));return o}get auditTrace(){return[...this.auditEvents]}setAuditSink(e){return this.auditSink=e,this}setRuntimeTelemetrySink(e){return this.telemetrySink=e,this}setDiagnosticSQLLogSink(e){return this.diagnosticSQLLogSink=e,this}setQueryLoggingEnabled(e){return this.queryLoggingEnabled=e,this}setMutationLoggingEnabled(e){return this.mutationLoggingEnabled=e,this}setRuntimeTelemetry(e){return this.customTelemetry=!0,this.runtimeTelemetry=e,this}attachStandardTelemetryStartup(e){this.telemetryStartup=e.then(async t=>{if(t){if(this.customTelemetry){await t.release();return}this.standardTelemetryHandle=t,this.runtimeTelemetry=t.telemetry}}).catch(()=>{pe("TeaQL telemetry: initialization failed; business continues without export.",!0)})}async flushTelemetry(){await this.telemetryStartup;try{await this.standardTelemetryHandle?.flush()}catch{pe("TeaQL telemetry: export flush failed; business outcome unchanged.",!0)}}async withQueryRequest(e,t){return new L(e),await this.telemetryStartup,F(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.request`,attributes:{"teaql.entity.type":String(e.entity)}},t)}recordSQL(e,t,n,r,o,s,a={},c="success",l,u){const g=e==="select"?this.queryLoggingEnabled:this.mutationLoggingEnabled,{targetID:h,inheritedBindings:p,...m}=a,y=Object.freeze({operation:e,...m,executionOutcome:c,traceChain:_(a.traceChain??[]),tracePath:ie(a.tracePath??[]),...a.traceChain?{traceChain:_(a.traceChain)}:{},...a.mutationLineage?{mutationLineage:_(a.mutationLineage)}:{},parameterizedSQL:t,parameters:Object.freeze([...n]),debugSQL:"",databaseKind:this.driver.databaseKind,sqlOrigin:"generated",parameterLogPolicies:Object.freeze([...this.bindLogPolicies.get(n)??n.map(()=>"unknown")]),elapsedMicros:Math.max(0,(Date.now()-r)*1e3),resultCount:o,affectedRows:s,resultSummary:o!==void 0?`${o} rows returned`:s!==void 0?`${s} rows affected`:`statement ${c}; row count unknown`}),d=p&&l?R(l,p):p??l,b=this.bindOperandSources.get(n),E=b?R(b,d):d;if(Ne(y,E,h===void 0?[]:[h]),this.runtimeTelemetry?.recordDiagnostic)try{this.runtimeTelemetry.recordsSQLDiagnostics?.()!==!1&&this.runtimeTelemetry.recordDiagnostic(Xt(Pt(y),u))}catch{pe("TeaQL telemetry: SQL diagnostic rejected; business outcome unchanged.",!0)}if(!this.telemetrySink&&!(g&&this.diagnosticSQLLogSink))return y;try{const S=Je(y);try{this.telemetrySink?.record(S)}catch{}if(g)try{this.diagnosticSQLLogSink?.write(S)}catch{}}catch{}return y}queryLogIntent(e){const t=new L(e),n=be(t.traceSource,this.driver.databaseKind,"select");return{comment:t.intent.comment,purpose:t.purpose,traceChain:t.traceChain,tracePath:ie(n.tracePath)}}async executeLoggedSQL(e,t,n,r,o,s,a){await this.telemetryStartup;const c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.${e}`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":e==="select"?"query":e}}),l=c.correlation?.(),u=Date.now();let f;try{f=await(c.run?c.run(o):o())}catch(h){try{const p=this.recordSQL(e,t,n,u,void 0,void 0,r,"failure",s,l);a?.push(p)}finally{throw c.failure(h),h}}const g=this.recordSQL(e,t,n,u,e==="select"?f.rowCount:void 0,e==="select"?void 0:f.rowCount,r,"success",s,l);return a?.push(g),c.success({attributes:{"teaql.result.cardinality":f.rowCount}}),f}async[Ge](e){await this.telemetryStartup,this.schemaReady||(this.schemaReady=this.driver.ensureSchema(this.schemas)),await this.schemaReady;const t=this.bootstrapTail;let n;this.bootstrapTail=new Promise(s=>{n=s}),await t,this.userContext=e;const r=e.getResource("bootstrapActor"),o=e.getResource("bootstrapCategory");e.insertResource("bootstrapActor","teaql-generated-bootstrap"),e.insertResource("bootstrapCategory","runtime-bootstrap");try{this.bootstrap.ensure?await this.bootstrap.ensure(e):await this.ensureBootstrapData()}finally{r===void 0?e.removeResource("bootstrapActor"):e.insertResource("bootstrapActor",r),o===void 0?e.removeResource("bootstrapCategory"):e.insertResource("bootstrapCategory",o),n()}}invalidateSchemaState(){this.schemaReady=void 0}async ensureBootstrapData(){const e=[...this.bootstrap.defaultDomainRoot?[this.bootstrap.defaultDomainRoot]:[],...this.bootstrap.constants??[]];e.length&&await this.executeGraphSave(new U("reconcile model bootstrap data"),async t=>{const n=this.graphMutationSession,r=[];for(const o of e){const s=await this.planBootstrapMutation(n,o);s&&r.push({record:o,request:t.request(s)})}for(const{request:o}of r)this.preflightMutation(o);for(const{request:o}of r)await this.executeMutation(o);for(const o of e)await this.driver.ensureIdFloor(n,o.entity,o.id)})}async planBootstrapMutation(e,t){const n=this.schema(t.entity),r=Object.entries(t.values??{}).map(([g,h])=>{const p=n.columns[g];if(!p)throw new Error(`Unknown bootstrap field ${t.entity}.${g}`);return{column:p.columnName,value:this.driver.encode(h,p)}}),o=new Yt(t.entity).filter({id:{$eq:t.id}}).limit(1).comment("inspect model bootstrap record").purpose("ensure model-defined root and constants");o.prepareForList();const s=new L(o),a=`SELECT * FROM ${this.driver.identifier(n.table)} WHERE ${this.driver.identifier(n.columns.id?.columnName??"id")} = ${this.driver.placeholder(1)}`,c=[t.id];this.bindLogPolicies.set(c,[this.fieldLogPolicy(n,"id")]);const l=await this.executeLoggedSQL("select",a,c,this.queryLogIntent(s.query),()=>e.query(a,c));if(!l.rowCount)return{entity:t.entity,action:"Create",id:t.id,version:0,payload:{...t.values}};const u=l.rows[0];if(r.filter(g=>!si(u[g.column],g.value)).length)return{entity:t.entity,action:"Update",id:t.id,version:Number(u[n.columns.version?.columnName??"version"]),payload:{...this.decodeRowForSchema(n,u),...t.values}}}async executeGraphSave(e,t){const n=new Mt(e);await this.telemetryStartup;const r=async()=>{const o=this.graphSaveTail;let s;this.graphSaveTail=new Promise(u=>{s=u}),await o;let a=!1,c=!1,l=!1;try{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],this.userContext.insertResource("fixTime",new Date),this.userContext.beginFixEvidence(),a=!0,this.userContext.beginMutationPolicyGraph(),c=!0;const u=await this.driver.transaction(async h=>{this.graphMutationSession=h,this.activeGraph=n;try{const p=await t(n);return this.userContext.ensureMutationPolicyGraphComplete(),p}finally{this.graphMutationSession=void 0,this.activeGraph=void 0}});l=!0;let f,g=!1;for(const h of[...this.graphCommitActions,...this.graphAuditActions])try{await h()}catch(p){g||(f=p),g=!0}if(g)throw new De(f);return u}catch(u){if(!l)for(const f of[...this.graphRollbackActions].reverse())try{f()}catch{}throw u}finally{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],c&&this.userContext.endMutationPolicyGraph(),this.userContext.removeResource("fixTime"),a&&this.userContext.finishFixEvidence(),s()}};return F(this.runtimeTelemetry,{family:"mutation",name:"graph.save",attributes:{"teaql.entity.type":"graph","teaql.mutation.kind":"graph"}},r)}afterGraphCommit(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphCommitActions.push(e)}afterGraphRollback(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphRollbackActions.push(e)}requireGraphOwnership(e){if(e.graphSession!==this.activeGraph||this.graphMutationSession!==void 0&&e.graphSession===void 0)throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability")}async withMutationSession(e,t){return this.requireGraphOwnership(e),e.graphSession?t(this.graphMutationSession):this.driver.transaction(t)}preflightMutation(e){const t=e instanceof j?e:new j(e);if(this.requireGraphOwnership(t),e=this.checkAndFixMutation(t),t.graphSession){const n=this.schema(e.entity);t.graphSession.captureLogBindings(this.mutationLogBindings(t,e,n))}return this.userContext.recordMutationPolicyPreflight(e),e}mutationLogBindings(e,t,n){const r=o=>{const s=this.toRuntimeMutationRecord(n,o),a=Object.keys(s);return{parameterizedSQL:"",sqlOrigin:"generated",parameters:a.map(c=>s[c]),parameterLogPolicies:a.map(c=>this.fieldLogPolicy(n,c))}};return R(r(t.payload||{}),r(e.loadedValues()))}checkAndFixMutation(e){const t=e instanceof j?e:new j(e);this.requireGraphOwnership(t),e=t.mutation,e={...e,payload:{...e?.payload??{}}},Object.defineProperty(e,"comment",{value:t.comment,enumerable:!0});const n=this.checkers[String(e.entity)];if(!n)return e;const r=[],o=this.userContext.getResource("fixTime")===void 0;o&&this.userContext.insertResource("fixTime",new Date).beginFixEvidence();try{if(n.checkAndFix(this.userContext,e,r),e.ledgerKey&&e.ledgerRoot)for(const[s,a]of Object.entries(e.payload||{}))e.ledgerRoot.set(e.ledgerKey,s,a);if(this.userContext.translateCheckResults(r),r.length)throw new dt(r);return e}finally{o&&this.userContext.removeResource("fixTime").finishFixEvidence()}}async executeMutation(e){await this.telemetryStartup;const t=e instanceof j?e:new j(e);this.requireGraphOwnership(t),e=t.mutation;const n=N(this.runtimeTelemetry,{family:"mutation",name:`${String(e?.entity||"unknown")}.${String(e?.action||"unknown").toLowerCase()}`,attributes:{"teaql.entity.type":String(e?.entity||"unknown"),"teaql.mutation.kind":String(e?.action||"unknown").toLowerCase()}}),r=async()=>{try{e=this.checkAndFixMutation(t);const o=this.userContext.enterMutationPolicy(e),s=this.schema(e.entity),a=this.toRuntimeMutationRecord(s,e.payload||{}),c=this.mutationLogBindings(t,e,s),l=this.driver.identifier(s.table),u=[],f=await F(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.mutation`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":String(e.action).toLowerCase()}},()=>this.withMutationSession(t,async y=>{if(e.action==="Create"){const d=e.id?String(e.id):await this.driver.nextId(y,e.entity);e.id&&await this.driver.ensureIdFloor(y,e.entity,d);const b=Number(e.version||0)+1,E={...a,id:d,version:b},S=Object.keys(s.columns).filter($=>E[$]!==void 0),w=S.map($=>this.driver.identifier(s.columns[$].columnName)).join(", "),v=S.map(($,T)=>this.driver.placeholder(T+1)).join(", "),I=S.map($=>this.encode(E[$],s.columns[$]));this.bindLogPolicies.set(I,S.map($=>this.fieldLogPolicy(s,$)));const O=`INSERT INTO ${l} (${w}) VALUES (${v})`,A=me(t,e,this.driver.databaseKind,"insert",d,c);return await this.executeLoggedSQL("insert",O,I,A,()=>y.query(O,I),void 0,u),{success:!0,id:d,version:b,persistedRecord:await this.readPersistedRecord(y,s,d,A,O,I,u)}}if(e.action==="Update"){const d=Object.keys(s.columns).filter($=>$!=="id"&&$!=="version"&&a[$]!==void 0),b=d.map($=>this.encode(a[$],s.columns[$]));this.bindLogPolicies.set(b,d.map($=>this.fieldLogPolicy(s,$)));const E=d.map(($,T)=>`${this.driver.identifier(s.columns[$].columnName)} = `+this.driver.placeholder(T+1)),S=this.driver.identifier("version");E.push(`${S} = ${S} + 1`),this.bindValue(b,String(e.id),this.fieldLogPolicy(s,"id"));const w=[`${this.driver.identifier("id")} = ${this.driver.placeholder(b.length)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),w.push(`${S} = ${this.driver.placeholder(b.length)}`));const v=`UPDATE ${l} SET ${E.join(", ")} WHERE ${w.join(" AND ")}`,I=me(t,e,this.driver.databaseKind,"update",String(e.id),c);if((await this.executeLoggedSQL("update",v,b,I,()=>y.query(v,b),void 0,u)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const A=await this.readPersistedRecord(y,s,String(e.id),I,v,b,u);return{success:!0,id:String(e.id),version:Number(A.version),persistedRecord:A}}if(e.action==="Delete"){const d=this.driver.identifier("version"),b=[String(e.id)];this.bindLogPolicies.set(b,[this.fieldLogPolicy(s,"id")]);const E=[`${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),E.push(`${this.driver.identifier("version")} = `+this.driver.placeholder(b.length)));const S=`UPDATE ${l} SET ${d} = -(${d} + 1) WHERE ${E.join(" AND ")}`,w=me(t,e,this.driver.databaseKind,"delete",String(e.id),c);if((await this.executeLoggedSQL("delete",S,b,w,()=>y.query(S,b),void 0,u)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const I=await this.readPersistedRecord(y,s,String(e.id),w,S,b,u);return{success:!0,id:String(e.id),version:Number(I.version),deleted:!0,persistedRecord:I}}throw new Error(`Unsupported mutation action: ${e.action}`)})),g=t.auditProjection({entity:String(e.entity),id:f.id},e.payload,c),h=Object.freeze({entity:e.entity,action:e.action,id:String(f.id),...g,recordedAt:new Date().toISOString(),actor:this.userContext.getResource("bootstrapActor"),category:this.userContext.getResource("bootstrapCategory"),changedFields:Object.freeze(Object.keys(e.payload||{}).sort()),version:f.version,mutationGovernance:o}),p=async()=>{this.auditEvents.push(h),this.auditSink&&await F(this.runtimeTelemetry,{family:"audit",name:`${e.entity}.audit`,attributes:{"teaql.entity.type":String(e.entity),"teaql.mutation.kind":String(e.action).toLowerCase(),"teaql.audit.changed_field_count":Object.keys(e.payload||{}).length}},async()=>this.auditSink(h))};if(t.graphSession)this.graphAuditActions.push(p);else try{await p()}catch(y){throw new De(y)}n.success();const m=Object.freeze({...u[0],statements:Object.freeze([...u])});return Ne(m,R(c,t.graphSession?.logBindings),[f.id]),{...f,metadata:m}}catch(o){throw n.failure(o),o}};return n.run?n.run(r):r()}async readPersistedRecord(e,t,n,r,o,s,a){const l=`SELECT ${Object.entries(t.columns).map(([S,w])=>`${this.driver.identifier(w.columnName)} AS ${this.driver.identifier(S)}`).join(", ")} FROM ${this.driver.identifier(t.table)} WHERE ${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`,u=[n];this.bindLogPolicies.set(u,[this.fieldLogPolicy(t,"id")]);const f=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.readback`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}}),g=Date.now();let h;const p={parameterizedSQL:o,parameters:s,parameterLogPolicies:this.bindLogPolicies.get(s),sqlOrigin:"generated"},m=r.tracePath?.find(S=>S.kind==="operation")?.name??"unknown",y=be([...He(m,r.auditReason,"verify persisted mutation result"),...(r.tracePath??[]).filter(S=>S.kind==="relation")],this.driver.databaseKind,"select"),d={...r,tracePath:ie(y.tracePath),comment:r.auditReason,purpose:"verify persisted mutation result"},b=S=>a.push(this.recordSQL("select",l,u,g,h?.rowCount,void 0,d,S,p,f.correlation?.()));let E;try{if(h=await(f.run?f.run(()=>e.query(l,u)):e.query(l,u)),f.success({attributes:{"teaql.result.cardinality":h.rowCount}}),h.rowCount!==1)throw new Error(`Persisted ${t.table}(${n}) could not be read back`);E=this.decodeRowForSchema(t,h.rows[0])}catch(S){h||f.failure(S);const w=h?"success":S instanceof Error&&(S.name==="AbortError"||S.name==="TimeoutError")?"cancelled":"failure";try{b(w)}finally{throw S}}return b("success"),E}decodeRowForSchema(e,t){const n={...t};for(const[r,o]of Object.entries(e.columns)){const s=n[r];s!=null&&(o.decode==="number"&&(n[r]=Number(s)),o.decode==="string"&&(n[r]=String(s)),o.decode==="date"&&s instanceof Date&&(n[r]=s.toISOString()),o.logicalType==="boolean"&&(n[r]=!!s))}return n}compileExpression(e,t,n){if(Array.isArray(e?.$and))return`(${e.$and.map(s=>this.compileExpression(s,t,n)).join(" AND ")})`;const r=Object.entries(e||{}).map(([o,s])=>{const a=t.columns[o];if(!a)throw new Error(`Unknown field ${o} for SQL query`);const c=this.driver.identifier(a.columnName),l=this.fieldLogPolicy(t,o);if(s?.$eq!==void 0){const u=s.$eq?.id??s.$eq;return u===null?`${c} IS NULL`:(this.bindValue(n,this.encode(u,a),l),`${c} = ${this.driver.placeholder(n.length)}`)}if(s?.$ne!==void 0){const u=s.$ne?.id??s.$ne;return u===null?`${c} IS NOT NULL`:(this.bindValue(n,this.encode(u,a),l),`${c} <> ${this.driver.placeholder(n.length)}`)}if(s?.$soundLike!==void 0)return this.bindValue(n,String(s.$soundLike),l),`SOUNDEX(${c}) = SOUNDEX(${this.driver.placeholder(n.length)})`;if(s?.$contains!==void 0)return this.bindValue(n,String(s.$contains),l),this.driver.contains(c,this.driver.placeholder(n.length));if(s?.$notContains!==void 0)return this.bindValue(n,String(s.$notContains),l),`NOT (${this.driver.contains(c,this.driver.placeholder(n.length))})`;for(const[u,f,g,h]of[["$startsWith","","%",!1],["$notStartsWith","","%",!0],["$endsWith","%","",!1],["$notEndsWith","%","",!0]])if(s?.[u]!==void 0){const p=String(s[u]);this.bindValue(n,`${f}${p}${g}`,l,p);const m=`${c} LIKE ${this.driver.placeholder(n.length)}`;return h?`NOT (${m})`:m}if(Array.isArray(s?.$in)){if(!s.$in.length)return"FALSE";const u=s.$in.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),l),this.driver.placeholder(n.length)));return`${c} IN (${u.join(", ")})`}if(Array.isArray(s?.$notIn)){if(!s.$notIn.length)return"TRUE";const u=s.$notIn.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),l),this.driver.placeholder(n.length)));return`${c} NOT IN (${u.join(", ")})`}for(const[u,f]of[["$inSubquery",!1],["$notInSubquery",!0]]){const g=s?.[u];if(g!==void 0){const h=g.query,p=this.schema(h?.entity),m=String(g.field),y=p.columns[m];if(!y)throw new Error(`Unknown subquery projection ${m} for ${h?.entity}`);const d=this.filters(h).map(S=>this.compileExpression(S,p,n));p.columns.version&&d.push(`${this.driver.identifier(p.columns.version.columnName)} > 0`),f&&d.push(`${this.driver.identifier(y.columnName)} IS NOT NULL`);const b=d.length?` WHERE ${d.join(" AND ")}`:"",E=`SELECT ${this.driver.identifier(y.columnName)} FROM ${this.driver.identifier(p.table)}${b}`;return`${c} ${f?"NOT IN":"IN"} (${E})`}}if(Array.isArray(s?.$between)&&s.$between.length===2){this.bindValue(n,this.encode(s.$between[0],a),l);const u=this.driver.placeholder(n.length);this.bindValue(n,this.encode(s.$between[1],a),l);const f=this.driver.placeholder(n.length);return`${c} BETWEEN ${u} AND ${f}`}if(s?.$isNull===!0)return`${c} IS NULL`;if(s?.$isNull===!1)return`${c} IS NOT NULL`;if(s?.$gte!==void 0)return this.bindValue(n,this.encode(s.$gte,a),l),`${c} >= ${this.driver.placeholder(n.length)}`;if(s?.$lte!==void 0)return this.bindValue(n,this.encode(s.$lte,a),l),`${c} <= ${this.driver.placeholder(n.length)}`;if(s?.$gt!==void 0)return this.bindValue(n,this.encode(s.$gt,a),l),`${c} > ${this.driver.placeholder(n.length)}`;if(s?.$lt!==void 0)return this.bindValue(n,this.encode(s.$lt,a),l),`${c} < ${this.driver.placeholder(n.length)}`;throw new Error(`Unsupported query predicate for ${o}: ${JSON.stringify(s)}`)});return r.length?`(${r.join(" AND ")})`:"TRUE"}filters(e){return Array.isArray(e._filters)&&e._filters.length?e._filters:e.filterCondition?[e.filterCondition]:[]}groupBy(e){return e._groupBy||e.groupByItems||[]}aggregates(e){return Array.isArray(e._aggregates)?e._aggregates:(e.aggregateItems||[]).map(t=>({func:t.function,field:t.field,retName:t.alias}))}orders(e){return Array.isArray(e._orderBy)?e._orderBy.map(t=>({field:t.f,direction:t.d})):(e.orderItems||[]).map(t=>({field:t.field,direction:t.direction}))}async compileQuery(e,t=!0,n=[]){new ae(e?.commentText??e?._comment,e?.purposeText??e?._purpose);const r=this.schema(e.entity),o=[],s=this.groupBy(e),a=s.map(w=>{if(!r.columns[w])throw new Error(`Unknown group field: ${w}`);return this.driver.identifier(r.columns[w].columnName)}),c=s.map(w=>`${this.driver.identifier(r.columns[w].columnName)} AS `+this.driver.identifier(w)),l=[],u=Array.isArray(e.selectItems)&&e.selectItems.length?[...new Set(["id","version",...e.selectItems])]:Object.keys(r.columns);if(!s.length&&!this.aggregates(e).length){for(const v of n)u.includes(v)||u.push(v);const w=[...(e.relations??[]).map(v=>v.name),...(e.relationAggregates??[]).map(v=>v.relationName)];for(const v of w){const I=r.relations?.[v];if(!I)throw new Error(`Missing relation ${e.entity}.${v}`);u.includes(I.localKey)||u.push(I.localKey)}}for(const w of u)if(!r.columns[w])throw new Error(`Unknown selected field: ${w}`);let f=u.map(w=>{const v=r.columns[w];return`${this.driver.identifier(v.columnName)} AS ${this.driver.identifier(w)}`}).join(", ");const g=this.aggregates(e);if(g.length){const w=g.map(v=>{if(!r.columns[v.field])throw new Error(`Unknown aggregate field: ${v.field}`);return l.push(v.retName),`${this.driver.aggregateFunction(v.func)}(${this.driver.identifier(r.columns[v.field].columnName)}) AS `+this.driver.identifier(v.retName)});f=[...c,...w].join(", ")}const h=e.__teaqlPartitionBy,p=this.orders(e),m=p.map(w=>{if(!r.columns[w.field])throw new Error(`Unknown order field: ${w.field}`);const v=String(w.direction).toLowerCase()==="desc"?"DESC":"ASC";return`${this.driver.identifier(r.columns[w.field].columnName)} ${v}`});if(h){const w=r.columns[h];if(!w)throw new Error(`Unknown partition field: ${h}`);const v=m.length?` ORDER BY ${m.join(", ")}`:"";f+=`, ROW_NUMBER() OVER (PARTITION BY ${this.driver.identifier(w.columnName)}${v}) AS `+this.driver.identifier("__teaql_partition_rank")}let y=`SELECT ${f} FROM ${this.driver.identifier(r.table)}`;const b=this.filters(e).map(w=>this.compileExpression(w,r,o));r.columns.version&&b.push(`${this.driver.identifier(r.columns.version.columnName)} > 0`),b.length&&(y+=` WHERE ${b.join(" AND ")}`),a.length&&(y+=` GROUP BY ${a.join(", ")}`);const E=e._limit!==void 0?Number(e._limit):Number(e.limitValue||0),S=e._offset!==void 0?Number(e._offset):Number(e.offsetValue||0);if(h){const w=this.driver.identifier("__teaql_partition_rank"),v=[];this.bindValue(o,S,"plain"),v.push(`${w} > ${this.driver.placeholder(o.length)}`),E>0&&(this.bindValue(o,S+E,"plain"),v.push(`${w} <= ${this.driver.placeholder(o.length)}`)),y=`SELECT * FROM (${y}) AS ${this.driver.identifier("__teaql_partitioned")} WHERE ${v.join(" AND ")} ORDER BY ${w}`}else p.length&&(y+=` ORDER BY ${m.join(", ")}`);return!h&&E>0&&(this.bindValue(o,E,"plain"),y+=` LIMIT ${this.driver.placeholder(o.length)}`),!h&&S>0&&(this.bindValue(o,S,"plain"),y+=` OFFSET ${this.driver.placeholder(o.length)}`),t&&this.sqlTrace.push(y),{sql:y,values:o,aggregateNames:l}}async executeQuery(e){const t=e instanceof L?e:new L(e);return!(e instanceof L)&&e?.[this.internalQueryToken]!==!0&&typeof e?.prepareForList=="function"&&e.prepareForList(),this.executeQueryWithIntent(t.query,this.derivedQueryBindings.get(e),this.derivedRelationAssembly.get(e))}async executeDerivedQuery(e,t,n,r){const o=new L(e,n).query;t&&this.derivedQueryBindings.set(o,t),r&&this.derivedRelationAssembly.set(o,r);try{return await this.executeQuery(o)}finally{this.derivedQueryBindings.delete(o),this.derivedRelationAssembly.delete(o)}}descendantBindings(e,t,n,r){if(!(!e.relations?.length&&!e.relationAggregates?.length))return R(this.queryLogBindings(t,n),r)}async queryTreeBindings(e,t,n,r){let o=R(this.queryLogBindings(t,n),r);const s=new L(e).intent,a=[e],c=new Set;for(;a.length;){const l=a.pop();if(!l||c.has(l))continue;if(c.add(l),l!==e){const f=await this.compileQuery(new L(l,s).query,!1);o=R(this.queryLogBindings(f.sql,f.values),o)}const u=Nt(l);u&&a.push(u);for(const f of[...l.relations??[],...l.relationAggregates??[]])f.query&&a.push(f.query);for(const f of l.facets??[]){if(!f.query)continue;const g=f.query.clone();g.aggregateItems=[],g.groupByItems=[],a.push(g)}}return o}async executeQueryWithIntent(e,t,n){await this.telemetryStartup;const r=N(this.runtimeTelemetry,{family:"query",name:`${String(e?.entity||"unknown")}.list`,attributes:{"teaql.entity.type":String(e?.entity||"unknown")}}),o=async()=>{try{const s=e?.[this.internalQueryToken]===!0;if(!s){if(typeof e?.prepareForList!="function")throw new Error("TeaQL list execution requires the formal runtime SelectQuery");e.prepareForList()}const a=s?{query:e,execution:void 0}:await this.prepareIdSetPage(e,t),c=s?a:await this.prepareContinuousPage(a.query);e=new L(e).withQuery(c.query).query;const{sql:l,values:u,aggregateNames:f}=await this.compileQuery(e,!0,n?[n.field]:[]);t=await this.queryTreeBindings(e,l,u,t);const h=(await this.executeLoggedSQL("select",l,u,this.queryLogIntent(e),()=>this.driver.query(l,u),t)).rows.map(m=>this.decodeRow(e.entity,m,f));if(a.execution?.pageIds){const m=new Map(a.execution.pageIds.map((y,d)=>[String(y),d]));h.sort((y,d)=>(m.get(String(y.id))??Number.MAX_SAFE_INTEGER)-(m.get(String(d.id))??Number.MAX_SAFE_INTEGER))}const p=this.descendantBindings(e,l,u,t);if(n)for(const m of h)n.keys.set(m,m[n.field]);if(await this.enhanceQueryRows(h,e,p),n&&Array.isArray(e.selectItems)&&e.selectItems.length&&!["id","version",...e.selectItems,...this.groupBy(e)].includes(n.field)){const m=this.schema(e.entity);if(![...(e.relations??[]).map(d=>d.name),...(e.relationAggregates??[]).map(d=>d.relationName)].some(d=>m.relations?.[d]?.localKey===n.field))for(const d of h)delete d[n.field]}return s||await this.registerContinuousPage(e,c.execution,h),r.success({attributes:{"teaql.result.cardinality":h.length}}),h}catch(s){throw r.failure(s),s}};return r.run?r.run(o):o()}async prepareIdSetPage(e,t){const n=e.localIdSetPaginationOptions?.(),r=e.localIdSetPaginationRuntime?.();if(!n||!r)return r?.observe("ID_SET_DISABLED"),{query:e};const o=this.queryLimit(e);if(!o||e.localContinuousPageOptions?.()||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return r.observe("ID_SET_FALLBACK_UNSUPPORTED_SHAPE"),{query:e};if((e.orderItems||[]).some(m=>m.expr!=null))return r.observe("ID_SET_FALLBACK_NON_DETERMINISTIC_ORDER"),{query:e};this.orders(e).some(m=>m.field==="id")||(e=e.clone().order(q.asc("id")));const s=e.clone();s.offsetValue=0,s.limitValue=0,s.selectItems=[],s.relations=[],s.commentText=void 0,s.purposeText=void 0,s.clearIdSetPaginationRuntime(),s.clearContinuousPageRuntime();const a=`${n.namespace}|${r.scope}|${JSON.stringify(s)}`;let c=2166136261;for(let m=0;m>>0).toString(16)}`;let u,f=!1;try{u=r.get(l)}catch{return r.observe("ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(u)f=!0,r.observe("ID_SET_HIT",u.ids.length);else{let m;try{m=await r.build(l,async()=>{const y=r.get(l);if(y)return y;const d=e.clone();d.selectItems=["id"],d.relations=[],d.relationAggregates=[],d.facets=[],d.offsetValue=0,d.limitValue=n.maxIds+1,d.clearIdSetPaginationRuntime(),d.clearContinuousPageRuntime(),d[this.internalQueryToken]=!0;const b=new L(e).deriveHelper(d,`collect ${e.entity} IDs for pagination`),E=await this.compileQuery(e,!1),S=await this.queryTreeBindings(e,E.sql,E.values,t),w=await this.executeDerivedQuery(b.query,S,b.intent);if(w.length>n.maxIds)return;let v;try{v=BigUint64Array.from(w.map(O=>BigInt(O.id)))}catch{throw new Error("ID_SET_UNSUPPORTED_ID")}const I={ids:v,expiresAt:Date.now()+n.ttlSeconds*1e3};return r.put(l,I),I})}catch(y){return r.observe(y instanceof Error&&y.message==="ID_SET_UNSUPPORTED_ID"?"ID_SET_FALLBACK_UNSUPPORTED_SHAPE":"ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(u=m.value,!u)return r.observe("ID_SET_FALLBACK_LIMIT_EXCEEDED",n.maxIds+1),{query:e};f=!m.built,r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",u.ids.length)}const g=Number(e.offsetValue||e._offset||0),h=Array.from(u.ids.slice(g,g+o)),p=e.clone();return p.offsetValue=0,p.limitValue=Math.max(h.length,1),p.filterCondition=p.filterCondition?{$and:[p.filterCondition,{id:{$in:h}}]}:{id:{$in:h}},p.clearIdSetPaginationRuntime(),r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",u.ids.length),{query:p,execution:{pageIds:h,totalCount:u.ids.length}}}async executeFacetMembership(e,t,n=[]){const r=await this.executeFacetAggregates(e,t,[{function:"Count",field:"id",alias:"__teaql_facet_count"}]);return new Map([...r].map(([o,s])=>[o,Number(s.__teaql_facet_count??0)]))}async executeFacetAggregates(e,t,n){const r=new L(e);e=r.query;const o=r.withQuery(e.clone()).query;Q(e,o),o.facets=[],o.relations=[],o.relationAggregates=[],o.orderItems=[],o.offsetValue=0,o.limitValue=0,o.selectItems=[],o.groupByItems=[t],o.aggregateItems=n.map(a=>({...a})),o[this.internalQueryToken]=!0;const s=await this.executeQuery(o);return new Map(s.flatMap(a=>{const c=a[t];if(c==null)return[];const l={};for(const u of n)l[u.alias]=a[u.alias];return[[String(c),l]]}))}async executeCount(e,t,n){const r=e instanceof L?e:new L(e);if(e=r.query,typeof e?.forExactCount!="function")throw new Error("TeaQL exact count requires the formal runtime SelectQuery");const o=t??"__teaql_total",s=r.deriveOperation(e.forExactCount(o),n??{kind:"named-count",...t!==void 0?{alias:t}:{}}),c=(await this.executeQuery(s.query))[0]?.[o];if(typeof c!="number"||!Number.isFinite(c))throw new Error(`TeaQL provider did not return exact count alias ${o}`);return c}async prepareContinuousPage(e){const t=e.localContinuousPageOptions?.(),n=e.localContinuousPageRuntime?.();if(!t||!n)return n?.observe("DISABLED"),{query:e};const r=this.orders(e),o=this.queryLimit(e);if(!o||r.length!==1||r[0].field!=="id"||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return n.observe("OFFSET_FALLBACK:UNSUPPORTED_QUERY_SHAPE"),{query:e};const s=Object.assign(Object.create(Object.getPrototypeOf(e)),e);s.orderItems=[...e.orderItems||[]],s.relations=[...e.relations||[]],Object.defineProperty(s,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:t}),Object.defineProperty(s,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:n});const a=Number(e.offsetValue||e._offset||0),c={...JSON.parse(JSON.stringify(s)),offsetValue:0,_offset:0,commentText:void 0,purposeText:void 0},l=`${t.namespace}|${n.owner}|${JSON.stringify(c)}`;let u=2166136261;for(let m=0;m>>0).toString(16)}`,g={queryKey:f,offset:a,limit:o,direction:String(r[0].direction).toLowerCase(),ttlSeconds:t.ttlSeconds,runtime:n,optimized:!1};if(a===0)return n.observe("OFFSET_FALLBACK:FIRST_PAGE"),{query:s,execution:g};let h;try{h=await F(this.runtimeTelemetry,{family:"cache",name:"continuous_page.get",attributes:{"teaql.cache.operation":"get"}},()=>n.get(f,a))}catch{return n.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE"),{query:s,execution:g}}if(!h)return n.observe("OFFSET_FALLBACK:CACHE_MISS"),{query:s,execution:g};const p={id:{[g.direction==="desc"?"$lt":"$gt"]:h.boundary}};return s.filterCondition=s.filterCondition?{$and:[s.filterCondition,p]}:p,s.offsetValue=0,s._offset!==void 0&&(s._offset=0),g.optimized=!0,g.cursorId=h.cursorId,n.observe("CURSOR_SEEK",h.cursorId),{query:s,execution:g}}async registerContinuousPage(e,t,n){if(!(!t||n.length!==t.limit||!n.length||n[n.length-1].id===void 0)){try{await F(this.runtimeTelemetry,{family:"cache",name:"continuous_page.put",attributes:{"teaql.cache.operation":"put"}},()=>t.runtime.put(t.queryKey,t.offset+n.length,{cursorId:`cpg_${Date.now().toString(16)}_${Math.random().toString(16).slice(2)}`,boundary:n[n.length-1].id,expiresAt:Date.now()+t.ttlSeconds*1e3}))}catch{t.runtime.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE");return}t.optimized&&t.runtime.observe("CURSOR_SEEK",t.cursorId)}}executeForStream(e,t=1e3){try{const n=e instanceof L?new L(e.query,e.intent):new L(e);return this.executeCapturedStream(n.query,t)}catch(n){return(async function*(){throw n})()}}async*executeCapturedStream(e,t){if(await this.telemetryStartup,!Number.isInteger(t)||t<=0)throw new Error("stream chunk size must be a positive integer");if(Array.isArray(e.facets)&&e.facets.length>0)throw new Error("QRY-F01_STREAM_UNSUPPORTED: execute facets with executeForList");const{sql:n,values:r,aggregateNames:o}=await this.compileQuery(e),s=await this.queryTreeBindings(e,n,r),a=N(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.stream`,attributes:{"teaql.entity.type":String(e.entity)}});let c;const l=async()=>{c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.stream`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}})};await(a.run?a.run(l):l());const u=c.correlation?.(),f=this.driver.stream(n,r)[Symbol.asyncIterator](),g=Date.now();let h="cancelled",p=0,m=[];const y=this.descendantBindings(e,n,r,s);try{for(;;){const d=await(c.run?c.run(()=>f.next()):f.next());if(d.done)break;m.push(this.decodeRow(e.entity,d.value,o)),m.length===t&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m,m=[])}m.length&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m),h="success"}catch(d){throw h="failure",c.failure(d),a.failure(d),d}finally{try{await f.return?.()}catch(d){if(h!=="failure")throw h="failure",c.failure(d),a.failure(d),d}finally{if(h==="failure")try{this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,u)}catch{}else this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,u),c.success({attributes:{"teaql.result.cardinality":p}}),a.success({attributes:{"teaql.result.cardinality":p}})}}}async enhanceQueryRows(e,t,n){if(!e.length)return;const r=[...(t.relations??[]).map(a=>a.name),...(t.relationAggregates??[]).map(a=>a.relationName)];if(!r.length)return;const o=this.schema(t.entity),s=new Map;for(const a of r){const c=o.relations?.[a];if(!c)throw new Error(`Missing relation ${t.entity}.${a}`);s.has(c.localKey)||s.set(c.localKey,e.map(l=>l[c.localKey]))}await this.enhanceRelationAggregates(e,t,s,n),await this.enhanceRelations(e,t,s,n)}async enhanceRelations(e,t,n,r){if(!e.length||!Array.isArray(t.relations)||!t.relations.length)return;const o=this.schema(t.entity),s=new L(t).intent;for(const a of t.relations){const c=o.relations?.[a.name];if(!c)throw new Error(`Missing relation ${t.entity}.${a.name}`);const l=n.get(c.localKey),u=l.filter(S=>S!=null),f=a.query?this.queryLimit(a.query):void 0,g=a.query?.localTopNProbeParentThreshold?.(),h=c.many&&f!==void 0,p=Array.isArray(a.query?.selectItems)?a.query.selectItems:[],m=p.length>0&&!p.includes(c.foreignKey),y=this.driver.topNRelationPlanPolicy==="alwaysProbe",d=h&&(g===void 0?y:g>0&&u.length<=g),b=d?"bounded_probes":"window",E=N(this.runtimeTelemetry,{family:"relation_load",name:`${t.entity}.${String(a.name)}`,attributes:{"teaql.entity.type":String(t.entity),"teaql.relation.name":String(a.name),"teaql.relation.parent_count":u.length,"teaql.relation.per_parent_limit":f??0,"teaql.relation.configured_probe_threshold":g??"provider-default","teaql.relation.selected_plan":b,"teaql.relation.probe_count":d?u.length:0}});try{if(!u.length&&!(c.many&&a.query?.facets?.length)){for(const O of e)O[a.name]=c.many?[]:null;E.success({attributes:{"teaql.result.cardinality":0}});continue}const S={...a.query||{},entity:c.targetEntity,selectItems:m?[...p,c.foreignKey]:p,_filters:[...this.filters(a.query||{})],relations:[...a.query?.relations||[]],orderItems:[...a.query?.orderItems||[]],__teaqlPartitionBy:h&&!d?c.foreignKey:void 0};if(h){const O=this.groupBy(S),A=O.length||this.aggregates(S).length?O:["id"];for(const $ of A)S.orderItems.some(T=>T.field===$)||S.orderItems.push(q.asc($))}typeof S.clearContinuousPageRuntime=="function"&&S.clearContinuousPageRuntime(),S[this.internalQueryToken]=!0;const w=[],v={field:c.foreignKey,keys:new WeakMap};if(d)for(const O of u){const A={...S,_filters:[...S._filters,{[c.foreignKey]:{$eq:O}}],__teaqlPartitionBy:void 0};w.push(...await this.executeDerivedQuery(new L(t).derive(A,a.name,a.operation).query,r,s,v))}else S._filters.push({[c.foreignKey]:{$in:u}}),w.push(...await this.executeDerivedQuery(new L(t).derive(S,a.name,a.operation).query,r,s,v));for(const O of w)delete O.__teaql_partition_rank;const I=new Map;for(const O of w){if(!v.keys.has(O))throw new Error("Relation assembly lost its captured row identity");const A=v.keys.get(O),$=I.get(A)||[];$.push(O),I.set(A,$)}if(m)for(const O of w)delete O[c.foreignKey];for(const[O,A]of e.entries()){const $=I.get(l[O])||[];if(c.many&&a.query?.facets?.length){const T=a.query.clone();T.entity=c.targetEntity;const he=l[O],Ae={[c.foreignKey]:he==null?{$in:[]}:{$eq:he}};T.filterCondition=T.filterCondition?{$and:[T.filterCondition,Ae]}:Ae,Q(t,T);const ct=new L(t).derive(T,a.name,a.operation).query;A[a.name]=new J($,{facets:await ot(this,lt=>lt,ct,T.facets)})}else{const T=l[O];A[a.name]=c.many?$:$[0]??(T==null?null:{[c.foreignKey]:T})}}E.success({attributes:{"teaql.result.cardinality":w.length}})}catch(S){throw E.failure(S),S}}}async enhanceRelationAggregates(e,t,n,r){const o=t.relationAggregates;if(!e.length||!Array.isArray(o)||!o.length)return;const s=this.schema(t.entity),a=new L(t).intent;for(const c of o){const l=s.relations?.[c.relationName];if(!l)throw new Error(`Missing relation ${t.entity}.${c.relationName}`);const u=n.get(l.localKey),f=u.filter(y=>y!=null);if(!f.length){for(const y of e)y[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{};continue}const g=c.query.clone();g.entity=l.targetEntity,g.selectItems=[],g.properties=[],g.orderItems=[],g.limitValue=0,g.offsetValue=0,g.relations=[],g.relationAggregates=[],g.aggregateItems.length||g.aggregate("Count","id",c.alias),g.groupByItems.includes(l.foreignKey)||g.groupBy(l.foreignKey);const h={[l.foreignKey]:{$in:f}};g.filterCondition=g.filterCondition?{$and:[g.filterCondition,h]}:h,g[this.internalQueryToken]=!0;const p=await this.executeDerivedQuery(new L(t).deriveAggregate(g,c.relationName,c.operation??{kind:"relation-count",relation:c.relationName,alias:c.alias}).query,r,a),m=new Map;for(const y of p)m.set(y[l.foreignKey],y);for(const[y,d]of e.entries()){const b=m.get(u[y]);b?c.singleResult?d[c.alias]=b[g.aggregateItems[0].alias]??null:d[c.alias]=Object.fromEntries(Object.entries(b).filter(([E])=>E!==l.foreignKey)):d[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{}}}}emptyAggregateValue(e){const t=e.aggregateItems[0];return!t||String(t.function).toLowerCase()==="count"?0:null}queryLimit(e){if(e._limit!==void 0)return Number(e._limit);if(e.limitValue!==void 0&&Number(e.limitValue)>0)return Number(e.limitValue)}async close(){try{await this.driver.close()}finally{await this.telemetryStartup,await this.standardTelemetryHandle?.release(),this.standardTelemetryHandle=void 0}}}function ci(i){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))throw new Error(`Unsafe SQL identifier: ${i}`);return i}function li(i){const t={count:"COUNT",sum:"SUM",avg:"AVG",min:"MIN",max:"MAX"}[String(i).toLowerCase()];if(!t)throw new Error(`Unsupported aggregate: ${i}`);return t}class ui{constructor(e){this.worker=e,this.nextRequestId=1,this.pending=new Map,this.closed=!1,this.onMessage=t=>{const n=t.data;if(!n||n.type!=="teaql-browser-sqlite-response")return;const r=this.pending.get(n.requestId);if(r)if(this.pending.delete(n.requestId),n.error){const o=new Error(n.error.message);o.name=n.error.name,n.error.code&&(o.code=n.error.code),r.reject(o)}else r.resolve(n.result)},this.onError=t=>{const n=new Error(t.message||"Browser SQLite worker failed");n.name="BrowserSQLiteWorkerError";for(const r of this.pending.values())r.reject(n);this.pending.clear()},e.addEventListener("message",this.onMessage),e.addEventListener("error",this.onError)}request(e,t){if(this.closed)return Promise.reject(new Error("Browser SQLite worker is closed"));const n=this.nextRequestId++;return new Promise((r,o)=>{this.pending.set(n,{resolve:s=>r(s),reject:o}),this.worker.postMessage({type:"teaql-browser-sqlite-request",requestId:n,operation:e,payload:t})})}async close(e){if(!this.closed)try{await this.request("close")}finally{this.closed=!0,this.worker.removeEventListener("message",this.onMessage),this.worker.removeEventListener("error",this.onError),e&&this.worker.terminate?.();const t=new Error("Browser SQLite worker is closed");for(const n of this.pending.values())n.reject(t);this.pending.clear()}}}class hi{constructor(e){this.transport=e}query(e,t=[]){return this.transport.request("query",{sql:e,values:t})}}class Te{constructor(e,t){this.transport=e,this.options=t,this.databaseKind="sqlite",this.accessTail=Promise.resolve()}static async open(e,t={}){const n={storage:t.storage??"memory",databaseName:fi(t.databaseName??"teaql-browser.sqlite3"),terminateWorkerOnClose:t.terminateWorkerOnClose??!0},r=new ui(e);return await r.request("open",n),new Te(r,n)}identifier(e){return`"${ci(e)}"`}placeholder(e){return"?"}contains(e,t){return`CAST(${e} AS TEXT) LIKE '%' || ${t} || '%'`}aggregateFunction(e){return li(e)}encode(e,t){return e==null?e:t?.logicalType==="json"&&typeof e!="string"?JSON.stringify(e):t?.logicalType==="boolean"?e?1:0:e instanceof Date?e.toISOString():e}async exclusive(e){const t=this.accessTail;let n;this.accessTail=new Promise(r=>{n=r}),await t;try{return await e()}finally{n()}}query(e,t=[]){return this.exclusive(()=>this.transport.request("query",{sql:e,values:t}))}async*stream(e,t=[]){const n=await this.query(e,t);for(const r of n.rows)yield r}transaction(e){return this.exclusive(async()=>{const t=new hi(this.transport);await t.query("BEGIN IMMEDIATE");try{const n=await e(t);return await t.query("COMMIT"),n}catch(n){try{await t.query("ROLLBACK")}catch{}throw n}})}async ensureSchema(e){for(const t of Object.values(e)){const n=this.identifier(t.table);await this.query(`CREATE TABLE IF NOT EXISTS ${n} ("id" INTEGER PRIMARY KEY, "version" INTEGER NOT NULL)`);const r=await this.query(`PRAGMA table_info(${n})`),o=new Set(r.rows.map(s=>String(s.name)));for(const[s,a]of Object.entries(t.columns))s==="id"||s==="version"||o.has(a.columnName)||await this.query(`ALTER TABLE ${n} ADD COLUMN ${this.identifier(a.columnName)} ${di(a.logicalType)}${a.nullable===!1?" NOT NULL":""}`)}for(const t of ni(e))await this.query(`CREATE INDEX IF NOT EXISTS ${this.identifier(t.name)} ON ${this.identifier(t.table)} (${this.identifier(t.foreignColumn)}, ${this.identifier(t.idColumn)} DESC)`);await this.query("CREATE TABLE IF NOT EXISTS teaql_id_space (type_name TEXT PRIMARY KEY, current_level INTEGER NOT NULL)")}async nextId(e,t){for(let n=1;n<=100;n+=1){const r=await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t]);if(!r.rowCount){try{if((await e.query("INSERT INTO teaql_id_space(type_name, current_level) VALUES (?, 1)",[t])).rowCount===1)return"1"}catch(c){if(!(await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t])).rowCount)throw c}continue}const o=Number(r.rows[0].id),s=o+1,a=await e.query("UPDATE teaql_id_space SET current_level = ? WHERE type_name = ? AND current_level = ?",[s,t,o]);if(a.rowCount===1)return String(s);if(a.rowCount!==0)throw new Error(`ID space update for ${t} changed ${a.rowCount} rows`)}throw new Error(`Unable to allocate ID for ${t} after 100 optimistic-lock attempts`)}ensureIdFloor(e,t,n){return ri(e,r=>this.placeholder(r),t,n)}reset(){return this.exclusive(()=>this.transport.request("reset",this.options))}close(){return this.exclusive(()=>this.transport.close(this.options.terminateWorkerOnClose))}}class at extends ai{constructor(e,t){super(e,t),this.browserDriver=e}static async open(e,t,n={}){return new at(await Te.open(e,n),t)}get storage(){return this.browserDriver.options.storage}async reset(e){await this.browserDriver.reset(),this.invalidateSchemaState(),await e.ensureSchema()}}function di(i){return{boolean:"INTEGER",double:"REAL",decimal:"NUMERIC",date:"TEXT",datetime:"TEXT",json:"TEXT",integer:"INTEGER",text:"TEXT"}[i]}function fi(i){const e=i.trim();if(!e||e.includes("/")||e.includes("\\")||e==="."||e==="..")throw new TypeError("Browser SQLite databaseName must be a simple file name");return e}function vi(i,e,t,n){const r=o=>{if(o.includes("."))throw new Error("Dynamic search requires a trusted relation binding");const s=t[i.entity]?.queryFields;if(!s||!Object.prototype.hasOwnProperty.call(s,o))throw new Error("Missing generated scalar search binding");return s[o]};return gi(i,e,t,{filter:(o,s)=>{const[a,c]=Object.entries(s)[0];if(c===null&&a!=="$eq"&&a!=="$ne")throw new Error("Null supports only equality predicates");return{[r(o)]:s}},order:(o,s)=>s==="asc"?q.asc(r(o)):q.desc(r(o))},n)}function gi(i,e,t,n,r=o=>console.warn({...o,fieldPath:""})){const o=yi(e,i.entity,t,()=>{}),s=Object.entries(o.search.filter??{}).map(([f,g])=>n.filter(f,g)),a=(o.search.orderBy??[]).map(f=>n.order(f.field,f.direction));if(s.some(f=>!V(f)))throw new Error("Invalid trusted search filter binding");if(a.some(f=>!(f instanceof q)))throw new Error("Invalid trusted search order binding");const c=i.clone(),l=i._filters??[],u=[...l,...i.filterCondition?[i.filterCondition]:[]];return(s.length||l.length)&&c.filter({$and:[...u,...s]}),c.orderItems.push(...a),o.warnings.forEach(f=>r({...f})),{query:c,warnings:o.warnings}}const te=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),V=i=>typeof i=="object"&&i!==null&&!Array.isArray(i),pi=new Set(["__proto__","prototype","constructor"]),mi=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$notIn","$contains"]);function yi(i,e,t,n=o=>console.warn({...o,fieldPath:""}),r=100){if(!Number.isSafeInteger(r)||r<1)throw new Error("Invalid search limit");if(!te(t,e))throw new Error("Unknown search entity");let o;try{o=typeof i=="string"?JSON.parse(i):i}catch{throw new Error("Dynamic search requires valid JSON")}if(!V(o)||Object.keys(o).some(h=>!["filter","orderBy"].includes(h)))throw new Error("Unsupported dynamic search input or control");if(o.filter!==void 0&&!V(o.filter))throw new Error("Invalid search filter");if(o.orderBy!==void 0&&!Array.isArray(o.orderBy))throw new Error("Invalid search ordering");const s=Object.entries(o.filter??{}),a=o.orderBy??[];if(s.length+a.length>r)throw new Error("Dynamic search exceeds clause limit");const c=[],l={filter:Object.create(null),orderBy:[]};function u(h){const p=h.split(".");if(p.length>16||p.some(d=>!d||d.startsWith("$")||pi.has(d)))throw new Error("Invalid dynamic search field path");let m=t[e];for(const d of p.slice(0,-1)){if(!te(m.relations,d))return;const b=m.relations[d];if(!te(t,b))throw new Error("Invalid trusted search relation metadata");m=t[b]}const y=p[p.length-1];return te(m.fields,y)?m.fields[y]:void 0}function f(h,p){c.push({code:"DYNAMIC_SEARCH_UNKNOWN_FIELD",entity:e,clause:p,fieldPath:h})}function g(h,p){if(h===null)return;if(!(p==="date"?typeof h=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(h)&&!h.startsWith("0000-")&&Number.isFinite(Date.parse(h+"T00:00:00Z"))&&new Date(h+"T00:00:00Z").toISOString().slice(0,10)===h:p==="decimal"?typeof h=="string"&&/^[+-]?\d+(?:\.\d+)?$/.test(h)||typeof h=="number"&&Number.isFinite(h):p==="integer"||p==="timestamp"?typeof h=="number"&&Number.isSafeInteger(h):p==="number"?typeof h=="number"&&Number.isFinite(h):typeof h===p))throw new Error("Invalid value for known search field")}for(const[h,p]of s){const m=V(p)?Object.entries(p):[["$eq",p]];if(m.length!==1||!mi.has(m[0][0]))throw new Error("Unsupported or malformed dynamic search operator");const[y,d]=m[0];if((y==="$in"||y==="$notIn")&&(!Array.isArray(d)||d.length>1e3))throw new Error("Invalid or oversized search value list");const b=u(h);if(b===void 0){f(h,"FILTER");continue}if(b==="unsupported")throw new Error("Known search field has no supported scalar binding");if(y==="$contains"&&b!=="string")throw new Error("String operator requires a string field");if(Array.isArray(d)){if(y!=="$in"&&y!=="$notIn")throw new Error("Unexpected search value list");d.forEach(E=>g(E,b))}else g(d,b);l.filter[h]={[y]:Array.isArray(d)?[...d]:d}}for(const h of a){if(!V(h)||Object.keys(h).some(m=>!["field","direction"].includes(m))||typeof h.field!="string"||!["asc","desc"].includes(h.direction))throw new Error("Invalid dynamic search ordering");const p=u(h.field);if(p===void 0){f(h.field,"ORDER_BY");continue}if(p==="unsupported")throw new Error("Known search field has no supported scalar binding");l.orderBy.push({field:h.field,direction:h.direction})}return c.forEach(h=>n({...h})),{search:l,warnings:c}}export{at as B,dt as C,wi as D,Oe as L,U as M,q as O,ae as Q,rt as R,Yt as S,Ht as U,J as a,Si as b,bi as c,vi as d,ot as e,_ as f,gi as m}; diff --git a/assets/main-Cg0XY2hs.js b/assets/main-Cg0XY2hs.js new file mode 100644 index 0000000000000000000000000000000000000000..8d0e51880261e77283ffad873144639d1587aed0 --- /dev/null +++ b/assets/main-Cg0XY2hs.js @@ -0,0 +1,104 @@ +import{S as x,m as Te,a as qe,e as xe,O as $,B as Qe,b as Re,R as $e,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-Ch_QcWVU.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ie={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(` +`,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const i=f[String(a)];return i===void 0?a:Number(i)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class P{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(` +`)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this.pageTotalAlias)));const i=await n.executeQuery(e.prepareQuery(a)),c=new qe(i,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,l=>e.prepareQuery(l),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?$.asc(e):$.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends P{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends P{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends P{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends P{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends P{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends P{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends P{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?$.asc(s):$.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),b=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),R=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),V=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let d=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[d]??t}function O(t){return d==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let w="tree",v,fe=0,ee;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ae==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset) + .limit(pageSize) + .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:te(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() + .selectPlatformWith(Q.platforms().selectName()) + .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .orderByOrderDateDescending() + .orderByIdDescending() + .limit(8) + .comment('what: list recent commerce orders') + .purpose('why: provide the default order overview') + .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() + .withOrderNumberIs('TQL-2026-1003') + .selectPlatformWith(Q.platforms()) + .selectCustomerWith(Q.customers()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectItemListWith(Q.orderItems().orderByIdAscending()) + .selectPaymentListWith(Q.payments().orderByIdAscending()) + .selectShipmentListWith(Q.shipments().orderByIdAscending()) + .limit(1) + .comment('what: load one complete order graph') + .purpose('why: inspect items, payment and fulfillment together') + .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() + .selectPlatformWith(Q.platforms().selectName()) + .countOrderListAs('orderCount') + .orderByNameAscending() + .comment('what: list customers with related order counts') + .purpose('why: compare customer activity at a glance') + .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() + .groupByCurrency().groupByStatus() + .countAs('orderCount') + .sumTotalAmountAs('grossAmount') + .averageTotalAmountAs('averageOrderValue') + .comment('what: aggregate orders by currency and status') + .purpose('why: show the current order funnel') + .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() + .groupByProductName() + .sumQuantityAs('units') + .sumLineAmountAs('revenue') + .comment('what: aggregate sold units and line revenue') + .purpose('why: identify the strongest products in the demo data') + .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() + .groupByCurrency().groupByProvider().groupByStatus() + .countAs('paymentCount').sumAmountAs('paymentAmount') + .orderByCurrencyAscending().orderByProviderAscending() + .comment('what: reconcile payment totals by provider') + .purpose('why: compare captured, pending and refunded money') + .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、范围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() + .withStatusIsPendingPayment() + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectCustomerWith(Q.customers().selectName()) + .selectPaymentListWith(Q.payments()) + .comment('what: find orders awaiting payment') + .purpose('why: support payment follow-up') + .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() + .withPlatformIdIs('1') + .withTotalAmountGreaterThanOrEqualTo(500) + .selectCustomerWith(Q.customers().selectName().selectCity()) + .orderByTotalAmountDescending() + .comment('what: find high-value domestic orders') + .purpose('why: prioritize valuable fulfillment work') + .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() + .withStatusIn('READY', 'IN_TRANSIT') + .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) + .orderByStatusAscending().orderByIdAscending() + .comment('what: find shipments that are not delivered') + .purpose('why: monitor active fulfillment') + .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { + "filter": { + "currency": "CNY", + "totalAmount": { "$gte": 250 }, + "status": { "$in": ["PAID", "SHIPPED"] } + }, + "orderBy": [{ "field": "totalAmount", "direction": "desc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>G(t,{filter:{currency:"CNY",totalAmount:{$gte:250},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { + "filter": { "orderDate": { "$gte": "2026-09-15" } }, + "orderBy": [{ "field": "orderDate", "direction": "asc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>G(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { + "filter": { + "status": "DELIVERED", + "internalNote": { "$contains": "not queryable" } + } +}; +const request = Q.customerOrders().filterByJson(input); +const data = await request + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx); +const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ie},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new Re().enableSelect();r.install(new $e(ie,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),o=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:o.payload}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){F.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const i=document.createElement("a");i.href=`#${a.id}`,i.dataset.queryId=a.id,i.textContent=O(a.title),i.addEventListener("click",c=>{c.preventDefault(),W=a.id,history.replaceState(null,"",`#${a.id}`),H(),E&&D(a,E).catch(N)}),o.append(i)}e.append(r,o),F.append(e)}H()}function H(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function D(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),b.classList.add("loading"),b.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),b.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),R.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",J.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),v={data:s,query:t,active:e},w=t.view==="dashboard"||Z(s)?"table":"tree",z();const o=Math.max(1,Math.round(performance.now()-r));fe=o,ee=n;const a=e.evidence.snapshot();we(a,n),Le(s,t,o)}finally{b.classList.remove("loading"),b.removeAttribute("aria-busy")}}function we(t,e=ee){ue.replaceChildren(),et.textContent=d==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(m=>m.kind==="relation"||m.kind==="request"||m.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const i=document.createElement("td");i.textContent=`${v?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const m=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${m?.detail||m?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(m=>m.detail||m.name).join(" → ");const l=document.createElement("td");l.className="evidence-sql";const h=r.parameters.length?r.parameters.map(m=>String(m)).join(", "):"none";l.textContent=`${r.parameterizedSQL} · bindings: ${h}`,s.append(a,i,c,l),ue.append(s)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!v)return;const{data:t,query:e,active:r}=v,n=e.view==="dashboard"||Z(t);if(n||(w="tree"),Q.disabled=!n,Q.classList.toggle("active",w==="table"),V.classList.toggle("active",w==="tree"),Q.setAttribute("aria-pressed",String(w==="table")),V.setAttribute("aria-pressed",String(w==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",w!=="tree"),w==="table"&&e.view==="dashboard"){R.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(w==="table"&&Z(t)){R.textContent=d==="en"?"Result table":"结果表格",ut(t);return}R.textContent=d==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const i=document.createElement("p");i.className="result-table-empty",i.textContent=d==="en"?"The query returned no records.":"查询没有返回记录。",e.append(i),b.replaceChildren(e);return}const r=[...new Set(t.flatMap(i=>Object.keys(i)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const i of r){const c=document.createElement("th");c.scope="col",c.textContent=i,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const i of t){const c=document.createElement("tr");for(const l of r){const h=document.createElement("td");h.textContent=lt(i[l]),c.append(h)}a.append(c)}n.append(s,a),e.append(n),b.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return d==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return be(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?d==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=d==="en"?"Order Management Center":"订单管理中心";const i=document.createElement("p");i.textContent=d==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,i);const c=document.createElement("form");c.className="order-search";const l=document.createElement("input");l.type="search",l.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",l.value=t.search,l.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),h.title=d==="en"?"Search":"查询";const m=document.createElement("span");m.className="search-icon",m.setAttribute("aria-hidden","true"),h.append(m),c.append(l,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=l.value.trim(),A.page=0,D(r,e).catch(N)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(d==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,D(r,e).catch(N)}));for(const p of t.statusFacets)S.append(me(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,D(r,e).catch(N)},`${d==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const ve=d==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of ve){const q=document.createElement("span");q.textContent=p,M.append(q)}if(g.append(M),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const _=document.createElement("div");_.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=d==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const T=document.createElement("div");T.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));T.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p=ae-1,e,r)),_.append(ne,T),n.append(s,S,g,_),b.replaceChildren(n)}function me(t,e,r,n,s,o,a){const i=document.createElement("button");i.type="button",i.className=`metric-card metric-${r}`,n&&i.style.setProperty("--metric-color",n),i.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const l=document.createElement("strong");if(l.textContent=String(e),i.append(c,l),a){const h=document.createElement("small");h.textContent=a,i.append(h)}return i.addEventListener("click",o),i}function pt(t){return new Intl.NumberFormat(d==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(m=>{const S=document.createElement("span");S.className="order-primary",S.textContent=m,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=te(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=be(i)||String(r.name??i);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const l=document.createElement("span");l.className="product-preview",n.forEach((m,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(m.productName??"?").slice(0,1),g.title=`${String(m.productName??"")} × ${String(m.quantity??1)}`,l.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const m=document.createElement("small");m.textContent=`+${h}`,l.append(m)}return e.append(l),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,D(s,n).catch(N)}),o}function be(t){return(d==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){b.replaceChildren(Ne(t,"result",0))}function Ne(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),i=document.createElement("details");i.className="tree-branch",i.open=r===0;const c=document.createElement("summary"),l=document.createElement("span");l.className="tree-key",l.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,a.length),c.append(l,h),i.append(c);const m=document.createElement("div");m.className="tree-children";for(const[S,g]of a)m.append(Ne(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(m),i}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return d==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):d==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Le(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=d==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;k.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function De(){document.documentElement.lang=d==="en"?"en":"zh-CN",document.title=d==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=d==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===d;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",d==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",d==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",d==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",d==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",d==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",d==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",d==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",d==="en"?"Result tree actions":"结果树操作"),dt(),v){const{data:e,query:r,active:n}=v;ye.textContent=O(r.title),he.textContent=O(r.description),z(),we(n.evidence.snapshot(),ee),Le(e,r,fe),Oe(B.checked?"opfs":"memory")}else k.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return le.find(t=>t.id===W)??le[0]}async function Pe(t){k.textContent=d==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await D(re(),r),Oe(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Pe(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await D(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{b.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(w="table",z())});V.addEventListener("click",()=>{w="tree",z()});tt.addEventListener("click",()=>{b.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{d=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",d),De()})});function N(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}De();W=re().id;H();Pe(Ae).catch(N); diff --git a/assets/main-gHLGx1pH.js b/assets/main-gHLGx1pH.js deleted file mode 100644 index 5de35f55d321681eb889d38d979c8068d7a7b040..0000000000000000000000000000000000000000 --- a/assets/main-gHLGx1pH.js +++ /dev/null @@ -1,102 +0,0 @@ -import{S as T,m as Te,a as ie,e as de,O as R,B as Qe,b as $e,R as Re,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-BBmdgl4H.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),_e=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ce={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},he=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(` -`,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),Me={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,o=n.status,s=d=>{const a=f[String(d)];return a===void 0?d:Number(a)};return o&&typeof o=="object"&&!Array.isArray(o)&&"$in"in o?n.status={$in:Array.isArray(o.$in)?o.$in.map(s):o.$in}:n.status=s(o),e}class D{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new T(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(` -`)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){this.ensureIntent();const r=this.service(e),n=this.toQuery(),o=await r.executeQuery(e.prepareQuery(n)),s=new ie(o);return n.facets.length&&(s.facets=await de(r,d=>e.prepareQuery(d),n,n.facets)),s}async executeForRows(e){return this.executeForList(e)}async executeForPage(e,r,n){this.ensureIntent();const o=this.service(e),s=this.toQuery(),d=await o.executeCount(s,this.pageTotalAlias,this.pageTotalAlias?{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}:void 0),a=this.toQuery().offset(r).limit(n),c=new ie(await o.executeQuery(e.prepareQuery(a)),{totalCount:d});return this.pageTotalAlias&&(c.aggregations[this.pageTotalAlias]=d),s.facets.length&&(c.facets=await de(o,m=>e.prepareQuery(m),s,s.facets)),{data:c,totalCount:d,offset:r,limit:n}}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends D{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends D{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new T("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends D{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends D{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class He extends D{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class Ve extends D{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class ue extends D{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),Me,{filter:(o,s)=>o==="status.code"?{status:{$inSubquery:{query:new T("OrderStatus").filter({code:s}),field:"id"}}}:o==="itemList.productName"?{id:{$inSubquery:{query:new T("OrderItem").filter({productName:s}),field:"orderId"}}}:{[o]:s},order:(o,s)=>s==="asc"?R.asc(o):R.desc(o)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new T("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const o=r.toQuery();return o.commentText||o.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>o},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.applyRowCount(),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForList(e)}executeForPage(e,r,n){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForPage(e,r,n)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new ue}static customerOrdersWithMinimalFields(){return new ue(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new He}static shipments(){return new Ve}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),b=document.querySelector("#result"),ge=document.querySelector("#result-title"),fe=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),le=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),$=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),me=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=document.querySelector("#view-tree"),Ae=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let i=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[i]??t}function O(t){return i==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let w="tree",v,Se=0,ee;const A={search:"",page:0,pageSize:4},Ce=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ce==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Ie(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(o=>o.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Ie(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=await r.executeForPage(t.context,A.page*A.pageSize,A.pageSize),o=n.data.facet("statusCounts")??[];return{orders:n.data,totalOrders:Number(n.data.aggregations.totalOrders??n.totalCount),filteredOrders:n.totalCount,statusFacets:o.map(s=>({code:te(s),name:String(s.name??""),color:String(s.color??""),orderCount:Number(s.orderCount??0),orderTotalAmount:Number(s.orderTotalAmount??0)})).filter(s=>s.code&&s.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:r.toQExpression("executeForPage(ctx, pageOffset, pageSize);")}}const we=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() - .selectPlatformWith(Q.platforms().selectName()) - .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) - .selectStatusWith(Q.orderStatuses().selectName().selectColor()) - .orderByOrderDateDescending() - .orderByIdDescending() - .limit(8) - .comment('what: list recent commerce orders') - .purpose('why: provide the default order overview') - .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() - .withOrderNumberIs('TQL-2026-1003') - .selectPlatformWith(Q.platforms()) - .selectCustomerWith(Q.customers()) - .selectStatusWith(Q.orderStatuses().selectName().selectColor()) - .selectItemListWith(Q.orderItems().orderByIdAscending()) - .selectPaymentListWith(Q.payments().orderByIdAscending()) - .selectShipmentListWith(Q.shipments().orderByIdAscending()) - .limit(1) - .comment('what: load one complete order graph') - .purpose('why: inspect items, payment and fulfillment together') - .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() - .selectPlatformWith(Q.platforms().selectName()) - .countOrderListAs('orderCount') - .orderByNameAscending() - .comment('what: list customers with related order counts') - .purpose('why: compare customer activity at a glance') - .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() - .groupByCurrency().groupByStatus() - .countAs('orderCount') - .sumTotalAmountAs('grossAmount') - .averageTotalAmountAs('averageOrderValue') - .comment('what: aggregate orders by currency and status') - .purpose('why: show the current order funnel') - .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() - .groupByProductName() - .sumQuantityAs('units') - .sumLineAmountAs('revenue') - .comment('what: aggregate sold units and line revenue') - .purpose('why: identify the strongest products in the demo data') - .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() - .groupByCurrency().groupByProvider().groupByStatus() - .countAs('paymentCount').sumAmountAs('paymentAmount') - .orderByCurrencyAscending().orderByProviderAscending() - .comment('what: reconcile payment totals by provider') - .purpose('why: compare captured, pending and refunded money') - .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、范围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() - .withStatusIsPendingPayment() - .selectStatusWith(Q.orderStatuses().selectName().selectColor()) - .selectCustomerWith(Q.customers().selectName()) - .selectPaymentListWith(Q.payments()) - .comment('what: find orders awaiting payment') - .purpose('why: support payment follow-up') - .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() - .withPlatformIdIs('1') - .withTotalAmountGreaterThanOrEqualTo(500) - .selectCustomerWith(Q.customers().selectName().selectCity()) - .orderByTotalAmountDescending() - .comment('what: find high-value domestic orders') - .purpose('why: prioritize valuable fulfillment work') - .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() - .withStatusIn('READY', 'IN_TRANSIT') - .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) - .orderByStatusAscending().orderByIdAscending() - .comment('what: find shipments that are not delivered') - .purpose('why: monitor active fulfillment') - .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { - "filter": { - "currency": "CNY", - "totalAmount": { "$gte": 250 }, - "status": { "$in": ["PAID", "SHIPPED"] } - }, - "orderBy": [{ "field": "totalAmount", "direction": "desc" }] -}; -const data = await Q.customerOrders() - .filterByJson(input) - .limit(20) - .comment('what: execute a validated browser search') - .purpose('why: demonstrate safe dynamic order discovery') - .executeForList(ctx);`,run:t=>G(t,{filter:{currency:"CNY",totalAmount:{$gte:250},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { - "filter": { "orderDate": { "$gte": "2026-09-15" } }, - "orderBy": [{ "field": "orderDate", "direction": "asc" }] -}; -const data = await Q.customerOrders() - .filterByJson(input) - .limit(20) - .comment('what: execute a validated browser search') - .purpose('why: demonstrate safe dynamic order discovery') - .executeForList(ctx);`,run:t=>G(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { - "filter": { - "status": "DELIVERED", - "internalNote": { "$contains": "not queryable" } - } -}; -const request = Q.customerOrders().filterByJson(input); -const data = await request - .limit(20) - .comment('what: execute a validated browser search') - .purpose('why: demonstrate safe dynamic order discovery') - .executeForList(ctx); -const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],pe=we.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ce},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new $e().enableSelect();r.install(new Re(ce,{},{constants:_e})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const o=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),s=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:o,review:(d,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(d=>({policy:d,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(s),await s.ensureSchema(),{client:r,context:s,evidence:n}}async function be(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const o=he.map(s=>n.request({entity:s.entity,action:"Create",id:s.id,payload:s.payload}));for(const s of o)t.client.preflightMutation(s);for(const s of o)await t.client.executeMutation(s)})}function dt(){F.replaceChildren();for(const t of we){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const o=document.createElement("p");o.textContent=O(t.description),r.append(n,o);const s=document.createElement("div");s.className="query-links";for(const d of t.queries){const a=document.createElement("a");a.href=`#${d.id}`,a.dataset.queryId=d.id,a.textContent=O(d.title),a.addEventListener("click",c=>{c.preventDefault(),W=d.id,history.replaceState(null,"",`#${d.id}`),V(),E&&P(d,E).catch(N)}),s.append(a)}e.append(r,s),F.append(e)}V()}function V(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function P(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),b.classList.add("loading"),b.setAttribute("aria-busy","true"),ge.textContent=O(t.title),fe.textContent=O(t.description),le.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Ie(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),b.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),$.textContent=t.view==="dashboard"?i==="en"?"Order management center":"订单管理中心":i==="en"?"Result tree":"结果树",J.textContent=i==="en"?"Running query…":"查询中…";try{const o=await t.run(e);t.view==="dashboard"&&(le.textContent=o.queryExpression),v={data:o,query:t,active:e},w=t.view==="dashboard"||Z(o)?"table":"tree",z();const s=Math.max(1,Math.round(performance.now()-r));Se=s,ee=n;const d=e.evidence.snapshot();Ee(d,n),Pe(o,t,s)}finally{b.classList.remove("loading"),b.removeAttribute("aria-busy")}}function Ee(t,e=ee){me.replaceChildren(),et.textContent=i==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const o=document.createElement("tr");o.className="evidence-row";const s=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),d=document.createElement("td");d.className="evidence-time",d.dataset.executedAt=e?.toISOString()??"",d.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const a=document.createElement("td");a.textContent=`${v?.query.id??"query"} · #${n+1} · ${s?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const h=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${h}`,o.append(d,a,c,m),me.append(o)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!v)return;const{data:t,query:e,active:r}=v,n=e.view==="dashboard"||Z(t);if(n||(w="tree"),Q.disabled=!n,Q.classList.toggle("active",w==="table"),H.classList.toggle("active",w==="tree"),Q.setAttribute("aria-pressed",String(w==="table")),H.setAttribute("aria-pressed",String(w==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",w!=="tree"),w==="table"&&e.view==="dashboard"){$.textContent=i==="en"?"Result table":"结果表格",mt(t,r,e);return}if(w==="table"&&Z(t)){$.textContent=i==="en"?"Result table":"结果表格",ut(t);return}$.textContent=i==="en"?"Result tree":"结果树",Le(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const a=document.createElement("p");a.className="result-table-empty",a.textContent=i==="en"?"The query returned no records.":"查询没有返回记录。",e.append(a),b.replaceChildren(e);return}const r=[...new Set(t.flatMap(a=>Object.keys(a)))],n=document.createElement("table");n.className="result-table";const o=document.createElement("thead"),s=document.createElement("tr");for(const a of r){const c=document.createElement("th");c.scope="col",c.textContent=a,s.append(c)}o.append(s);const d=document.createElement("tbody");for(const a of t){const c=document.createElement("tr");for(const m of r){const h=document.createElement("td");h.textContent=lt(a[m]),c.append(h)}d.append(c)}n.append(o,d),e.append(n),b.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return i==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return Ne(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?i==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const o=document.createElement("div");o.className="order-center-toolbar";const s=document.createElement("div"),d=document.createElement("h3");d.textContent=i==="en"?"Order Management Center":"订单管理中心";const a=document.createElement("p");a.textContent=i==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",s.append(d,a);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=i==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",i==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",i==="en"?"Run order query":"执行订单查询"),h.title=i==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),h.append(l),c.append(m,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=m.value.trim(),A.page=0,P(r,e).catch(N)}),o.append(s,c);const S=document.createElement("div");S.className="order-metrics",S.append(ye(i==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,P(r,e).catch(N)}));for(const p of t.statusFacets)S.append(ye(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,P(r,e).catch(N)},`${i==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const _=document.createElement("div");_.className="order-row order-row-head";const xe=i==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of xe){const x=document.createElement("span");x.textContent=p,_.append(x)}if(g.append(_),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=i==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const M=document.createElement("div");M.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=i==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const q=document.createElement("div");q.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));q.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p=ae-1,e,r)),M.append(ne,q),n.append(o,S,g,M),b.replaceChildren(n)}function ye(t,e,r,n,o,s,d){const a=document.createElement("button");a.type="button",a.className=`metric-card metric-${r}`,n&&a.style.setProperty("--metric-color",n),a.classList.toggle("active",o);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),a.append(c,m),d){const h=document.createElement("small");h.textContent=d,a.append(h)}return a.addEventListener("click",s),a}function pt(t){return new Intl.NumberFormat(i==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const s=document.createElement("span"),d=document.createElement("span"),a=te(r);d.className=`status-badge status-${a.toLowerCase()}`,d.textContent=Ne(a)||String(r.name??a);const c=String(r.color??"");c&&(d.style.color=c,d.style.backgroundColor=`${c}18`),s.append(d),e.append(s);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const l=document.createElement("small");l.textContent=`+${h}`,m.append(l)}return e.append(m),e}function j(t,e,r,n,o){const s=document.createElement("button");return s.type="button",s.textContent=t,s.disabled=r,s.addEventListener("click",()=>{A.page=e,P(o,n).catch(N)}),s}function Ne(t){return(i==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Le(t){b.replaceChildren(Oe(t,"result",0))}function Oe(t,e,r){if(t!==null&&typeof t=="object"){const d=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),a=document.createElement("details");a.className="tree-branch",a.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,d.length),c.append(m,h),a.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of d)l.append(Oe(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return a.append(l),a}const n=document.createElement("div");n.className="tree-leaf";const o=document.createElement("span");o.className="tree-key",o.textContent=e;const s=document.createElement("span");return s.className=`tree-value tree-${t===null?"null":typeof t}`,s.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(o,s),n}function ht(t,e){if(Array.isArray(t))return i==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):i==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Pe(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),o=i==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${o} · ${r} ms · ${i==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function De(t){const e=he.filter(r=>r.entity==="CustomerOrder").length;k.textContent=i==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=i==="en"?"en":"zh-CN",document.title=i==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=i==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),Ae.forEach(e=>{const r=e.dataset.locale===i;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",i==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",i==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",i==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",i==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",i==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",i==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",i==="en"?"Result tree actions":"结果树操作"),dt(),v){const{data:e,query:r,active:n}=v;ge.textContent=O(r.title),fe.textContent=O(r.description),z(),Ee(n.evidence.snapshot(),ee),Pe(e,r,Se),De(B.checked?"opfs":"memory")}else k.textContent=i==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return pe.find(t=>t.id===W)??pe[0]}async function qe(t){k.textContent=i==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await be(r),await P(re(),r),De(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),qe(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await be(E),await P(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{b.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(w="table",z())});H.addEventListener("click",()=>{w="tree",z()});tt.addEventListener("click",()=>{b.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});Ae.forEach(t=>{t.addEventListener("click",()=>{i=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",i),ve()})});function N(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=i==="en"?"Query failed":"查询失败",Le({error:e.name,message:e.message})}ve();W=re().id;V();qe(Ce).catch(N); diff --git a/dist/assets/object-location-xgYMemK6.js b/assets/object-location-CJfVWqJC.js similarity index 98% rename from dist/assets/object-location-xgYMemK6.js rename to assets/object-location-CJfVWqJC.js index 8c8bc4aa545522c7f661771b17aa4cfc4635714b..c939dc87b827c5badde2203ea5ea8a76769aea66 100644 --- a/dist/assets/object-location-xgYMemK6.js +++ b/assets/object-location-CJfVWqJC.js @@ -1 +1 @@ -import{f as u}from"./dynamic-search-BBmdgl4H.js";const i=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class V{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(s,e){this.traces.set(i(s),{key:Object.freeze({...s}),nodes:u(e)})}traceChain(s){return this.traces.get(i(s))?.nodes}set(s,e,t){if(!e.trim())throw new TypeError("field is required");const r=i(s),a=this.changes.get(r)??{key:Object.freeze({...s}),values:{}};a.values[e]=t,this.changes.set(r,a)}snapshot(){return[...this.changes.values()].map(s=>({key:Object.freeze({...s.key}),values:Object.freeze({...s.values})}))}change(s){return Object.freeze({...this.changes.get(i(s))?.values??{}})}mergeFrom(s){if(s!==this){for(const e of s.snapshotVersions())this.requireMatchingVersion(e.key,e.version);for(const e of s.snapshot())for(const[t,r]of Object.entries(e.values))this.set(e.key,t,r);for(const e of s.newKeys.values())this.markAsNew(e);for(const e of s.deletedKeys.values())this.markAsDeleted(e);for(const e of s.snapshotVersions())this.setOriginalVersion(e.key,e.version);for(const e of s.traces.values())this.setTraceChain(e.key,e.nodes)}}mergeEntityFrom(s,e){if(s===this)return;const t=s.originalVersion(e);t!==void 0&&this.requireMatchingVersion(e,t);for(const[a,c]of Object.entries(s.change(e)))this.set(e,a,c);s.isNew(e)&&this.markAsNew(e),s.isDeleted(e)&&this.markAsDeleted(e),t!==void 0&&this.setOriginalVersion(e,t);const r=s.traceChain(e);r&&this.setTraceChain(e,r)}hasPending(s){const e=i(s);return this.newKeys.has(e)||this.deletedKeys.has(e)||Object.keys(this.changes.get(e)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(s,e){const t=i(s),r=i(e);if(t===r)return;const a=this.originalVersion(s);a!==void 0&&this.requireMatchingVersion(e,a);const c=this.changes.get(t);if(c){this.changes.delete(t);for(const[f,g]of Object.entries(c.values))this.set(e,f,g)}const h=this.originalVersions.get(t);h!==void 0&&(this.originalVersions.delete(t),this.originalVersions.set(r,{key:Object.freeze({...e}),version:h.version})),this.newKeys.delete(t)&&this.newKeys.set(r,Object.freeze({...e})),this.deletedKeys.delete(t)&&this.deletedKeys.set(r,Object.freeze({...e}));const l=this.traces.get(t);l&&(this.traces.delete(t),this.setTraceChain(e,l.nodes))}clearEntity(s){const e=i(s);this.changes.delete(e),this.newKeys.delete(e),this.deletedKeys.delete(e),this.traces.delete(e)}requireMatchingVersion(s,e){const t=this.originalVersion(s);if(t!==void 0&&t!==e)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(s,e){this.requireMatchingVersion(s,e),this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}acceptCommittedVersion(s,e){if(this.hasPending(s))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}originalVersion(s){return this.originalVersions.get(i(s))?.version}markAsNew(s){this.newKeys.set(i(s),Object.freeze({...s}))}isNew(s){return this.newKeys.has(i(s))}markAsDeleted(s){const e=i(s);this.changes.delete(e),this.deletedKeys.set(e,Object.freeze({...s}))}isDeleted(s){return this.deletedKeys.has(i(s))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}function d(n){const s=n.split("_");return s[0]+s.slice(1).map(e=>e?e[0].toUpperCase()+e.slice(1):"").join("")}function p(n,s){if(s==="snake_case")return n;const e=d(n);return s==="camelCase"||!e?e:e[0].toUpperCase()+e.slice(1)}function m(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class o{constructor(s){this.segments=s}static root(){return new o([])}static property(s){return o.root().property(s)}property(s){return new o([...this.segments,{kind:"property",name:s}])}index(s){return new o([...this.segments,{kind:"index",index:s}])}prefixedBy(s){return new o([...s.segments,...this.segments])}modelPath(){return this.render(s=>s)}nativePath(){return this.render(d)}instancePath(s="camelCase"){return this.segments.map(e=>e.kind==="index"?String(e.index):m(p(e.name,s))).map(e=>`/${e}`).join("")}toString(){return this.nativePath()}render(s){let e="";for(const t of this.segments)t.kind==="index"?e+=`[${t.index}]`:e+=`${e?".":""}${s(t.name)}`;return e}}export{V as E,o as O}; +import{f as u}from"./dynamic-search-Ch_QcWVU.js";const i=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class V{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(s,e){this.traces.set(i(s),{key:Object.freeze({...s}),nodes:u(e)})}traceChain(s){return this.traces.get(i(s))?.nodes}set(s,e,t){if(!e.trim())throw new TypeError("field is required");const r=i(s),a=this.changes.get(r)??{key:Object.freeze({...s}),values:{}};a.values[e]=t,this.changes.set(r,a)}snapshot(){return[...this.changes.values()].map(s=>({key:Object.freeze({...s.key}),values:Object.freeze({...s.values})}))}change(s){return Object.freeze({...this.changes.get(i(s))?.values??{}})}mergeFrom(s){if(s!==this){for(const e of s.snapshotVersions())this.requireMatchingVersion(e.key,e.version);for(const e of s.snapshot())for(const[t,r]of Object.entries(e.values))this.set(e.key,t,r);for(const e of s.newKeys.values())this.markAsNew(e);for(const e of s.deletedKeys.values())this.markAsDeleted(e);for(const e of s.snapshotVersions())this.setOriginalVersion(e.key,e.version);for(const e of s.traces.values())this.setTraceChain(e.key,e.nodes)}}mergeEntityFrom(s,e){if(s===this)return;const t=s.originalVersion(e);t!==void 0&&this.requireMatchingVersion(e,t);for(const[a,c]of Object.entries(s.change(e)))this.set(e,a,c);s.isNew(e)&&this.markAsNew(e),s.isDeleted(e)&&this.markAsDeleted(e),t!==void 0&&this.setOriginalVersion(e,t);const r=s.traceChain(e);r&&this.setTraceChain(e,r)}hasPending(s){const e=i(s);return this.newKeys.has(e)||this.deletedKeys.has(e)||Object.keys(this.changes.get(e)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(s,e){const t=i(s),r=i(e);if(t===r)return;const a=this.originalVersion(s);a!==void 0&&this.requireMatchingVersion(e,a);const c=this.changes.get(t);if(c){this.changes.delete(t);for(const[f,g]of Object.entries(c.values))this.set(e,f,g)}const h=this.originalVersions.get(t);h!==void 0&&(this.originalVersions.delete(t),this.originalVersions.set(r,{key:Object.freeze({...e}),version:h.version})),this.newKeys.delete(t)&&this.newKeys.set(r,Object.freeze({...e})),this.deletedKeys.delete(t)&&this.deletedKeys.set(r,Object.freeze({...e}));const l=this.traces.get(t);l&&(this.traces.delete(t),this.setTraceChain(e,l.nodes))}clearEntity(s){const e=i(s);this.changes.delete(e),this.newKeys.delete(e),this.deletedKeys.delete(e),this.traces.delete(e)}requireMatchingVersion(s,e){const t=this.originalVersion(s);if(t!==void 0&&t!==e)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(s,e){this.requireMatchingVersion(s,e),this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}acceptCommittedVersion(s,e){if(this.hasPending(s))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}originalVersion(s){return this.originalVersions.get(i(s))?.version}markAsNew(s){this.newKeys.set(i(s),Object.freeze({...s}))}isNew(s){return this.newKeys.has(i(s))}markAsDeleted(s){const e=i(s);this.changes.delete(e),this.deletedKeys.set(e,Object.freeze({...s}))}isDeleted(s){return this.deletedKeys.has(i(s))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}function d(n){const s=n.split("_");return s[0]+s.slice(1).map(e=>e?e[0].toUpperCase()+e.slice(1):"").join("")}function p(n,s){if(s==="snake_case")return n;const e=d(n);return s==="camelCase"||!e?e:e[0].toUpperCase()+e.slice(1)}function m(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class o{constructor(s){this.segments=s}static root(){return new o([])}static property(s){return o.root().property(s)}property(s){return new o([...this.segments,{kind:"property",name:s}])}index(s){return new o([...this.segments,{kind:"index",index:s}])}prefixedBy(s){return new o([...s.segments,...this.segments])}modelPath(){return this.render(s=>s)}nativePath(){return this.render(d)}instancePath(s="camelCase"){return this.segments.map(e=>e.kind==="index"?String(e.index):m(p(e.name,s))).map(e=>`/${e}`).join("")}toString(){return this.nativePath()}render(s){let e="";for(const t of this.segments)t.kind==="index"?e+=`[${t.index}]`:e+=`${e?".":""}${s(t.name)}`;return e}}export{V as E,o as O}; diff --git a/dist/assets/orders-CQOGX0kN.js b/assets/orders-BIvSfQqM.js similarity index 99% rename from dist/assets/orders-CQOGX0kN.js rename to assets/orders-BIvSfQqM.js index 7d712fbdeea59f2a682869956b591f9018f3c8d5..aab4e2a829e978be0cb9595d8597ed94fb5e0dcf 100644 --- a/dist/assets/orders-CQOGX0kN.js +++ b/assets/orders-BIvSfQqM.js @@ -1,2 +1,2 @@ -import{S as yt,a as A,L as v,M as b,C as L,d as G,e as F,Q as z,R as pt,B as ft,U as gt,D as Ot,c as wt,b as qt}from"./dynamic-search-BBmdgl4H.js";import{E as T,O as w}from"./object-location-xgYMemK6.js";/* empty css */class c extends yt{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,r="id",i="id",s=!0,h){return super.relationQuery(t,e,r,i,s,h)}}class Q{static teaqlTemporaryId=0;id;platform;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--Q.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Customer",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new Q(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new Q({id:String(t)})}static teaqlBootstrapNew(t){return new Q().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Customer",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.customer;(this.id===void 0||!a.isLoaded("customer")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomer(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Customer",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.customer;(this.id===void 0||!y.isLoaded("customer")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomer(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.customer;(this.id===void 0||!g.isLoaded("customer")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomer(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,platform:this.platform,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class B{static teaqlTemporaryId=0;id;customerOrder;productName;quantity;unitPrice;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--B.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const r={...t};Object.assign(this,r),t.customerOrder&&typeof t.customerOrder=="object"&&(this.customerOrder=t.customerOrder instanceof $?t.customerOrder:$.fromRecord(t.customerOrder),this.markLoaded("customerOrder"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const r=new B(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new B({id:String(t)})}static teaqlBootstrapNew(t){return new B().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const p=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(l=>!this.isLoaded(l.member));if(p)throw new L([{ruleId:"invalid_type",location:w.property(p.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o),o.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderItem",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return p.scopeFor(this.teaqlEntityKey()),this;const l=await e.executeMutation(p);for(const[C,f]of Object.entries(o.payload))C!=="id"&&C!=="version"&&this._root.set(this.teaqlEntityKey(),C,f);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();return this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update"),p.scopeFor(m),e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer_order:this.customerOrder,product_name:this.productName,quantity:this.quantity,unit_price:this.unitPrice,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateProductName(t){return this.productName=t,this.markLoaded("productName"),this._root.set(this.teaqlEntityKey(),"product_name",t),this}updateQuantity(t){return this.quantity=t,this.markLoaded("quantity"),this._root.set(this.teaqlEntityKey(),"quantity",t),this}updateUnitPrice(t){return this.unitPrice=t,this.markLoaded("unitPrice"),this._root.set(this.teaqlEntityKey(),"unit_price",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomerOrder(t){return this.customerOrder=t?.id??t,this.markLoaded("customerOrder"),this._root.set(this.teaqlEntityKey(),"customer_order",this.customerOrder),this}}class ${static teaqlTemporaryId=0;id;customer;status;orderNumber;orderDate;totalAmount;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--$.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderItemList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderItemList,Object.assign(this,r),t.customer&&typeof t.customer=="object"&&(this.customer=t.customer instanceof Q?t.customer:Q.fromRecord(t.customer),this.markLoaded("customer")),t.status&&typeof t.status=="object"&&(this.status=t.status instanceof S?t.status:S.fromRecord(t.status),this.markLoaded("status")),Array.isArray(t.orderItemList)){const i=t.orderItemList;this._orderItemList=new A(i.map(s=>s instanceof B?s:B.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"CustomerOrder",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new $(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new $({id:String(t)})}static teaqlBootstrapNew(t){return new $().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"CustomerOrder",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderItemList.entries()){a.teaqlAttachRoot(this._root);const u=a.customerOrder;(this.id===void 0||!a.isLoaded("customerOrder")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomerOrder(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_item_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"CustomerOrder",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderItemList.entries()){y.teaqlAttachRoot(this._root);const O=y.customerOrder;(this.id===void 0||!y.isLoaded("customerOrder")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomerOrder(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_item_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderItemList.entries()){g.teaqlAttachRoot(this._root);const y=g.customerOrder;(this.id===void 0||!g.isLoaded("customerOrder")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomerOrder(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_item_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer:this.customer,status:this.status,order_number:this.orderNumber,order_date:this.orderDate,total_amount:this.totalAmount,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateOrderNumber(t){return this.orderNumber=t,this.markLoaded("orderNumber"),this._root.set(this.teaqlEntityKey(),"order_number",t),this}updateOrderDate(t){return this.orderDate=t,this.markLoaded("orderDate"),this._root.set(this.teaqlEntityKey(),"order_date",t),this}updateTotalAmount(t){return this.totalAmount=t,this.markLoaded("totalAmount"),this._root.set(this.teaqlEntityKey(),"total_amount",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomer(t){return this.customer=t?.id??t,this.markLoaded("customer"),this._root.set(this.teaqlEntityKey(),"customer",this.customer),this}updateStatus(t){return this.status=t?.id??t,this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToNew(){return this.status="1001",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToPaid(){return this.status="1002",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToCancelled(){return this.status="1003",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}orderItemList(){return this._orderItemList}}class S{static teaqlTemporaryId=0;platform;id;name;code;color;displayOrder;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--S.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderStatus",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new S(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new S({id:String(t)})}static teaqlBootstrapNew(t){return new S().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderStatus",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.status;(this.id===void 0||!a.isLoaded("status")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateStatus(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderStatus",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.status;(this.id===void 0||!y.isLoaded("status")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateStatus(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.status;(this.id===void 0||!g.isLoaded("status")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateStatus(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{platform:this.platform,id:this.id,name:this.name,code:this.code,color:this.color,display_order:this.displayOrder,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateCode(t){return this.code=t,this.markLoaded("code"),this._root.set(this.teaqlEntityKey(),"code",t),this}updateColor(t){return this.color=t,this.markLoaded("color"),this._root.set(this.teaqlEntityKey(),"color",t),this}updateDisplayOrder(t){return this.displayOrder=t,this.markLoaded("displayOrder"),this._root.set(this.teaqlEntityKey(),"display_order",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class N{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--N.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderStatusList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderStatusList,delete r.customerList,Object.assign(this,r),Array.isArray(t.orderStatusList)){const i=t.orderStatusList;this._orderStatusList=new A(i.map(s=>s instanceof S?s:S.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderStatusList")}if(Array.isArray(t.customerList)){const i=t.customerList;this._customerList=new A(i.map(s=>s instanceof Q?s:Q.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderStatusList)e.teaqlAttachRoot(t);for(const e of this._customerList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new N(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new N({id:String(t)})}static teaqlBootstrapNew(t){return new N().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderStatusList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_status_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}for(const[l,a]of this._customerList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Platform",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderStatusList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_status_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}for(const[g,y]of this._customerList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderStatusList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_status_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}for(const[f,g]of this._customerList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}orderStatusList(){return this._orderStatusList}customerList(){return this._customerList}}const J=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({orderStatusList:"OrderStatus",customerList:"Customer"})}),OrderStatus:Object.freeze({fields:Object.freeze({platform:"integer",id:"integer",name:"string",code:"string",color:"string",display_order:"integer",displayOrder:"integer",version:"integer"}),queryFields:Object.freeze({platform:"platform",id:"id",name:"name",code:"code",color:"color",display_order:"displayOrder",displayOrder:"displayOrder",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),Customer:Object.freeze({fields:Object.freeze({id:"integer",platform:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",platform:"platform",name:"name",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),CustomerOrder:Object.freeze({fields:Object.freeze({id:"integer",customer:"integer",status:"integer",order_number:"string",orderNumber:"string",order_date:"date",orderDate:"date",total_amount:"decimal",totalAmount:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer:"customer",status:"status",order_number:"orderNumber",orderNumber:"orderNumber",order_date:"orderDate",orderDate:"orderDate",total_amount:"totalAmount",totalAmount:"totalAmount",version:"version"}),relations:Object.freeze({customer:"Customer",status:"OrderStatus",orderItemList:"OrderItem"})}),OrderItem:Object.freeze({fields:Object.freeze({id:"integer",customer_order:"integer",customerOrder:"integer",product_name:"string",productName:"string",quantity:"integer",unit_price:"decimal",unitPrice:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer_order:"customerOrder",customerOrder:"customerOrder",product_name:"productName",productName:"productName",quantity:"quantity",unit_price:"unitPrice",unitPrice:"unitPrice",version:"version"}),relations:Object.freeze({customer_order:"CustomerOrder",customerOrder:"CustomerOrder"})})});class st{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new vt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectOrderStatusListWith(t){return this.query.relationQuery("orderStatusList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectOrderStatusListWith",relation:"orderStatusList"}),this}selectCustomerListWith(t){return this.query.relationQuery("customerList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectCustomerListWith",relation:"customerList"}),this}haveOrderStatuses(){return this.withOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}haveNoOrderStatuses(){return this.withoutOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}withOrderStatusListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutOrderStatusListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}haveCustomers(){return this.withCustomerListMatching({toQuery:()=>new c("Customer")})}haveNoCustomers(){return this.withoutCustomerListMatching({toQuery:()=>new c("Customer")})}withCustomerListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutCustomerListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countOrderStatuses(){return this.countOrderStatusesAs("countOrderStatuses")}countOrderStatusesAs(t){const e=new c("OrderStatus").filter({version:{$gte:1}});return this.countOrderStatusesWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderStatusesAs",relation:"orderStatusList",alias:t},this}countOrderStatusesWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"relation-count",method:"countOrderStatusesWith",relation:"orderStatusList",alias:t}),this}minDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.minDisplayOrderOfOrderStatusesAs("minOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}minDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"minDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}maxDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.maxDisplayOrderOfOrderStatusesAs("maxOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}maxDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"maxDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sumDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sumDisplayOrderOfOrderStatusesAs("sumOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sumDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sumDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}avgDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.avgDisplayOrderOfOrderStatusesAs("avgOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}avgDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"avgDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}standardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.standardDeviationDisplayOrderOfOrderStatusesAs("standardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}standardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"standardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs("squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sampleVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sampleVarianceDisplayOrderOfOrderStatusesAs("sampleVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sampleVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sampleVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}samplePopulationVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs("samplePopulationVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}samplePopulationVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}countCustomers(){return this.countCustomersAs("countCustomers")}countCustomersAs(t){const e=new c("Customer").filter({version:{$gte:1}});return this.countCustomersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomersAs",relation:"customerList",alias:t},this}countCustomersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerList",t,r,!0,{kind:"relation-count",method:"countCustomersWith",relation:"customerList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof N?o:N.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof N?u:N.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof N?o:N.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class vt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new N}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ot{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderStatus"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new It(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["platform","id","name","code","color","displayOrder","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectCode(){return this.query.select(["code"]),this}selectColor(){return this.query.select(["color"]),this}selectDisplayOrder(){return this.query.select(["displayOrder"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","status",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"status"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"status"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withCodeContaining(t){return this.filters.push({code:{$contains:t}}),this}withCodeIs(t){return this.filters.push({code:{$eq:t}}),this}withCodeIsNot(t){return this.filters.push({code:{$ne:t}}),this}withCodeIn(...t){return this.filters.push({code:{$in:t}}),this}withCodeNotIn(...t){return this.filters.push({code:{$notIn:t}}),this}withCodeGreaterThan(t){return this.filters.push({code:{$gt:t}}),this}withCodeGreaterThanOrEqualTo(t){return this.filters.push({code:{$gte:t}}),this}withCodeLessThan(t){return this.filters.push({code:{$lt:t}}),this}withCodeLessThanOrEqualTo(t){return this.filters.push({code:{$lte:t}}),this}withCodeBetween(t,e){return this.filters.push({code:{$between:[t,e]}}),this}withCodeIsKnown(){return this.filters.push({code:{$isNull:!1}}),this}withCodeIsUnknown(){return this.filters.push({code:{$isNull:!0}}),this}withCodeNotContaining(t){return this.filters.push({code:{$notContains:t}}),this}withCodeStartingWith(t){return this.filters.push({code:{$startsWith:t}}),this}withCodeNotStartingWith(t){return this.filters.push({code:{$notStartsWith:t}}),this}withCodeEndingWith(t){return this.filters.push({code:{$endsWith:t}}),this}withCodeNotEndingWith(t){return this.filters.push({code:{$notEndsWith:t}}),this}withCodeSoundingLike(t){return this.filters.push({code:{$soundLike:t}}),this}withColorContaining(t){return this.filters.push({color:{$contains:t}}),this}withColorIs(t){return this.filters.push({color:{$eq:t}}),this}withColorIsNot(t){return this.filters.push({color:{$ne:t}}),this}withColorIn(...t){return this.filters.push({color:{$in:t}}),this}withColorNotIn(...t){return this.filters.push({color:{$notIn:t}}),this}withColorGreaterThan(t){return this.filters.push({color:{$gt:t}}),this}withColorGreaterThanOrEqualTo(t){return this.filters.push({color:{$gte:t}}),this}withColorLessThan(t){return this.filters.push({color:{$lt:t}}),this}withColorLessThanOrEqualTo(t){return this.filters.push({color:{$lte:t}}),this}withColorBetween(t,e){return this.filters.push({color:{$between:[t,e]}}),this}withColorIsKnown(){return this.filters.push({color:{$isNull:!1}}),this}withColorIsUnknown(){return this.filters.push({color:{$isNull:!0}}),this}withColorNotContaining(t){return this.filters.push({color:{$notContains:t}}),this}withColorStartingWith(t){return this.filters.push({color:{$startsWith:t}}),this}withColorNotStartingWith(t){return this.filters.push({color:{$notStartsWith:t}}),this}withColorEndingWith(t){return this.filters.push({color:{$endsWith:t}}),this}withColorNotEndingWith(t){return this.filters.push({color:{$notEndsWith:t}}),this}withColorSoundingLike(t){return this.filters.push({color:{$soundLike:t}}),this}withDisplayOrderIs(t){return this.filters.push({displayOrder:{$eq:t}}),this}withDisplayOrderIsNot(t){return this.filters.push({displayOrder:{$ne:t}}),this}withDisplayOrderIn(...t){return this.filters.push({displayOrder:{$in:t}}),this}withDisplayOrderNotIn(...t){return this.filters.push({displayOrder:{$notIn:t}}),this}withDisplayOrderGreaterThan(t){return this.filters.push({displayOrder:{$gt:t}}),this}withDisplayOrderGreaterThanOrEqualTo(t){return this.filters.push({displayOrder:{$gte:t}}),this}withDisplayOrderLessThan(t){return this.filters.push({displayOrder:{$lt:t}}),this}withDisplayOrderLessThanOrEqualTo(t){return this.filters.push({displayOrder:{$lte:t}}),this}withDisplayOrderBetween(t,e){return this.filters.push({displayOrder:{$between:[t,e]}}),this}withDisplayOrderIsKnown(){return this.filters.push({displayOrder:{$isNull:!1}}),this}withDisplayOrderIsUnknown(){return this.filters.push({displayOrder:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByCodeAscending(){return this.query.orderBy("code","asc"),this}orderByCodeDescending(){return this.query.orderBy("code","desc"),this}orderByColorAscending(){return this.query.orderBy("color","asc"),this}orderByColorDescending(){return this.query.orderBy("color","desc"),this}orderByDisplayOrderAscending(){return this.query.orderBy("displayOrder","asc"),this}orderByDisplayOrderDescending(){return this.query.orderBy("displayOrder","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minDisplayOrder(){return this.minDisplayOrderAs("minOfDisplayOrder")}minDisplayOrderAs(t){return this.query.aggregate("min","displayOrder",t),this}maxDisplayOrder(){return this.maxDisplayOrderAs("maxOfDisplayOrder")}maxDisplayOrderAs(t){return this.query.aggregate("max","displayOrder",t),this}sumDisplayOrder(){return this.sumDisplayOrderAs("sumOfDisplayOrder")}sumDisplayOrderAs(t){return this.query.aggregate("sum","displayOrder",t),this}avgDisplayOrder(){return this.avgDisplayOrderAs("avgOfDisplayOrder")}avgDisplayOrderAs(t){return this.query.aggregate("avg","displayOrder",t),this}standardDeviationDisplayOrder(){return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder")}standardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev","displayOrder",t),this}squareRootOfPopulationStandardDeviationDisplayOrder(){return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder")}squareRootOfPopulationStandardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev_pop","displayOrder",t),this}sampleVarianceDisplayOrder(){return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder")}sampleVarianceDisplayOrderAs(t){return this.query.aggregate("var_samp","displayOrder",t),this}samplePopulationVarianceDisplayOrder(){return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder")}samplePopulationVarianceDisplayOrderAs(t){return this.query.aggregate("var_pop","displayOrder",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByCode(){return this.query.groupBy("code"),this}groupByCodeAs(t){return this.query.groupBy("code"),this}groupByColor(){return this.query.groupBy("color"),this}groupByColorAs(t){return this.query.groupBy("color"),this}groupByDisplayOrder(){return this.query.groupBy("displayOrder"),this}groupByDisplayOrderAs(t){return this.query.groupBy("displayOrder"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof S?o:S.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof S?u:S.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof S?o:S.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class It{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new S}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class nt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Customer"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Lt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","platform","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","customer",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customer"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customer"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof Q?o:Q.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof Q?u:Q.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof Q?o:Q.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class Lt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new Q}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class at{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("CustomerOrder"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new At(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customer","status","orderNumber","orderDate","totalAmount","version"]),this}selectId(){return this.query.select(["id"]),this}selectOrderNumber(){return this.query.select(["orderNumber"]),this}selectOrderDate(){return this.query.select(["orderDate"]),this}selectTotalAmount(){return this.query.select(["totalAmount"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerWith(t){return this.query.select(["customer"]),this.query.relationQuery("customer",t.toQuery(),"customer","id",!1,{kind:"relation-select",method:"selectCustomerWith",relation:"customer"}),this}selectStatusWith(t){return this.query.select(["status"]),this.query.relationQuery("status",t.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this}withCustomerMatching(t){return this.filters.push({customer:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerMatching(t){return this.filters.push({customer:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withStatusMatching(t){return this.filters.push({status:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutStatusMatching(t){return this.filters.push({status:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectOrderItemListWith(t){return this.query.relationQuery("orderItemList",t.toQuery(),"id","customerOrder",!0,{kind:"relation-select",method:"selectOrderItemListWith",relation:"orderItemList"}),this}haveOrderItems(){return this.withOrderItemListMatching({toQuery:()=>new c("OrderItem")})}haveNoOrderItems(){return this.withoutOrderItemListMatching({toQuery:()=>new c("OrderItem")})}withOrderItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}withoutOrderItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}countOrderItems(){return this.countOrderItemsAs("countOrderItems")}countOrderItemsAs(t){const e=new c("OrderItem").filter({version:{$gte:1}});return this.countOrderItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderItemsAs",relation:"orderItemList",alias:t},this}countOrderItemsWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"relation-count",method:"countOrderItemsWith",relation:"orderItemList",alias:t}),this}minQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minQuantityOfOrderItemsAs("minOfQuantityOfOrderItems",{toQuery:()=>t})}minQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxQuantityOfOrderItemsAs("maxOfQuantityOfOrderItems",{toQuery:()=>t})}maxQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumQuantityOfOrderItemsAs("sumOfQuantityOfOrderItems",{toQuery:()=>t})}sumQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgQuantityOfOrderItemsAs("avgOfQuantityOfOrderItems",{toQuery:()=>t})}avgQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationQuantityOfOrderItemsAs("standardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}standardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceQuantityOfOrderItemsAs("sampleVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}sampleVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceQuantityOfOrderItemsAs("samplePopulationVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}minUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minUnitPriceOfOrderItemsAs("minOfUnitPriceOfOrderItems",{toQuery:()=>t})}minUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxUnitPriceOfOrderItemsAs("maxOfUnitPriceOfOrderItems",{toQuery:()=>t})}maxUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumUnitPriceOfOrderItemsAs("sumOfUnitPriceOfOrderItems",{toQuery:()=>t})}sumUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgUnitPriceOfOrderItemsAs("avgOfUnitPriceOfOrderItems",{toQuery:()=>t})}avgUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationUnitPriceOfOrderItemsAs("standardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}standardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceUnitPriceOfOrderItemsAs("sampleVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}sampleVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceUnitPriceOfOrderItemsAs("samplePopulationVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomer(t){return this.filters.push({customer:{$eq:t}}),this}filterByCustomerIn(...t){return this.filters.push({customer:{$in:t}}),this}withCustomerIsKnown(){return this.filters.push({customer:{$isNull:!1}}),this}withCustomerIsUnknown(){return this.filters.push({customer:{$isNull:!0}}),this}filterByStatus(t){return this.filters.push({status:{$eq:t}}),this}filterByStatusIn(...t){return this.filters.push({status:{$in:t}}),this}withStatusIsKnown(){return this.filters.push({status:{$isNull:!1}}),this}withStatusIsUnknown(){return this.filters.push({status:{$isNull:!0}}),this}withStatusIsNew(){return this.filters.push({status:{$eq:"1001"}}),this}withStatusIsPaid(){return this.filters.push({status:{$eq:"1002"}}),this}withStatusIsCancelled(){return this.filters.push({status:{$eq:"1003"}}),this}withOrderNumberContaining(t){return this.filters.push({orderNumber:{$contains:t}}),this}withOrderNumberIs(t){return this.filters.push({orderNumber:{$eq:t}}),this}withOrderNumberIsNot(t){return this.filters.push({orderNumber:{$ne:t}}),this}withOrderNumberIn(...t){return this.filters.push({orderNumber:{$in:t}}),this}withOrderNumberNotIn(...t){return this.filters.push({orderNumber:{$notIn:t}}),this}withOrderNumberGreaterThan(t){return this.filters.push({orderNumber:{$gt:t}}),this}withOrderNumberGreaterThanOrEqualTo(t){return this.filters.push({orderNumber:{$gte:t}}),this}withOrderNumberLessThan(t){return this.filters.push({orderNumber:{$lt:t}}),this}withOrderNumberLessThanOrEqualTo(t){return this.filters.push({orderNumber:{$lte:t}}),this}withOrderNumberBetween(t,e){return this.filters.push({orderNumber:{$between:[t,e]}}),this}withOrderNumberIsKnown(){return this.filters.push({orderNumber:{$isNull:!1}}),this}withOrderNumberIsUnknown(){return this.filters.push({orderNumber:{$isNull:!0}}),this}withOrderNumberNotContaining(t){return this.filters.push({orderNumber:{$notContains:t}}),this}withOrderNumberStartingWith(t){return this.filters.push({orderNumber:{$startsWith:t}}),this}withOrderNumberNotStartingWith(t){return this.filters.push({orderNumber:{$notStartsWith:t}}),this}withOrderNumberEndingWith(t){return this.filters.push({orderNumber:{$endsWith:t}}),this}withOrderNumberNotEndingWith(t){return this.filters.push({orderNumber:{$notEndsWith:t}}),this}withOrderNumberSoundingLike(t){return this.filters.push({orderNumber:{$soundLike:t}}),this}withOrderDateIs(t){return this.filters.push({orderDate:{$eq:t}}),this}withOrderDateIsNot(t){return this.filters.push({orderDate:{$ne:t}}),this}withOrderDateIn(...t){return this.filters.push({orderDate:{$in:t}}),this}withOrderDateNotIn(...t){return this.filters.push({orderDate:{$notIn:t}}),this}withOrderDateGreaterThan(t){return this.filters.push({orderDate:{$gt:t}}),this}withOrderDateGreaterThanOrEqualTo(t){return this.filters.push({orderDate:{$gte:t}}),this}withOrderDateLessThan(t){return this.filters.push({orderDate:{$lt:t}}),this}withOrderDateLessThanOrEqualTo(t){return this.filters.push({orderDate:{$lte:t}}),this}withOrderDateBetween(t,e){return this.filters.push({orderDate:{$between:[t,e]}}),this}withOrderDateIsKnown(){return this.filters.push({orderDate:{$isNull:!1}}),this}withOrderDateIsUnknown(){return this.filters.push({orderDate:{$isNull:!0}}),this}withTotalAmountIs(t){return this.filters.push({totalAmount:{$eq:t}}),this}withTotalAmountIsNot(t){return this.filters.push({totalAmount:{$ne:t}}),this}withTotalAmountIn(...t){return this.filters.push({totalAmount:{$in:t}}),this}withTotalAmountNotIn(...t){return this.filters.push({totalAmount:{$notIn:t}}),this}withTotalAmountGreaterThan(t){return this.filters.push({totalAmount:{$gt:t}}),this}withTotalAmountGreaterThanOrEqualTo(t){return this.filters.push({totalAmount:{$gte:t}}),this}withTotalAmountLessThan(t){return this.filters.push({totalAmount:{$lt:t}}),this}withTotalAmountLessThanOrEqualTo(t){return this.filters.push({totalAmount:{$lte:t}}),this}withTotalAmountBetween(t,e){return this.filters.push({totalAmount:{$between:[t,e]}}),this}withTotalAmountIsKnown(){return this.filters.push({totalAmount:{$isNull:!1}}),this}withTotalAmountIsUnknown(){return this.filters.push({totalAmount:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByOrderNumberAscending(){return this.query.orderBy("orderNumber","asc"),this}orderByOrderNumberDescending(){return this.query.orderBy("orderNumber","desc"),this}orderByOrderDateAscending(){return this.query.orderBy("orderDate","asc"),this}orderByOrderDateDescending(){return this.query.orderBy("orderDate","desc"),this}orderByTotalAmountAscending(){return this.query.orderBy("totalAmount","asc"),this}orderByTotalAmountDescending(){return this.query.orderBy("totalAmount","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minTotalAmount(){return this.minTotalAmountAs("minOfTotalAmount")}minTotalAmountAs(t){return this.query.aggregate("min","totalAmount",t),this}maxTotalAmount(){return this.maxTotalAmountAs("maxOfTotalAmount")}maxTotalAmountAs(t){return this.query.aggregate("max","totalAmount",t),this}sumTotalAmount(){return this.sumTotalAmountAs("sumOfTotalAmount")}sumTotalAmountAs(t){return this.query.aggregate("sum","totalAmount",t),this}avgTotalAmount(){return this.avgTotalAmountAs("avgOfTotalAmount")}avgTotalAmountAs(t){return this.query.aggregate("avg","totalAmount",t),this}standardDeviationTotalAmount(){return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount")}standardDeviationTotalAmountAs(t){return this.query.aggregate("stddev","totalAmount",t),this}squareRootOfPopulationStandardDeviationTotalAmount(){return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount")}squareRootOfPopulationStandardDeviationTotalAmountAs(t){return this.query.aggregate("stddev_pop","totalAmount",t),this}sampleVarianceTotalAmount(){return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount")}sampleVarianceTotalAmountAs(t){return this.query.aggregate("var_samp","totalAmount",t),this}samplePopulationVarianceTotalAmount(){return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount")}samplePopulationVarianceTotalAmountAs(t){return this.query.aggregate("var_pop","totalAmount",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomer(){return this.query.groupBy("customer"),this}groupByCustomerAs(t){return this.query.groupBy("customer"),this}groupByStatus(){return this.query.groupBy("status"),this}groupByStatusAs(t){return this.query.groupBy("status"),this}groupByOrderNumber(){return this.query.groupBy("orderNumber"),this}groupByOrderNumberAs(t){return this.query.groupBy("orderNumber"),this}groupByOrderDate(){return this.query.groupBy("orderDate"),this}groupByOrderDateAs(t){return this.query.groupBy("orderDate"),this}groupByTotalAmount(){return this.query.groupBy("totalAmount"),this}groupByTotalAmountAs(t){return this.query.groupBy("totalAmount"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerAs(t,e,r=!0){return this.query.facetBy(t,"customer",e,r,{kind:"facet",method:"facetByCustomerAs",relation:"customer",alias:t}),this}facetByStatusAs(t,e,r=!0){return this.query.facetBy(t,"status",e,r,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof $?o:$.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof $?u:$.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof $?o:$.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class At{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new $}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ut{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new _t(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customerOrder","productName","quantity","unitPrice","version"]),this}selectId(){return this.query.select(["id"]),this}selectProductName(){return this.query.select(["productName"]),this}selectQuantity(){return this.query.select(["quantity"]),this}selectUnitPrice(){return this.query.select(["unitPrice"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerOrderWith(t){return this.query.select(["customerOrder"]),this.query.relationQuery("customerOrder",t.toQuery(),"customerOrder","id",!1,{kind:"relation-select",method:"selectCustomerOrderWith",relation:"customerOrder"}),this}withCustomerOrderMatching(t){return this.filters.push({customerOrder:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerOrderMatching(t){return this.filters.push({customerOrder:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomerOrder(t){return this.filters.push({customerOrder:{$eq:t}}),this}filterByCustomerOrderIn(...t){return this.filters.push({customerOrder:{$in:t}}),this}withCustomerOrderIsKnown(){return this.filters.push({customerOrder:{$isNull:!1}}),this}withCustomerOrderIsUnknown(){return this.filters.push({customerOrder:{$isNull:!0}}),this}withProductNameContaining(t){return this.filters.push({productName:{$contains:t}}),this}withProductNameIs(t){return this.filters.push({productName:{$eq:t}}),this}withProductNameIsNot(t){return this.filters.push({productName:{$ne:t}}),this}withProductNameIn(...t){return this.filters.push({productName:{$in:t}}),this}withProductNameNotIn(...t){return this.filters.push({productName:{$notIn:t}}),this}withProductNameGreaterThan(t){return this.filters.push({productName:{$gt:t}}),this}withProductNameGreaterThanOrEqualTo(t){return this.filters.push({productName:{$gte:t}}),this}withProductNameLessThan(t){return this.filters.push({productName:{$lt:t}}),this}withProductNameLessThanOrEqualTo(t){return this.filters.push({productName:{$lte:t}}),this}withProductNameBetween(t,e){return this.filters.push({productName:{$between:[t,e]}}),this}withProductNameIsKnown(){return this.filters.push({productName:{$isNull:!1}}),this}withProductNameIsUnknown(){return this.filters.push({productName:{$isNull:!0}}),this}withProductNameNotContaining(t){return this.filters.push({productName:{$notContains:t}}),this}withProductNameStartingWith(t){return this.filters.push({productName:{$startsWith:t}}),this}withProductNameNotStartingWith(t){return this.filters.push({productName:{$notStartsWith:t}}),this}withProductNameEndingWith(t){return this.filters.push({productName:{$endsWith:t}}),this}withProductNameNotEndingWith(t){return this.filters.push({productName:{$notEndsWith:t}}),this}withProductNameSoundingLike(t){return this.filters.push({productName:{$soundLike:t}}),this}withQuantityIs(t){return this.filters.push({quantity:{$eq:t}}),this}withQuantityIsNot(t){return this.filters.push({quantity:{$ne:t}}),this}withQuantityIn(...t){return this.filters.push({quantity:{$in:t}}),this}withQuantityNotIn(...t){return this.filters.push({quantity:{$notIn:t}}),this}withQuantityGreaterThan(t){return this.filters.push({quantity:{$gt:t}}),this}withQuantityGreaterThanOrEqualTo(t){return this.filters.push({quantity:{$gte:t}}),this}withQuantityLessThan(t){return this.filters.push({quantity:{$lt:t}}),this}withQuantityLessThanOrEqualTo(t){return this.filters.push({quantity:{$lte:t}}),this}withQuantityBetween(t,e){return this.filters.push({quantity:{$between:[t,e]}}),this}withQuantityIsKnown(){return this.filters.push({quantity:{$isNull:!1}}),this}withQuantityIsUnknown(){return this.filters.push({quantity:{$isNull:!0}}),this}withUnitPriceIs(t){return this.filters.push({unitPrice:{$eq:t}}),this}withUnitPriceIsNot(t){return this.filters.push({unitPrice:{$ne:t}}),this}withUnitPriceIn(...t){return this.filters.push({unitPrice:{$in:t}}),this}withUnitPriceNotIn(...t){return this.filters.push({unitPrice:{$notIn:t}}),this}withUnitPriceGreaterThan(t){return this.filters.push({unitPrice:{$gt:t}}),this}withUnitPriceGreaterThanOrEqualTo(t){return this.filters.push({unitPrice:{$gte:t}}),this}withUnitPriceLessThan(t){return this.filters.push({unitPrice:{$lt:t}}),this}withUnitPriceLessThanOrEqualTo(t){return this.filters.push({unitPrice:{$lte:t}}),this}withUnitPriceBetween(t,e){return this.filters.push({unitPrice:{$between:[t,e]}}),this}withUnitPriceIsKnown(){return this.filters.push({unitPrice:{$isNull:!1}}),this}withUnitPriceIsUnknown(){return this.filters.push({unitPrice:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByProductNameAscending(){return this.query.orderBy("productName","asc"),this}orderByProductNameDescending(){return this.query.orderBy("productName","desc"),this}orderByQuantityAscending(){return this.query.orderBy("quantity","asc"),this}orderByQuantityDescending(){return this.query.orderBy("quantity","desc"),this}orderByUnitPriceAscending(){return this.query.orderBy("unitPrice","asc"),this}orderByUnitPriceDescending(){return this.query.orderBy("unitPrice","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minQuantity(){return this.minQuantityAs("minOfQuantity")}minQuantityAs(t){return this.query.aggregate("min","quantity",t),this}maxQuantity(){return this.maxQuantityAs("maxOfQuantity")}maxQuantityAs(t){return this.query.aggregate("max","quantity",t),this}sumQuantity(){return this.sumQuantityAs("sumOfQuantity")}sumQuantityAs(t){return this.query.aggregate("sum","quantity",t),this}avgQuantity(){return this.avgQuantityAs("avgOfQuantity")}avgQuantityAs(t){return this.query.aggregate("avg","quantity",t),this}standardDeviationQuantity(){return this.standardDeviationQuantityAs("standardDeviationOfQuantity")}standardDeviationQuantityAs(t){return this.query.aggregate("stddev","quantity",t),this}squareRootOfPopulationStandardDeviationQuantity(){return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity")}squareRootOfPopulationStandardDeviationQuantityAs(t){return this.query.aggregate("stddev_pop","quantity",t),this}sampleVarianceQuantity(){return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity")}sampleVarianceQuantityAs(t){return this.query.aggregate("var_samp","quantity",t),this}samplePopulationVarianceQuantity(){return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity")}samplePopulationVarianceQuantityAs(t){return this.query.aggregate("var_pop","quantity",t),this}minUnitPrice(){return this.minUnitPriceAs("minOfUnitPrice")}minUnitPriceAs(t){return this.query.aggregate("min","unitPrice",t),this}maxUnitPrice(){return this.maxUnitPriceAs("maxOfUnitPrice")}maxUnitPriceAs(t){return this.query.aggregate("max","unitPrice",t),this}sumUnitPrice(){return this.sumUnitPriceAs("sumOfUnitPrice")}sumUnitPriceAs(t){return this.query.aggregate("sum","unitPrice",t),this}avgUnitPrice(){return this.avgUnitPriceAs("avgOfUnitPrice")}avgUnitPriceAs(t){return this.query.aggregate("avg","unitPrice",t),this}standardDeviationUnitPrice(){return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice")}standardDeviationUnitPriceAs(t){return this.query.aggregate("stddev","unitPrice",t),this}squareRootOfPopulationStandardDeviationUnitPrice(){return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice")}squareRootOfPopulationStandardDeviationUnitPriceAs(t){return this.query.aggregate("stddev_pop","unitPrice",t),this}sampleVarianceUnitPrice(){return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice")}sampleVarianceUnitPriceAs(t){return this.query.aggregate("var_samp","unitPrice",t),this}samplePopulationVarianceUnitPrice(){return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice")}samplePopulationVarianceUnitPriceAs(t){return this.query.aggregate("var_pop","unitPrice",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomerOrder(){return this.query.groupBy("customerOrder"),this}groupByCustomerOrderAs(t){return this.query.groupBy("customerOrder"),this}groupByProductName(){return this.query.groupBy("productName"),this}groupByProductNameAs(t){return this.query.groupBy("productName"),this}groupByQuantity(){return this.query.groupBy("quantity"),this}groupByQuantityAs(t){return this.query.groupBy("quantity"),this}groupByUnitPrice(){return this.query.groupBy("unitPrice"),this}groupByUnitPriceAs(t){return this.query.groupBy("unitPrice"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerOrderAs(t,e,r=!0){return this.query.facetBy(t,"customerOrder",e,r,{kind:"facet",method:"facetByCustomerOrderAs",relation:"customerOrder",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof B?o:B.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof B?u:B.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof B?o:B.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class _t{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new B}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class E{static platforms(){return new st(!1)}static platformsWithMinimalFields(){return new st(!0)}static orderStatuses(){return new ot(!1)}static orderStatusesWithMinimalFields(){return new ot(!0)}static customers(){return new nt(!1)}static customersWithMinimalFields(){return new nt(!0)}static customerOrders(){return new at(!1)}static customerOrdersWithMinimalFields(){return new at(!0)}static orderItems(){return new ut(!1)}static orderItemsWithMinimalFields(){return new ut(!0)}}class I extends Error{constructor(t,e,r){const i=`select${r.charAt(0).toUpperCase()}${r.slice(1)}(...)`,s={error:"TeaQLNotLoadedError",root:t,accessPath:e.split("."),breakPoint:r,missingPreload:[r],suggestedFix:i,severity:"error",humanMessage:`访问 ${t}.${e} 时缺少预加载。请在查询中加入 ${i}`};super(JSON.stringify(s)),this.root=t,this.accessPath=e,this.breakPoint=r,this.name="TeaQLNotLoadedError",this.details=s}root;accessPath;breakPoint;details}function q(d,t){return d?`${d}.${t}`:t}class n{constructor(t,e=!0,r){this.value=t,this.present=e,this.notLoaded=r}value;present;notLoaded;static missing(){return new n(void 0,!1)}static notLoaded(t){return new n(void 0,!1,t)}eval(){if(this.notLoaded)throw this.notLoaded;return this.present?this.value:void 0}isPresent(){if(this.notLoaded)throw this.notLoaded;return this.present}orElse(t){const e=this.eval();return this.present&&e!=null?e:t}}class x{constructor(t,e="Platform(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}orderStatusList(){const t=q(this.path,"orderStatusList");return this.notLoaded?new U([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderStatusList")?new U(this.value.orderStatusList(),this.root,t):new U([],this.root,t,!1,new I(this.root,t,"orderStatusList")):U.missing(this.root,t)}customerList(){const t=q(this.path,"customerList");return this.notLoaded?new M([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerList")?new M(this.value.customerList(),this.root,t):new M([],this.root,t,!1,new I(this.root,t,"customerList")):M.missing(this.root,t)}}class V{constructor(t,e="OrderStatus(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}code(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"code");return this.value.isLoaded("code")?new n(this.value.code):n.notLoaded(new I(this.root,t,"code"))}color(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"color");return this.value.isLoaded("color")?new n(this.value.color):n.notLoaded(new I(this.root,t,"color"))}displayOrder(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"displayOrder");return this.value.isLoaded("displayOrder")?new n(this.value.displayOrder):n.notLoaded(new I(this.root,t,"displayOrder"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class W{constructor(t,e="Customer(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class K{constructor(t,e="CustomerOrder(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}orderNumber(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderNumber");return this.value.isLoaded("orderNumber")?new n(this.value.orderNumber):n.notLoaded(new I(this.root,t,"orderNumber"))}orderDate(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderDate");return this.value.isLoaded("orderDate")?new n(this.value.orderDate):n.notLoaded(new I(this.root,t,"orderDate"))}totalAmount(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"totalAmount");return this.value.isLoaded("totalAmount")?new n(this.value.totalAmount):n.notLoaded(new I(this.root,t,"totalAmount"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customer");if(!this.value.isLoaded("customer"))return n.notLoaded(new I(this.root,t,"customer"));const e=this.value.customer;return new n(e instanceof Q?e.id:e)}statusId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"status");if(!this.value.isLoaded("status"))return n.notLoaded(new I(this.root,t,"status"));const e=this.value.status;return new n(e instanceof S?e.id:e)}customer(){const t=q(this.path,"customer");if(this.notLoaded)return new W(void 0,this.root,t,this.notLoaded);if(!this.value)return new W(void 0,this.root,t);if(!this.value.isLoaded("customer"))return new W(void 0,this.root,t,new I(this.root,t,"customer"));const e=this.value.customer,r=e==null?void 0:e instanceof Q?e:Q.fromRecord({id:e});return new W(r,this.root,t)}status(){const t=q(this.path,"status");if(this.notLoaded)return new V(void 0,this.root,t,this.notLoaded);if(!this.value)return new V(void 0,this.root,t);if(!this.value.isLoaded("status"))return new V(void 0,this.root,t,new I(this.root,t,"status"));const e=this.value.status,r=e==null?void 0:e instanceof S?e:S.fromRecord({id:e});return new V(r,this.root,t)}orderItemList(){const t=q(this.path,"orderItemList");return this.notLoaded?new j([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderItemList")?new j(this.value.orderItemList(),this.root,t):new j([],this.root,t,!1,new I(this.root,t,"orderItemList")):j.missing(this.root,t)}}class H{constructor(t,e="OrderItem(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}productName(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"productName");return this.value.isLoaded("productName")?new n(this.value.productName):n.notLoaded(new I(this.root,t,"productName"))}quantity(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"quantity");return this.value.isLoaded("quantity")?new n(this.value.quantity):n.notLoaded(new I(this.root,t,"quantity"))}unitPrice(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"unitPrice");return this.value.isLoaded("unitPrice")?new n(this.value.unitPrice):n.notLoaded(new I(this.root,t,"unitPrice"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerOrderId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customerOrder");if(!this.value.isLoaded("customerOrder"))return n.notLoaded(new I(this.root,t,"customerOrder"));const e=this.value.customerOrder;return new n(e instanceof $?e.id:e)}customerOrder(){const t=q(this.path,"customerOrder");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded);if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("customerOrder"))return new K(void 0,this.root,t,new I(this.root,t,"customerOrder"));const e=this.value.customerOrder,r=e==null?void 0:e instanceof $?e:$.fromRecord({id:e});return new K(r,this.root,t)}}class U{constructor(t,e="OrderStatus(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new U([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new V(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new V(void 0,this.root,e):new V(this.items[t],this.root,e)}}class M{constructor(t,e="Customer(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new M([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new W(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new W(void 0,this.root,e):new W(this.items[t],this.root,e)}}class k{constructor(t,e="CustomerOrder(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new k([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new K(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new K(void 0,this.root,e):new K(this.items[t],this.root,e)}}class j{constructor(t,e="OrderItem(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new j([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new H(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new H(void 0,this.root,e):new H(this.items[t],this.root,e)}}class et{static platform(t){return new x(t,`Platform(id=${t?.id??"null"})`)}static orderStatus(t){return new V(t,`OrderStatus(id=${t?.id??"null"})`)}static customer(t){return new W(t,`Customer(id=${t?.id??"null"})`)}static customerOrder(t){return new K(t,`CustomerOrder(id=${t?.id??"null"})`)}static orderItem(t){return new H(t,`OrderItem(id=${t?.id??"null"})`)}}const ht={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{orderStatusList:{targetEntity:"OrderStatus",localKey:"id",foreignKey:"platform",many:!0},customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platform",many:!0}}},OrderStatus:{table:"order_status_data",auditMaskFields:[],columns:{platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},code:{columnName:"code",modelName:"code",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},color:{columnName:"color",modelName:"color",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},displayOrder:{columnName:"display_order",modelName:"display_order",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},Customer:{table:"customer_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customer",many:!0}}},CustomerOrder:{table:"customer_order_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customer:{columnName:"customer",modelName:"customer",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},status:{columnName:"status",modelName:"status",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},orderNumber:{columnName:"order_number",modelName:"order_number",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},orderDate:{columnName:"order_date",modelName:"order_date",logPolicy:"plain",logicalType:"date",decode:"date",nullable:!1},totalAmount:{columnName:"total_amount",modelName:"total_amount",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customer:{targetEntity:"Customer",localKey:"customer",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},orderItemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"customerOrder",many:!0}}},OrderItem:{table:"order_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customerOrder:{columnName:"customer_order",modelName:"customer_order",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},productName:{columnName:"product_name",modelName:"product_name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},quantity:{columnName:"quantity",modelName:"quantity",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},unitPrice:{columnName:"unit_price",modelName:"unit_price",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customerOrder:{targetEntity:"CustomerOrder",localKey:"customerOrder",foreignKey:"id",many:!1}}}};async function Ct(d){let t=(await E.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];t||(t=N.teaqlBootstrapNew("1"),t.updateName("Commerce Test Platform"),await t.auditAs("create generated Domain Root Platform").save(d)),d.withActiveRoot({entity:"Platform",id:t.id});let e=(await E.orderStatuses().withIdIs("1001").comment("what: locate generated constant OrderStatus(1001)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!e)e=S.teaqlBootstrapNew("1001"),e.updatePlatform(t),e.updateName("New"),e.updateCode("NEW"),e.updateColor("#94A3B8"),e.updateDisplayOrder(1),await e.auditAs("create model constant OrderStatus(1001)").save(d);else{let s=!1;String(e.platform?.id??e.platform)!==String(t.id)&&(e.updatePlatform(t),s=!0),e.name!=="New"&&(e.updateName("New"),s=!0),e.code!=="NEW"&&(e.updateCode("NEW"),s=!0),e.color!=="#94A3B8"&&(e.updateColor("#94A3B8"),s=!0),e.displayOrder!==1&&(e.updateDisplayOrder(1),s=!0),s&&await e.auditAs("reconcile model constant OrderStatus(1001)").save(d)}let r=(await E.orderStatuses().withIdIs("1002").comment("what: locate generated constant OrderStatus(1002)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!r)r=S.teaqlBootstrapNew("1002"),r.updatePlatform(t),r.updateName("Paid"),r.updateCode("PAID"),r.updateColor("#22C55E"),r.updateDisplayOrder(2),await r.auditAs("create model constant OrderStatus(1002)").save(d);else{let s=!1;String(r.platform?.id??r.platform)!==String(t.id)&&(r.updatePlatform(t),s=!0),r.name!=="Paid"&&(r.updateName("Paid"),s=!0),r.code!=="PAID"&&(r.updateCode("PAID"),s=!0),r.color!=="#22C55E"&&(r.updateColor("#22C55E"),s=!0),r.displayOrder!==2&&(r.updateDisplayOrder(2),s=!0),s&&await r.auditAs("reconcile model constant OrderStatus(1002)").save(d)}let i=(await E.orderStatuses().withIdIs("1003").comment("what: locate generated constant OrderStatus(1003)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!i)i=S.teaqlBootstrapNew("1003"),i.updatePlatform(t),i.updateName("Cancelled"),i.updateCode("CANCELLED"),i.updateColor("#EF4444"),i.updateDisplayOrder(3),await i.auditAs("create model constant OrderStatus(1003)").save(d);else{let s=!1;String(i.platform?.id??i.platform)!==String(t.id)&&(i.updatePlatform(t),s=!0),i.name!=="Cancelled"&&(i.updateName("Cancelled"),s=!0),i.code!=="CANCELLED"&&(i.updateCode("CANCELLED"),s=!0),i.color!=="#EF4444"&&(i.updateColor("#EF4444"),s=!0),i.displayOrder!==3&&(i.updateDisplayOrder(3),s=!0),s&&await i.auditAs("reconcile model constant OrderStatus(1003)").save(d)}}const Pt=new pt(ht,{Platform:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},OrderStatus:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100}),(t.action==="Create"&&t.payload.code===void 0||t.payload.code===null)&&e.push({ruleId:"required",location:w.property("code")}),t.payload.code!=null&&[...String(t.payload.code)].length>100&&e.push({ruleId:"max_length",location:w.property("code"),inputValue:t.payload.code,systemValue:100}),(t.action==="Create"&&t.payload.color===void 0||t.payload.color===null)&&e.push({ruleId:"required",location:w.property("color")}),t.payload.color!=null&&[...String(t.payload.color)].length>100&&e.push({ruleId:"max_length",location:w.property("color"),inputValue:t.payload.color,systemValue:100}),(t.action==="Create"&&t.payload.display_order===void 0||t.payload.display_order===null)&&e.push({ruleId:"required",location:w.property("display_order")})}},Customer:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},CustomerOrder:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer===void 0||t.payload.customer===null)&&e.push({ruleId:"required",location:w.property("customer")}),(t.action==="Create"&&t.payload.status===void 0||t.payload.status===null)&&e.push({ruleId:"required",location:w.property("status")}),(t.action==="Create"&&t.payload.order_number===void 0||t.payload.order_number===null)&&e.push({ruleId:"required",location:w.property("order_number")}),t.payload.order_number!=null&&[...String(t.payload.order_number)].length>100&&e.push({ruleId:"max_length",location:w.property("order_number"),inputValue:t.payload.order_number,systemValue:100}),(t.action==="Create"&&t.payload.order_date===void 0||t.payload.order_date===null)&&e.push({ruleId:"required",location:w.property("order_date")}),(t.action==="Create"&&t.payload.total_amount===void 0||t.payload.total_amount===null)&&e.push({ruleId:"required",location:w.property("total_amount")})}},OrderItem:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer_order===void 0||t.payload.customer_order===null)&&e.push({ruleId:"required",location:w.property("customer_order")}),(t.action==="Create"&&t.payload.product_name===void 0||t.payload.product_name===null)&&e.push({ruleId:"required",location:w.property("product_name")}),t.payload.product_name!=null&&[...String(t.payload.product_name)].length>100&&e.push({ruleId:"max_length",location:w.property("product_name"),inputValue:t.payload.product_name,systemValue:100}),(t.action==="Create"&&t.payload.quantity===void 0||t.payload.quantity===null)&&e.push({ruleId:"required",location:w.property("quantity")}),(t.action==="Create"&&t.payload.unit_price===void 0||t.payload.unit_price===null)&&e.push({ruleId:"required",location:w.property("unit_price")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Commerce Test Platform"}},constants:[{entity:"OrderStatus",id:"1001",values:{platform:"1",name:"New",code:"NEW",color:"#94A3B8",displayOrder:1}},{entity:"OrderStatus",id:"1002",values:{platform:"1",name:"Paid",code:"PAID",color:"#22C55E",displayOrder:2}},{entity:"OrderStatus",id:"1003",values:{platform:"1",name:"Cancelled",code:"CANCELLED",color:"#EF4444",displayOrder:3}}],ensure:Ct}),it=document.querySelector("#status"),St=document.querySelector("#result"),Nt=document.querySelector("#trace"),$t=document.querySelector("#sql"),bt=document.querySelector("#evidence-rows"),Z=document.querySelector("#persist"),dt=document.querySelector("#logging"),rt=document.querySelector("#reset"),Y=document.querySelector("#query"),lt=document.querySelector("#search"),Tt={filter:{orderNumber:{$contains:"KEEP"}}};let R;Z.checked=localStorage.getItem("teaql-browser-order-storage")==="opfs";async function Qt(d){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await ft.open(t,{...ht},{storage:d,databaseName:"teaql-browser-orders.sqlite3"});e.install(Pt),e.setDiagnosticSQLLogSink(void 0).setMutationLoggingEnabled(!1);const r=Object.freeze({policyId:"browser-order-seed",version:"1",fingerprint:"sha256:browser-order-seed-v1"}),i=new gt().insertResource("dataService",e).withMutationPolicyRegistry(new Ot(()=>({identity:r,review:(s,h)=>h.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new wt(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(i),await i.ensureSchema(),await i.ensureSchema(),{client:e,context:i,evidence:new qt,diagnostics:[]}}async function ct({context:d}){if((await E.customerOrdersWithMinimalFields().limit(1).comment("detect existing order demo").purpose("keep mutation seeding idempotent").executeForList(d)).length)return;const e=(await E.platforms().limit(2).comment("load bootstrap platform").purpose("prepare order demo").executeForList(d))[0],r=E.customers().comment("initialize demo customer").purpose("prepare order demo").newEntity(d);r.updateName("North Star Retail").updatePlatform(e.id),await r.auditAs("seed browser order customer").save(d);for(let i=1;i<=4;i++){const s=E.customerOrders().comment("initialize demo order").purpose("prepare order demo").newEntity(d);s.updateCustomer(r.id).updateOrderNumber(i<4?`KEEP-00${i}`:"DROP-004").updateOrderDate(`2026-10-0${i}`).updateTotalAmount(i<4?i*100:900),i===1?s.updateStatusToNew():s.updateStatusToPaid(),await s.auditAs("seed browser order").save(d);for(let h=1;h<=5;h++){const o=E.orderItems().comment("initialize demo item").purpose("prepare item previews").newEntity(d);o.updateCustomerOrder(s.id).updateProductName(`Box ${h}`).updateQuantity(h).updateUnitPrice(20),await o.auditAs("seed browser order item").save(d)}}}async function tt(d){const t=JSON.parse(lt.value),e=E.customerOrdersWithMinimalFields().filterByJson(t);d.evidence.enableAll(),d.diagnostics.length=0,d.client.setRuntimeTelemetrySink(d.evidence).setQueryLoggingEnabled(dt.checked).setDiagnosticSQLLogSink({write:o=>d.diagnostics.push(o)});const r=await e.countAs("totalOrders").facetByStatusAs("statusCounts",E.orderStatusesWithMinimalFields().selectName().selectColor().countAs("orderCount").sumTotalAmountOfCustomerOrdersAs("orderTotalAmount",E.customerOrdersWithMinimalFields()).orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(E.orderStatusesWithMinimalFields().selectName().selectColor().comment("load status")).selectOrderItemListWith(E.orderItemsWithMinimalFields().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countOrderItemsAs("itemCount").orderByOrderDateDescending().orderByIdDescending().offset(1).limit(1).comment("load order list").purpose("render order list page").executeForList(d.context),i={data:r.data.map(o=>{const p=et.customerOrder(o),l=p.orderItemList().size().eval();if(l==null)throw new Error("Selected item list unexpectedly has a null size");return{id:o.id,version:o.version,orderNumber:p.orderNumber().eval(),orderDate:p.orderDate().eval(),status:{name:p.status().name().eval(),color:p.status().color().eval()},items:Array.from({length:l},(a,u)=>({productName:p.orderItemList().get(u).productName().eval(),quantity:p.orderItemList().get(u).quantity().eval()})),itemCount:o.itemCount}}),metadata:{totalCount:r.totalCount,pageOffset:1,pageSize:1,aggregations:r.data.aggregations,searchWarnings:e.dynamicSearchWarnings},facets:{statusCounts:r.data.facets.statusCounts.map(o=>({id:o.id,name:et.orderStatus(S.fromRecord(o)).name().eval(),color:et.orderStatus(S.fromRecord(o)).color().eval(),orderCount:o.orderCount,orderTotalAmount:o.orderTotalAmount}))}};St.textContent=JSON.stringify(i,null,2);const s=d.evidence.snapshot(),h=s.map(o=>{const p=o.traceChain??[],l=p.filter(m=>m.kind==="purpose"),a=l.length===1?`${l[0].detail}: ${p.filter(m=>m.kind==="comment").map(m=>m.detail).join(" → ")}`:"TraceChain unavailable",u=document.createElement("tr");for(const m of[`${o.elapsedMicros} µs`,o.tracePath.find(C=>C.kind==="request")?.name??"—",a,o.debugSQL]){const C=document.createElement("td");C.textContent=m,u.append(C)}return{row:u,businessTrace:a}});bt.replaceChildren(...h.map(o=>o.row)),Nt.textContent=h.map(o=>o.businessTrace).join(` +import{S as yt,a as A,L as v,M as b,C as L,d as G,e as F,Q as z,R as pt,B as ft,U as gt,D as Ot,c as wt,b as qt}from"./dynamic-search-Ch_QcWVU.js";import{E as T,O as w}from"./object-location-CJfVWqJC.js";/* empty css */class c extends yt{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,r="id",i="id",s=!0,h){return super.relationQuery(t,e,r,i,s,h)}}class Q{static teaqlTemporaryId=0;id;platform;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--Q.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Customer",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new Q(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new Q({id:String(t)})}static teaqlBootstrapNew(t){return new Q().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Customer",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.customer;(this.id===void 0||!a.isLoaded("customer")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomer(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Customer",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.customer;(this.id===void 0||!y.isLoaded("customer")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomer(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.customer;(this.id===void 0||!g.isLoaded("customer")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomer(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,platform:this.platform,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class B{static teaqlTemporaryId=0;id;customerOrder;productName;quantity;unitPrice;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--B.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const r={...t};Object.assign(this,r),t.customerOrder&&typeof t.customerOrder=="object"&&(this.customerOrder=t.customerOrder instanceof $?t.customerOrder:$.fromRecord(t.customerOrder),this.markLoaded("customerOrder"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const r=new B(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new B({id:String(t)})}static teaqlBootstrapNew(t){return new B().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const p=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(l=>!this.isLoaded(l.member));if(p)throw new L([{ruleId:"invalid_type",location:w.property(p.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o),o.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderItem",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return p.scopeFor(this.teaqlEntityKey()),this;const l=await e.executeMutation(p);for(const[C,f]of Object.entries(o.payload))C!=="id"&&C!=="version"&&this._root.set(this.teaqlEntityKey(),C,f);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();return this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update"),p.scopeFor(m),e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer_order:this.customerOrder,product_name:this.productName,quantity:this.quantity,unit_price:this.unitPrice,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateProductName(t){return this.productName=t,this.markLoaded("productName"),this._root.set(this.teaqlEntityKey(),"product_name",t),this}updateQuantity(t){return this.quantity=t,this.markLoaded("quantity"),this._root.set(this.teaqlEntityKey(),"quantity",t),this}updateUnitPrice(t){return this.unitPrice=t,this.markLoaded("unitPrice"),this._root.set(this.teaqlEntityKey(),"unit_price",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomerOrder(t){return this.customerOrder=t?.id??t,this.markLoaded("customerOrder"),this._root.set(this.teaqlEntityKey(),"customer_order",this.customerOrder),this}}class ${static teaqlTemporaryId=0;id;customer;status;orderNumber;orderDate;totalAmount;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--$.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderItemList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderItemList,Object.assign(this,r),t.customer&&typeof t.customer=="object"&&(this.customer=t.customer instanceof Q?t.customer:Q.fromRecord(t.customer),this.markLoaded("customer")),t.status&&typeof t.status=="object"&&(this.status=t.status instanceof S?t.status:S.fromRecord(t.status),this.markLoaded("status")),Array.isArray(t.orderItemList)){const i=t.orderItemList;this._orderItemList=new A(i.map(s=>s instanceof B?s:B.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"CustomerOrder",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new $(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new $({id:String(t)})}static teaqlBootstrapNew(t){return new $().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"CustomerOrder",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderItemList.entries()){a.teaqlAttachRoot(this._root);const u=a.customerOrder;(this.id===void 0||!a.isLoaded("customerOrder")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomerOrder(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_item_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"CustomerOrder",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderItemList.entries()){y.teaqlAttachRoot(this._root);const O=y.customerOrder;(this.id===void 0||!y.isLoaded("customerOrder")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomerOrder(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_item_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderItemList.entries()){g.teaqlAttachRoot(this._root);const y=g.customerOrder;(this.id===void 0||!g.isLoaded("customerOrder")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomerOrder(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_item_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer:this.customer,status:this.status,order_number:this.orderNumber,order_date:this.orderDate,total_amount:this.totalAmount,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateOrderNumber(t){return this.orderNumber=t,this.markLoaded("orderNumber"),this._root.set(this.teaqlEntityKey(),"order_number",t),this}updateOrderDate(t){return this.orderDate=t,this.markLoaded("orderDate"),this._root.set(this.teaqlEntityKey(),"order_date",t),this}updateTotalAmount(t){return this.totalAmount=t,this.markLoaded("totalAmount"),this._root.set(this.teaqlEntityKey(),"total_amount",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomer(t){return this.customer=t?.id??t,this.markLoaded("customer"),this._root.set(this.teaqlEntityKey(),"customer",this.customer),this}updateStatus(t){return this.status=t?.id??t,this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToNew(){return this.status="1001",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToPaid(){return this.status="1002",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToCancelled(){return this.status="1003",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}orderItemList(){return this._orderItemList}}class S{static teaqlTemporaryId=0;platform;id;name;code;color;displayOrder;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--S.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderStatus",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new S(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new S({id:String(t)})}static teaqlBootstrapNew(t){return new S().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderStatus",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.status;(this.id===void 0||!a.isLoaded("status")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateStatus(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderStatus",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.status;(this.id===void 0||!y.isLoaded("status")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateStatus(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.status;(this.id===void 0||!g.isLoaded("status")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateStatus(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{platform:this.platform,id:this.id,name:this.name,code:this.code,color:this.color,display_order:this.displayOrder,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateCode(t){return this.code=t,this.markLoaded("code"),this._root.set(this.teaqlEntityKey(),"code",t),this}updateColor(t){return this.color=t,this.markLoaded("color"),this._root.set(this.teaqlEntityKey(),"color",t),this}updateDisplayOrder(t){return this.displayOrder=t,this.markLoaded("displayOrder"),this._root.set(this.teaqlEntityKey(),"display_order",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class N{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--N.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderStatusList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderStatusList,delete r.customerList,Object.assign(this,r),Array.isArray(t.orderStatusList)){const i=t.orderStatusList;this._orderStatusList=new A(i.map(s=>s instanceof S?s:S.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderStatusList")}if(Array.isArray(t.customerList)){const i=t.customerList;this._customerList=new A(i.map(s=>s instanceof Q?s:Q.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderStatusList)e.teaqlAttachRoot(t);for(const e of this._customerList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new N(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new N({id:String(t)})}static teaqlBootstrapNew(t){return new N().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderStatusList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_status_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}for(const[l,a]of this._customerList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Platform",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderStatusList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_status_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}for(const[g,y]of this._customerList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderStatusList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_status_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}for(const[f,g]of this._customerList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}orderStatusList(){return this._orderStatusList}customerList(){return this._customerList}}const J=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({orderStatusList:"OrderStatus",customerList:"Customer"})}),OrderStatus:Object.freeze({fields:Object.freeze({platform:"integer",id:"integer",name:"string",code:"string",color:"string",display_order:"integer",displayOrder:"integer",version:"integer"}),queryFields:Object.freeze({platform:"platform",id:"id",name:"name",code:"code",color:"color",display_order:"displayOrder",displayOrder:"displayOrder",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),Customer:Object.freeze({fields:Object.freeze({id:"integer",platform:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",platform:"platform",name:"name",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),CustomerOrder:Object.freeze({fields:Object.freeze({id:"integer",customer:"integer",status:"integer",order_number:"string",orderNumber:"string",order_date:"date",orderDate:"date",total_amount:"decimal",totalAmount:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer:"customer",status:"status",order_number:"orderNumber",orderNumber:"orderNumber",order_date:"orderDate",orderDate:"orderDate",total_amount:"totalAmount",totalAmount:"totalAmount",version:"version"}),relations:Object.freeze({customer:"Customer",status:"OrderStatus",orderItemList:"OrderItem"})}),OrderItem:Object.freeze({fields:Object.freeze({id:"integer",customer_order:"integer",customerOrder:"integer",product_name:"string",productName:"string",quantity:"integer",unit_price:"decimal",unitPrice:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer_order:"customerOrder",customerOrder:"customerOrder",product_name:"productName",productName:"productName",quantity:"quantity",unit_price:"unitPrice",unitPrice:"unitPrice",version:"version"}),relations:Object.freeze({customer_order:"CustomerOrder",customerOrder:"CustomerOrder"})})});class st{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new vt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectOrderStatusListWith(t){return this.query.relationQuery("orderStatusList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectOrderStatusListWith",relation:"orderStatusList"}),this}selectCustomerListWith(t){return this.query.relationQuery("customerList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectCustomerListWith",relation:"customerList"}),this}haveOrderStatuses(){return this.withOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}haveNoOrderStatuses(){return this.withoutOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}withOrderStatusListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutOrderStatusListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}haveCustomers(){return this.withCustomerListMatching({toQuery:()=>new c("Customer")})}haveNoCustomers(){return this.withoutCustomerListMatching({toQuery:()=>new c("Customer")})}withCustomerListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutCustomerListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countOrderStatuses(){return this.countOrderStatusesAs("countOrderStatuses")}countOrderStatusesAs(t){const e=new c("OrderStatus").filter({version:{$gte:1}});return this.countOrderStatusesWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderStatusesAs",relation:"orderStatusList",alias:t},this}countOrderStatusesWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"relation-count",method:"countOrderStatusesWith",relation:"orderStatusList",alias:t}),this}minDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.minDisplayOrderOfOrderStatusesAs("minOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}minDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"minDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}maxDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.maxDisplayOrderOfOrderStatusesAs("maxOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}maxDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"maxDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sumDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sumDisplayOrderOfOrderStatusesAs("sumOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sumDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sumDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}avgDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.avgDisplayOrderOfOrderStatusesAs("avgOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}avgDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"avgDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}standardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.standardDeviationDisplayOrderOfOrderStatusesAs("standardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}standardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"standardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs("squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sampleVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sampleVarianceDisplayOrderOfOrderStatusesAs("sampleVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sampleVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sampleVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}samplePopulationVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs("samplePopulationVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}samplePopulationVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}countCustomers(){return this.countCustomersAs("countCustomers")}countCustomersAs(t){const e=new c("Customer").filter({version:{$gte:1}});return this.countCustomersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomersAs",relation:"customerList",alias:t},this}countCustomersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerList",t,r,!0,{kind:"relation-count",method:"countCustomersWith",relation:"customerList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof N?o:N.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof N?u:N.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof N?o:N.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class vt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new N}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ot{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderStatus"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new It(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["platform","id","name","code","color","displayOrder","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectCode(){return this.query.select(["code"]),this}selectColor(){return this.query.select(["color"]),this}selectDisplayOrder(){return this.query.select(["displayOrder"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","status",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"status"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"status"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withCodeContaining(t){return this.filters.push({code:{$contains:t}}),this}withCodeIs(t){return this.filters.push({code:{$eq:t}}),this}withCodeIsNot(t){return this.filters.push({code:{$ne:t}}),this}withCodeIn(...t){return this.filters.push({code:{$in:t}}),this}withCodeNotIn(...t){return this.filters.push({code:{$notIn:t}}),this}withCodeGreaterThan(t){return this.filters.push({code:{$gt:t}}),this}withCodeGreaterThanOrEqualTo(t){return this.filters.push({code:{$gte:t}}),this}withCodeLessThan(t){return this.filters.push({code:{$lt:t}}),this}withCodeLessThanOrEqualTo(t){return this.filters.push({code:{$lte:t}}),this}withCodeBetween(t,e){return this.filters.push({code:{$between:[t,e]}}),this}withCodeIsKnown(){return this.filters.push({code:{$isNull:!1}}),this}withCodeIsUnknown(){return this.filters.push({code:{$isNull:!0}}),this}withCodeNotContaining(t){return this.filters.push({code:{$notContains:t}}),this}withCodeStartingWith(t){return this.filters.push({code:{$startsWith:t}}),this}withCodeNotStartingWith(t){return this.filters.push({code:{$notStartsWith:t}}),this}withCodeEndingWith(t){return this.filters.push({code:{$endsWith:t}}),this}withCodeNotEndingWith(t){return this.filters.push({code:{$notEndsWith:t}}),this}withCodeSoundingLike(t){return this.filters.push({code:{$soundLike:t}}),this}withColorContaining(t){return this.filters.push({color:{$contains:t}}),this}withColorIs(t){return this.filters.push({color:{$eq:t}}),this}withColorIsNot(t){return this.filters.push({color:{$ne:t}}),this}withColorIn(...t){return this.filters.push({color:{$in:t}}),this}withColorNotIn(...t){return this.filters.push({color:{$notIn:t}}),this}withColorGreaterThan(t){return this.filters.push({color:{$gt:t}}),this}withColorGreaterThanOrEqualTo(t){return this.filters.push({color:{$gte:t}}),this}withColorLessThan(t){return this.filters.push({color:{$lt:t}}),this}withColorLessThanOrEqualTo(t){return this.filters.push({color:{$lte:t}}),this}withColorBetween(t,e){return this.filters.push({color:{$between:[t,e]}}),this}withColorIsKnown(){return this.filters.push({color:{$isNull:!1}}),this}withColorIsUnknown(){return this.filters.push({color:{$isNull:!0}}),this}withColorNotContaining(t){return this.filters.push({color:{$notContains:t}}),this}withColorStartingWith(t){return this.filters.push({color:{$startsWith:t}}),this}withColorNotStartingWith(t){return this.filters.push({color:{$notStartsWith:t}}),this}withColorEndingWith(t){return this.filters.push({color:{$endsWith:t}}),this}withColorNotEndingWith(t){return this.filters.push({color:{$notEndsWith:t}}),this}withColorSoundingLike(t){return this.filters.push({color:{$soundLike:t}}),this}withDisplayOrderIs(t){return this.filters.push({displayOrder:{$eq:t}}),this}withDisplayOrderIsNot(t){return this.filters.push({displayOrder:{$ne:t}}),this}withDisplayOrderIn(...t){return this.filters.push({displayOrder:{$in:t}}),this}withDisplayOrderNotIn(...t){return this.filters.push({displayOrder:{$notIn:t}}),this}withDisplayOrderGreaterThan(t){return this.filters.push({displayOrder:{$gt:t}}),this}withDisplayOrderGreaterThanOrEqualTo(t){return this.filters.push({displayOrder:{$gte:t}}),this}withDisplayOrderLessThan(t){return this.filters.push({displayOrder:{$lt:t}}),this}withDisplayOrderLessThanOrEqualTo(t){return this.filters.push({displayOrder:{$lte:t}}),this}withDisplayOrderBetween(t,e){return this.filters.push({displayOrder:{$between:[t,e]}}),this}withDisplayOrderIsKnown(){return this.filters.push({displayOrder:{$isNull:!1}}),this}withDisplayOrderIsUnknown(){return this.filters.push({displayOrder:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByCodeAscending(){return this.query.orderBy("code","asc"),this}orderByCodeDescending(){return this.query.orderBy("code","desc"),this}orderByColorAscending(){return this.query.orderBy("color","asc"),this}orderByColorDescending(){return this.query.orderBy("color","desc"),this}orderByDisplayOrderAscending(){return this.query.orderBy("displayOrder","asc"),this}orderByDisplayOrderDescending(){return this.query.orderBy("displayOrder","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minDisplayOrder(){return this.minDisplayOrderAs("minOfDisplayOrder")}minDisplayOrderAs(t){return this.query.aggregate("min","displayOrder",t),this}maxDisplayOrder(){return this.maxDisplayOrderAs("maxOfDisplayOrder")}maxDisplayOrderAs(t){return this.query.aggregate("max","displayOrder",t),this}sumDisplayOrder(){return this.sumDisplayOrderAs("sumOfDisplayOrder")}sumDisplayOrderAs(t){return this.query.aggregate("sum","displayOrder",t),this}avgDisplayOrder(){return this.avgDisplayOrderAs("avgOfDisplayOrder")}avgDisplayOrderAs(t){return this.query.aggregate("avg","displayOrder",t),this}standardDeviationDisplayOrder(){return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder")}standardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev","displayOrder",t),this}squareRootOfPopulationStandardDeviationDisplayOrder(){return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder")}squareRootOfPopulationStandardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev_pop","displayOrder",t),this}sampleVarianceDisplayOrder(){return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder")}sampleVarianceDisplayOrderAs(t){return this.query.aggregate("var_samp","displayOrder",t),this}samplePopulationVarianceDisplayOrder(){return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder")}samplePopulationVarianceDisplayOrderAs(t){return this.query.aggregate("var_pop","displayOrder",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByCode(){return this.query.groupBy("code"),this}groupByCodeAs(t){return this.query.groupBy("code"),this}groupByColor(){return this.query.groupBy("color"),this}groupByColorAs(t){return this.query.groupBy("color"),this}groupByDisplayOrder(){return this.query.groupBy("displayOrder"),this}groupByDisplayOrderAs(t){return this.query.groupBy("displayOrder"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof S?o:S.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof S?u:S.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof S?o:S.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class It{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new S}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class nt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Customer"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Lt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","platform","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","customer",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customer"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customer"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof Q?o:Q.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof Q?u:Q.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof Q?o:Q.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class Lt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new Q}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class at{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("CustomerOrder"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new At(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customer","status","orderNumber","orderDate","totalAmount","version"]),this}selectId(){return this.query.select(["id"]),this}selectOrderNumber(){return this.query.select(["orderNumber"]),this}selectOrderDate(){return this.query.select(["orderDate"]),this}selectTotalAmount(){return this.query.select(["totalAmount"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerWith(t){return this.query.select(["customer"]),this.query.relationQuery("customer",t.toQuery(),"customer","id",!1,{kind:"relation-select",method:"selectCustomerWith",relation:"customer"}),this}selectStatusWith(t){return this.query.select(["status"]),this.query.relationQuery("status",t.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this}withCustomerMatching(t){return this.filters.push({customer:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerMatching(t){return this.filters.push({customer:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withStatusMatching(t){return this.filters.push({status:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutStatusMatching(t){return this.filters.push({status:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectOrderItemListWith(t){return this.query.relationQuery("orderItemList",t.toQuery(),"id","customerOrder",!0,{kind:"relation-select",method:"selectOrderItemListWith",relation:"orderItemList"}),this}haveOrderItems(){return this.withOrderItemListMatching({toQuery:()=>new c("OrderItem")})}haveNoOrderItems(){return this.withoutOrderItemListMatching({toQuery:()=>new c("OrderItem")})}withOrderItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}withoutOrderItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}countOrderItems(){return this.countOrderItemsAs("countOrderItems")}countOrderItemsAs(t){const e=new c("OrderItem").filter({version:{$gte:1}});return this.countOrderItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderItemsAs",relation:"orderItemList",alias:t},this}countOrderItemsWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"relation-count",method:"countOrderItemsWith",relation:"orderItemList",alias:t}),this}minQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minQuantityOfOrderItemsAs("minOfQuantityOfOrderItems",{toQuery:()=>t})}minQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxQuantityOfOrderItemsAs("maxOfQuantityOfOrderItems",{toQuery:()=>t})}maxQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumQuantityOfOrderItemsAs("sumOfQuantityOfOrderItems",{toQuery:()=>t})}sumQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgQuantityOfOrderItemsAs("avgOfQuantityOfOrderItems",{toQuery:()=>t})}avgQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationQuantityOfOrderItemsAs("standardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}standardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceQuantityOfOrderItemsAs("sampleVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}sampleVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceQuantityOfOrderItemsAs("samplePopulationVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}minUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minUnitPriceOfOrderItemsAs("minOfUnitPriceOfOrderItems",{toQuery:()=>t})}minUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxUnitPriceOfOrderItemsAs("maxOfUnitPriceOfOrderItems",{toQuery:()=>t})}maxUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumUnitPriceOfOrderItemsAs("sumOfUnitPriceOfOrderItems",{toQuery:()=>t})}sumUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgUnitPriceOfOrderItemsAs("avgOfUnitPriceOfOrderItems",{toQuery:()=>t})}avgUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationUnitPriceOfOrderItemsAs("standardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}standardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceUnitPriceOfOrderItemsAs("sampleVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}sampleVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceUnitPriceOfOrderItemsAs("samplePopulationVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomer(t){return this.filters.push({customer:{$eq:t}}),this}filterByCustomerIn(...t){return this.filters.push({customer:{$in:t}}),this}withCustomerIsKnown(){return this.filters.push({customer:{$isNull:!1}}),this}withCustomerIsUnknown(){return this.filters.push({customer:{$isNull:!0}}),this}filterByStatus(t){return this.filters.push({status:{$eq:t}}),this}filterByStatusIn(...t){return this.filters.push({status:{$in:t}}),this}withStatusIsKnown(){return this.filters.push({status:{$isNull:!1}}),this}withStatusIsUnknown(){return this.filters.push({status:{$isNull:!0}}),this}withStatusIsNew(){return this.filters.push({status:{$eq:"1001"}}),this}withStatusIsPaid(){return this.filters.push({status:{$eq:"1002"}}),this}withStatusIsCancelled(){return this.filters.push({status:{$eq:"1003"}}),this}withOrderNumberContaining(t){return this.filters.push({orderNumber:{$contains:t}}),this}withOrderNumberIs(t){return this.filters.push({orderNumber:{$eq:t}}),this}withOrderNumberIsNot(t){return this.filters.push({orderNumber:{$ne:t}}),this}withOrderNumberIn(...t){return this.filters.push({orderNumber:{$in:t}}),this}withOrderNumberNotIn(...t){return this.filters.push({orderNumber:{$notIn:t}}),this}withOrderNumberGreaterThan(t){return this.filters.push({orderNumber:{$gt:t}}),this}withOrderNumberGreaterThanOrEqualTo(t){return this.filters.push({orderNumber:{$gte:t}}),this}withOrderNumberLessThan(t){return this.filters.push({orderNumber:{$lt:t}}),this}withOrderNumberLessThanOrEqualTo(t){return this.filters.push({orderNumber:{$lte:t}}),this}withOrderNumberBetween(t,e){return this.filters.push({orderNumber:{$between:[t,e]}}),this}withOrderNumberIsKnown(){return this.filters.push({orderNumber:{$isNull:!1}}),this}withOrderNumberIsUnknown(){return this.filters.push({orderNumber:{$isNull:!0}}),this}withOrderNumberNotContaining(t){return this.filters.push({orderNumber:{$notContains:t}}),this}withOrderNumberStartingWith(t){return this.filters.push({orderNumber:{$startsWith:t}}),this}withOrderNumberNotStartingWith(t){return this.filters.push({orderNumber:{$notStartsWith:t}}),this}withOrderNumberEndingWith(t){return this.filters.push({orderNumber:{$endsWith:t}}),this}withOrderNumberNotEndingWith(t){return this.filters.push({orderNumber:{$notEndsWith:t}}),this}withOrderNumberSoundingLike(t){return this.filters.push({orderNumber:{$soundLike:t}}),this}withOrderDateIs(t){return this.filters.push({orderDate:{$eq:t}}),this}withOrderDateIsNot(t){return this.filters.push({orderDate:{$ne:t}}),this}withOrderDateIn(...t){return this.filters.push({orderDate:{$in:t}}),this}withOrderDateNotIn(...t){return this.filters.push({orderDate:{$notIn:t}}),this}withOrderDateGreaterThan(t){return this.filters.push({orderDate:{$gt:t}}),this}withOrderDateGreaterThanOrEqualTo(t){return this.filters.push({orderDate:{$gte:t}}),this}withOrderDateLessThan(t){return this.filters.push({orderDate:{$lt:t}}),this}withOrderDateLessThanOrEqualTo(t){return this.filters.push({orderDate:{$lte:t}}),this}withOrderDateBetween(t,e){return this.filters.push({orderDate:{$between:[t,e]}}),this}withOrderDateIsKnown(){return this.filters.push({orderDate:{$isNull:!1}}),this}withOrderDateIsUnknown(){return this.filters.push({orderDate:{$isNull:!0}}),this}withTotalAmountIs(t){return this.filters.push({totalAmount:{$eq:t}}),this}withTotalAmountIsNot(t){return this.filters.push({totalAmount:{$ne:t}}),this}withTotalAmountIn(...t){return this.filters.push({totalAmount:{$in:t}}),this}withTotalAmountNotIn(...t){return this.filters.push({totalAmount:{$notIn:t}}),this}withTotalAmountGreaterThan(t){return this.filters.push({totalAmount:{$gt:t}}),this}withTotalAmountGreaterThanOrEqualTo(t){return this.filters.push({totalAmount:{$gte:t}}),this}withTotalAmountLessThan(t){return this.filters.push({totalAmount:{$lt:t}}),this}withTotalAmountLessThanOrEqualTo(t){return this.filters.push({totalAmount:{$lte:t}}),this}withTotalAmountBetween(t,e){return this.filters.push({totalAmount:{$between:[t,e]}}),this}withTotalAmountIsKnown(){return this.filters.push({totalAmount:{$isNull:!1}}),this}withTotalAmountIsUnknown(){return this.filters.push({totalAmount:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByOrderNumberAscending(){return this.query.orderBy("orderNumber","asc"),this}orderByOrderNumberDescending(){return this.query.orderBy("orderNumber","desc"),this}orderByOrderDateAscending(){return this.query.orderBy("orderDate","asc"),this}orderByOrderDateDescending(){return this.query.orderBy("orderDate","desc"),this}orderByTotalAmountAscending(){return this.query.orderBy("totalAmount","asc"),this}orderByTotalAmountDescending(){return this.query.orderBy("totalAmount","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minTotalAmount(){return this.minTotalAmountAs("minOfTotalAmount")}minTotalAmountAs(t){return this.query.aggregate("min","totalAmount",t),this}maxTotalAmount(){return this.maxTotalAmountAs("maxOfTotalAmount")}maxTotalAmountAs(t){return this.query.aggregate("max","totalAmount",t),this}sumTotalAmount(){return this.sumTotalAmountAs("sumOfTotalAmount")}sumTotalAmountAs(t){return this.query.aggregate("sum","totalAmount",t),this}avgTotalAmount(){return this.avgTotalAmountAs("avgOfTotalAmount")}avgTotalAmountAs(t){return this.query.aggregate("avg","totalAmount",t),this}standardDeviationTotalAmount(){return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount")}standardDeviationTotalAmountAs(t){return this.query.aggregate("stddev","totalAmount",t),this}squareRootOfPopulationStandardDeviationTotalAmount(){return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount")}squareRootOfPopulationStandardDeviationTotalAmountAs(t){return this.query.aggregate("stddev_pop","totalAmount",t),this}sampleVarianceTotalAmount(){return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount")}sampleVarianceTotalAmountAs(t){return this.query.aggregate("var_samp","totalAmount",t),this}samplePopulationVarianceTotalAmount(){return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount")}samplePopulationVarianceTotalAmountAs(t){return this.query.aggregate("var_pop","totalAmount",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomer(){return this.query.groupBy("customer"),this}groupByCustomerAs(t){return this.query.groupBy("customer"),this}groupByStatus(){return this.query.groupBy("status"),this}groupByStatusAs(t){return this.query.groupBy("status"),this}groupByOrderNumber(){return this.query.groupBy("orderNumber"),this}groupByOrderNumberAs(t){return this.query.groupBy("orderNumber"),this}groupByOrderDate(){return this.query.groupBy("orderDate"),this}groupByOrderDateAs(t){return this.query.groupBy("orderDate"),this}groupByTotalAmount(){return this.query.groupBy("totalAmount"),this}groupByTotalAmountAs(t){return this.query.groupBy("totalAmount"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerAs(t,e,r=!0){return this.query.facetBy(t,"customer",e,r,{kind:"facet",method:"facetByCustomerAs",relation:"customer",alias:t}),this}facetByStatusAs(t,e,r=!0){return this.query.facetBy(t,"status",e,r,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof $?o:$.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof $?u:$.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof $?o:$.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class At{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new $}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ut{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new _t(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customerOrder","productName","quantity","unitPrice","version"]),this}selectId(){return this.query.select(["id"]),this}selectProductName(){return this.query.select(["productName"]),this}selectQuantity(){return this.query.select(["quantity"]),this}selectUnitPrice(){return this.query.select(["unitPrice"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerOrderWith(t){return this.query.select(["customerOrder"]),this.query.relationQuery("customerOrder",t.toQuery(),"customerOrder","id",!1,{kind:"relation-select",method:"selectCustomerOrderWith",relation:"customerOrder"}),this}withCustomerOrderMatching(t){return this.filters.push({customerOrder:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerOrderMatching(t){return this.filters.push({customerOrder:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomerOrder(t){return this.filters.push({customerOrder:{$eq:t}}),this}filterByCustomerOrderIn(...t){return this.filters.push({customerOrder:{$in:t}}),this}withCustomerOrderIsKnown(){return this.filters.push({customerOrder:{$isNull:!1}}),this}withCustomerOrderIsUnknown(){return this.filters.push({customerOrder:{$isNull:!0}}),this}withProductNameContaining(t){return this.filters.push({productName:{$contains:t}}),this}withProductNameIs(t){return this.filters.push({productName:{$eq:t}}),this}withProductNameIsNot(t){return this.filters.push({productName:{$ne:t}}),this}withProductNameIn(...t){return this.filters.push({productName:{$in:t}}),this}withProductNameNotIn(...t){return this.filters.push({productName:{$notIn:t}}),this}withProductNameGreaterThan(t){return this.filters.push({productName:{$gt:t}}),this}withProductNameGreaterThanOrEqualTo(t){return this.filters.push({productName:{$gte:t}}),this}withProductNameLessThan(t){return this.filters.push({productName:{$lt:t}}),this}withProductNameLessThanOrEqualTo(t){return this.filters.push({productName:{$lte:t}}),this}withProductNameBetween(t,e){return this.filters.push({productName:{$between:[t,e]}}),this}withProductNameIsKnown(){return this.filters.push({productName:{$isNull:!1}}),this}withProductNameIsUnknown(){return this.filters.push({productName:{$isNull:!0}}),this}withProductNameNotContaining(t){return this.filters.push({productName:{$notContains:t}}),this}withProductNameStartingWith(t){return this.filters.push({productName:{$startsWith:t}}),this}withProductNameNotStartingWith(t){return this.filters.push({productName:{$notStartsWith:t}}),this}withProductNameEndingWith(t){return this.filters.push({productName:{$endsWith:t}}),this}withProductNameNotEndingWith(t){return this.filters.push({productName:{$notEndsWith:t}}),this}withProductNameSoundingLike(t){return this.filters.push({productName:{$soundLike:t}}),this}withQuantityIs(t){return this.filters.push({quantity:{$eq:t}}),this}withQuantityIsNot(t){return this.filters.push({quantity:{$ne:t}}),this}withQuantityIn(...t){return this.filters.push({quantity:{$in:t}}),this}withQuantityNotIn(...t){return this.filters.push({quantity:{$notIn:t}}),this}withQuantityGreaterThan(t){return this.filters.push({quantity:{$gt:t}}),this}withQuantityGreaterThanOrEqualTo(t){return this.filters.push({quantity:{$gte:t}}),this}withQuantityLessThan(t){return this.filters.push({quantity:{$lt:t}}),this}withQuantityLessThanOrEqualTo(t){return this.filters.push({quantity:{$lte:t}}),this}withQuantityBetween(t,e){return this.filters.push({quantity:{$between:[t,e]}}),this}withQuantityIsKnown(){return this.filters.push({quantity:{$isNull:!1}}),this}withQuantityIsUnknown(){return this.filters.push({quantity:{$isNull:!0}}),this}withUnitPriceIs(t){return this.filters.push({unitPrice:{$eq:t}}),this}withUnitPriceIsNot(t){return this.filters.push({unitPrice:{$ne:t}}),this}withUnitPriceIn(...t){return this.filters.push({unitPrice:{$in:t}}),this}withUnitPriceNotIn(...t){return this.filters.push({unitPrice:{$notIn:t}}),this}withUnitPriceGreaterThan(t){return this.filters.push({unitPrice:{$gt:t}}),this}withUnitPriceGreaterThanOrEqualTo(t){return this.filters.push({unitPrice:{$gte:t}}),this}withUnitPriceLessThan(t){return this.filters.push({unitPrice:{$lt:t}}),this}withUnitPriceLessThanOrEqualTo(t){return this.filters.push({unitPrice:{$lte:t}}),this}withUnitPriceBetween(t,e){return this.filters.push({unitPrice:{$between:[t,e]}}),this}withUnitPriceIsKnown(){return this.filters.push({unitPrice:{$isNull:!1}}),this}withUnitPriceIsUnknown(){return this.filters.push({unitPrice:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByProductNameAscending(){return this.query.orderBy("productName","asc"),this}orderByProductNameDescending(){return this.query.orderBy("productName","desc"),this}orderByQuantityAscending(){return this.query.orderBy("quantity","asc"),this}orderByQuantityDescending(){return this.query.orderBy("quantity","desc"),this}orderByUnitPriceAscending(){return this.query.orderBy("unitPrice","asc"),this}orderByUnitPriceDescending(){return this.query.orderBy("unitPrice","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minQuantity(){return this.minQuantityAs("minOfQuantity")}minQuantityAs(t){return this.query.aggregate("min","quantity",t),this}maxQuantity(){return this.maxQuantityAs("maxOfQuantity")}maxQuantityAs(t){return this.query.aggregate("max","quantity",t),this}sumQuantity(){return this.sumQuantityAs("sumOfQuantity")}sumQuantityAs(t){return this.query.aggregate("sum","quantity",t),this}avgQuantity(){return this.avgQuantityAs("avgOfQuantity")}avgQuantityAs(t){return this.query.aggregate("avg","quantity",t),this}standardDeviationQuantity(){return this.standardDeviationQuantityAs("standardDeviationOfQuantity")}standardDeviationQuantityAs(t){return this.query.aggregate("stddev","quantity",t),this}squareRootOfPopulationStandardDeviationQuantity(){return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity")}squareRootOfPopulationStandardDeviationQuantityAs(t){return this.query.aggregate("stddev_pop","quantity",t),this}sampleVarianceQuantity(){return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity")}sampleVarianceQuantityAs(t){return this.query.aggregate("var_samp","quantity",t),this}samplePopulationVarianceQuantity(){return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity")}samplePopulationVarianceQuantityAs(t){return this.query.aggregate("var_pop","quantity",t),this}minUnitPrice(){return this.minUnitPriceAs("minOfUnitPrice")}minUnitPriceAs(t){return this.query.aggregate("min","unitPrice",t),this}maxUnitPrice(){return this.maxUnitPriceAs("maxOfUnitPrice")}maxUnitPriceAs(t){return this.query.aggregate("max","unitPrice",t),this}sumUnitPrice(){return this.sumUnitPriceAs("sumOfUnitPrice")}sumUnitPriceAs(t){return this.query.aggregate("sum","unitPrice",t),this}avgUnitPrice(){return this.avgUnitPriceAs("avgOfUnitPrice")}avgUnitPriceAs(t){return this.query.aggregate("avg","unitPrice",t),this}standardDeviationUnitPrice(){return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice")}standardDeviationUnitPriceAs(t){return this.query.aggregate("stddev","unitPrice",t),this}squareRootOfPopulationStandardDeviationUnitPrice(){return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice")}squareRootOfPopulationStandardDeviationUnitPriceAs(t){return this.query.aggregate("stddev_pop","unitPrice",t),this}sampleVarianceUnitPrice(){return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice")}sampleVarianceUnitPriceAs(t){return this.query.aggregate("var_samp","unitPrice",t),this}samplePopulationVarianceUnitPrice(){return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice")}samplePopulationVarianceUnitPriceAs(t){return this.query.aggregate("var_pop","unitPrice",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomerOrder(){return this.query.groupBy("customerOrder"),this}groupByCustomerOrderAs(t){return this.query.groupBy("customerOrder"),this}groupByProductName(){return this.query.groupBy("productName"),this}groupByProductNameAs(t){return this.query.groupBy("productName"),this}groupByQuantity(){return this.query.groupBy("quantity"),this}groupByQuantityAs(t){return this.query.groupBy("quantity"),this}groupByUnitPrice(){return this.query.groupBy("unitPrice"),this}groupByUnitPriceAs(t){return this.query.groupBy("unitPrice"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerOrderAs(t,e,r=!0){return this.query.facetBy(t,"customerOrder",e,r,{kind:"facet",method:"facetByCustomerOrderAs",relation:"customerOrder",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof B?o:B.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof B?u:B.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof B?o:B.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class _t{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new B}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class E{static platforms(){return new st(!1)}static platformsWithMinimalFields(){return new st(!0)}static orderStatuses(){return new ot(!1)}static orderStatusesWithMinimalFields(){return new ot(!0)}static customers(){return new nt(!1)}static customersWithMinimalFields(){return new nt(!0)}static customerOrders(){return new at(!1)}static customerOrdersWithMinimalFields(){return new at(!0)}static orderItems(){return new ut(!1)}static orderItemsWithMinimalFields(){return new ut(!0)}}class I extends Error{constructor(t,e,r){const i=`select${r.charAt(0).toUpperCase()}${r.slice(1)}(...)`,s={error:"TeaQLNotLoadedError",root:t,accessPath:e.split("."),breakPoint:r,missingPreload:[r],suggestedFix:i,severity:"error",humanMessage:`访问 ${t}.${e} 时缺少预加载。请在查询中加入 ${i}`};super(JSON.stringify(s)),this.root=t,this.accessPath=e,this.breakPoint=r,this.name="TeaQLNotLoadedError",this.details=s}root;accessPath;breakPoint;details}function q(d,t){return d?`${d}.${t}`:t}class n{constructor(t,e=!0,r){this.value=t,this.present=e,this.notLoaded=r}value;present;notLoaded;static missing(){return new n(void 0,!1)}static notLoaded(t){return new n(void 0,!1,t)}eval(){if(this.notLoaded)throw this.notLoaded;return this.present?this.value:void 0}isPresent(){if(this.notLoaded)throw this.notLoaded;return this.present}orElse(t){const e=this.eval();return this.present&&e!=null?e:t}}class x{constructor(t,e="Platform(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}orderStatusList(){const t=q(this.path,"orderStatusList");return this.notLoaded?new U([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderStatusList")?new U(this.value.orderStatusList(),this.root,t):new U([],this.root,t,!1,new I(this.root,t,"orderStatusList")):U.missing(this.root,t)}customerList(){const t=q(this.path,"customerList");return this.notLoaded?new M([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerList")?new M(this.value.customerList(),this.root,t):new M([],this.root,t,!1,new I(this.root,t,"customerList")):M.missing(this.root,t)}}class V{constructor(t,e="OrderStatus(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}code(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"code");return this.value.isLoaded("code")?new n(this.value.code):n.notLoaded(new I(this.root,t,"code"))}color(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"color");return this.value.isLoaded("color")?new n(this.value.color):n.notLoaded(new I(this.root,t,"color"))}displayOrder(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"displayOrder");return this.value.isLoaded("displayOrder")?new n(this.value.displayOrder):n.notLoaded(new I(this.root,t,"displayOrder"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class W{constructor(t,e="Customer(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class K{constructor(t,e="CustomerOrder(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}orderNumber(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderNumber");return this.value.isLoaded("orderNumber")?new n(this.value.orderNumber):n.notLoaded(new I(this.root,t,"orderNumber"))}orderDate(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderDate");return this.value.isLoaded("orderDate")?new n(this.value.orderDate):n.notLoaded(new I(this.root,t,"orderDate"))}totalAmount(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"totalAmount");return this.value.isLoaded("totalAmount")?new n(this.value.totalAmount):n.notLoaded(new I(this.root,t,"totalAmount"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customer");if(!this.value.isLoaded("customer"))return n.notLoaded(new I(this.root,t,"customer"));const e=this.value.customer;return new n(e instanceof Q?e.id:e)}statusId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"status");if(!this.value.isLoaded("status"))return n.notLoaded(new I(this.root,t,"status"));const e=this.value.status;return new n(e instanceof S?e.id:e)}customer(){const t=q(this.path,"customer");if(this.notLoaded)return new W(void 0,this.root,t,this.notLoaded);if(!this.value)return new W(void 0,this.root,t);if(!this.value.isLoaded("customer"))return new W(void 0,this.root,t,new I(this.root,t,"customer"));const e=this.value.customer,r=e==null?void 0:e instanceof Q?e:Q.fromRecord({id:e});return new W(r,this.root,t)}status(){const t=q(this.path,"status");if(this.notLoaded)return new V(void 0,this.root,t,this.notLoaded);if(!this.value)return new V(void 0,this.root,t);if(!this.value.isLoaded("status"))return new V(void 0,this.root,t,new I(this.root,t,"status"));const e=this.value.status,r=e==null?void 0:e instanceof S?e:S.fromRecord({id:e});return new V(r,this.root,t)}orderItemList(){const t=q(this.path,"orderItemList");return this.notLoaded?new j([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderItemList")?new j(this.value.orderItemList(),this.root,t):new j([],this.root,t,!1,new I(this.root,t,"orderItemList")):j.missing(this.root,t)}}class H{constructor(t,e="OrderItem(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}productName(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"productName");return this.value.isLoaded("productName")?new n(this.value.productName):n.notLoaded(new I(this.root,t,"productName"))}quantity(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"quantity");return this.value.isLoaded("quantity")?new n(this.value.quantity):n.notLoaded(new I(this.root,t,"quantity"))}unitPrice(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"unitPrice");return this.value.isLoaded("unitPrice")?new n(this.value.unitPrice):n.notLoaded(new I(this.root,t,"unitPrice"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerOrderId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customerOrder");if(!this.value.isLoaded("customerOrder"))return n.notLoaded(new I(this.root,t,"customerOrder"));const e=this.value.customerOrder;return new n(e instanceof $?e.id:e)}customerOrder(){const t=q(this.path,"customerOrder");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded);if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("customerOrder"))return new K(void 0,this.root,t,new I(this.root,t,"customerOrder"));const e=this.value.customerOrder,r=e==null?void 0:e instanceof $?e:$.fromRecord({id:e});return new K(r,this.root,t)}}class U{constructor(t,e="OrderStatus(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new U([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new V(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new V(void 0,this.root,e):new V(this.items[t],this.root,e)}}class M{constructor(t,e="Customer(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new M([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new W(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new W(void 0,this.root,e):new W(this.items[t],this.root,e)}}class k{constructor(t,e="CustomerOrder(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new k([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new K(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new K(void 0,this.root,e):new K(this.items[t],this.root,e)}}class j{constructor(t,e="OrderItem(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new j([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new H(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new H(void 0,this.root,e):new H(this.items[t],this.root,e)}}class et{static platform(t){return new x(t,`Platform(id=${t?.id??"null"})`)}static orderStatus(t){return new V(t,`OrderStatus(id=${t?.id??"null"})`)}static customer(t){return new W(t,`Customer(id=${t?.id??"null"})`)}static customerOrder(t){return new K(t,`CustomerOrder(id=${t?.id??"null"})`)}static orderItem(t){return new H(t,`OrderItem(id=${t?.id??"null"})`)}}const ht={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{orderStatusList:{targetEntity:"OrderStatus",localKey:"id",foreignKey:"platform",many:!0},customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platform",many:!0}}},OrderStatus:{table:"order_status_data",auditMaskFields:[],columns:{platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},code:{columnName:"code",modelName:"code",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},color:{columnName:"color",modelName:"color",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},displayOrder:{columnName:"display_order",modelName:"display_order",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},Customer:{table:"customer_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customer",many:!0}}},CustomerOrder:{table:"customer_order_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customer:{columnName:"customer",modelName:"customer",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},status:{columnName:"status",modelName:"status",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},orderNumber:{columnName:"order_number",modelName:"order_number",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},orderDate:{columnName:"order_date",modelName:"order_date",logPolicy:"plain",logicalType:"date",decode:"date",nullable:!1},totalAmount:{columnName:"total_amount",modelName:"total_amount",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customer:{targetEntity:"Customer",localKey:"customer",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},orderItemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"customerOrder",many:!0}}},OrderItem:{table:"order_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customerOrder:{columnName:"customer_order",modelName:"customer_order",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},productName:{columnName:"product_name",modelName:"product_name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},quantity:{columnName:"quantity",modelName:"quantity",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},unitPrice:{columnName:"unit_price",modelName:"unit_price",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customerOrder:{targetEntity:"CustomerOrder",localKey:"customerOrder",foreignKey:"id",many:!1}}}};async function Ct(d){let t=(await E.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];t||(t=N.teaqlBootstrapNew("1"),t.updateName("Commerce Test Platform"),await t.auditAs("create generated Domain Root Platform").save(d)),d.withActiveRoot({entity:"Platform",id:t.id});let e=(await E.orderStatuses().withIdIs("1001").comment("what: locate generated constant OrderStatus(1001)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!e)e=S.teaqlBootstrapNew("1001"),e.updatePlatform(t),e.updateName("New"),e.updateCode("NEW"),e.updateColor("#94A3B8"),e.updateDisplayOrder(1),await e.auditAs("create model constant OrderStatus(1001)").save(d);else{let s=!1;String(e.platform?.id??e.platform)!==String(t.id)&&(e.updatePlatform(t),s=!0),e.name!=="New"&&(e.updateName("New"),s=!0),e.code!=="NEW"&&(e.updateCode("NEW"),s=!0),e.color!=="#94A3B8"&&(e.updateColor("#94A3B8"),s=!0),e.displayOrder!==1&&(e.updateDisplayOrder(1),s=!0),s&&await e.auditAs("reconcile model constant OrderStatus(1001)").save(d)}let r=(await E.orderStatuses().withIdIs("1002").comment("what: locate generated constant OrderStatus(1002)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!r)r=S.teaqlBootstrapNew("1002"),r.updatePlatform(t),r.updateName("Paid"),r.updateCode("PAID"),r.updateColor("#22C55E"),r.updateDisplayOrder(2),await r.auditAs("create model constant OrderStatus(1002)").save(d);else{let s=!1;String(r.platform?.id??r.platform)!==String(t.id)&&(r.updatePlatform(t),s=!0),r.name!=="Paid"&&(r.updateName("Paid"),s=!0),r.code!=="PAID"&&(r.updateCode("PAID"),s=!0),r.color!=="#22C55E"&&(r.updateColor("#22C55E"),s=!0),r.displayOrder!==2&&(r.updateDisplayOrder(2),s=!0),s&&await r.auditAs("reconcile model constant OrderStatus(1002)").save(d)}let i=(await E.orderStatuses().withIdIs("1003").comment("what: locate generated constant OrderStatus(1003)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!i)i=S.teaqlBootstrapNew("1003"),i.updatePlatform(t),i.updateName("Cancelled"),i.updateCode("CANCELLED"),i.updateColor("#EF4444"),i.updateDisplayOrder(3),await i.auditAs("create model constant OrderStatus(1003)").save(d);else{let s=!1;String(i.platform?.id??i.platform)!==String(t.id)&&(i.updatePlatform(t),s=!0),i.name!=="Cancelled"&&(i.updateName("Cancelled"),s=!0),i.code!=="CANCELLED"&&(i.updateCode("CANCELLED"),s=!0),i.color!=="#EF4444"&&(i.updateColor("#EF4444"),s=!0),i.displayOrder!==3&&(i.updateDisplayOrder(3),s=!0),s&&await i.auditAs("reconcile model constant OrderStatus(1003)").save(d)}}const Pt=new pt(ht,{Platform:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},OrderStatus:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100}),(t.action==="Create"&&t.payload.code===void 0||t.payload.code===null)&&e.push({ruleId:"required",location:w.property("code")}),t.payload.code!=null&&[...String(t.payload.code)].length>100&&e.push({ruleId:"max_length",location:w.property("code"),inputValue:t.payload.code,systemValue:100}),(t.action==="Create"&&t.payload.color===void 0||t.payload.color===null)&&e.push({ruleId:"required",location:w.property("color")}),t.payload.color!=null&&[...String(t.payload.color)].length>100&&e.push({ruleId:"max_length",location:w.property("color"),inputValue:t.payload.color,systemValue:100}),(t.action==="Create"&&t.payload.display_order===void 0||t.payload.display_order===null)&&e.push({ruleId:"required",location:w.property("display_order")})}},Customer:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},CustomerOrder:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer===void 0||t.payload.customer===null)&&e.push({ruleId:"required",location:w.property("customer")}),(t.action==="Create"&&t.payload.status===void 0||t.payload.status===null)&&e.push({ruleId:"required",location:w.property("status")}),(t.action==="Create"&&t.payload.order_number===void 0||t.payload.order_number===null)&&e.push({ruleId:"required",location:w.property("order_number")}),t.payload.order_number!=null&&[...String(t.payload.order_number)].length>100&&e.push({ruleId:"max_length",location:w.property("order_number"),inputValue:t.payload.order_number,systemValue:100}),(t.action==="Create"&&t.payload.order_date===void 0||t.payload.order_date===null)&&e.push({ruleId:"required",location:w.property("order_date")}),(t.action==="Create"&&t.payload.total_amount===void 0||t.payload.total_amount===null)&&e.push({ruleId:"required",location:w.property("total_amount")})}},OrderItem:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer_order===void 0||t.payload.customer_order===null)&&e.push({ruleId:"required",location:w.property("customer_order")}),(t.action==="Create"&&t.payload.product_name===void 0||t.payload.product_name===null)&&e.push({ruleId:"required",location:w.property("product_name")}),t.payload.product_name!=null&&[...String(t.payload.product_name)].length>100&&e.push({ruleId:"max_length",location:w.property("product_name"),inputValue:t.payload.product_name,systemValue:100}),(t.action==="Create"&&t.payload.quantity===void 0||t.payload.quantity===null)&&e.push({ruleId:"required",location:w.property("quantity")}),(t.action==="Create"&&t.payload.unit_price===void 0||t.payload.unit_price===null)&&e.push({ruleId:"required",location:w.property("unit_price")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Commerce Test Platform"}},constants:[{entity:"OrderStatus",id:"1001",values:{platform:"1",name:"New",code:"NEW",color:"#94A3B8",displayOrder:1}},{entity:"OrderStatus",id:"1002",values:{platform:"1",name:"Paid",code:"PAID",color:"#22C55E",displayOrder:2}},{entity:"OrderStatus",id:"1003",values:{platform:"1",name:"Cancelled",code:"CANCELLED",color:"#EF4444",displayOrder:3}}],ensure:Ct}),it=document.querySelector("#status"),St=document.querySelector("#result"),Nt=document.querySelector("#trace"),$t=document.querySelector("#sql"),bt=document.querySelector("#evidence-rows"),Z=document.querySelector("#persist"),dt=document.querySelector("#logging"),rt=document.querySelector("#reset"),Y=document.querySelector("#query"),lt=document.querySelector("#search"),Tt={filter:{orderNumber:{$contains:"KEEP"}}};let R;Z.checked=localStorage.getItem("teaql-browser-order-storage")==="opfs";async function Qt(d){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await ft.open(t,{...ht},{storage:d,databaseName:"teaql-browser-orders.sqlite3"});e.install(Pt),e.setDiagnosticSQLLogSink(void 0).setMutationLoggingEnabled(!1);const r=Object.freeze({policyId:"browser-order-seed",version:"1",fingerprint:"sha256:browser-order-seed-v1"}),i=new gt().insertResource("dataService",e).withMutationPolicyRegistry(new Ot(()=>({identity:r,review:(s,h)=>h.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new wt(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(i),await i.ensureSchema(),await i.ensureSchema(),{client:e,context:i,evidence:new qt,diagnostics:[]}}async function ct({context:d}){if((await E.customerOrdersWithMinimalFields().limit(1).comment("detect existing order demo").purpose("keep mutation seeding idempotent").executeForList(d)).length)return;const e=(await E.platforms().limit(2).comment("load bootstrap platform").purpose("prepare order demo").executeForList(d))[0],r=E.customers().comment("initialize demo customer").purpose("prepare order demo").newEntity(d);r.updateName("North Star Retail").updatePlatform(e.id),await r.auditAs("seed browser order customer").save(d);for(let i=1;i<=4;i++){const s=E.customerOrders().comment("initialize demo order").purpose("prepare order demo").newEntity(d);s.updateCustomer(r.id).updateOrderNumber(i<4?`KEEP-00${i}`:"DROP-004").updateOrderDate(`2026-10-0${i}`).updateTotalAmount(i<4?i*100:900),i===1?s.updateStatusToNew():s.updateStatusToPaid(),await s.auditAs("seed browser order").save(d);for(let h=1;h<=5;h++){const o=E.orderItems().comment("initialize demo item").purpose("prepare item previews").newEntity(d);o.updateCustomerOrder(s.id).updateProductName(`Box ${h}`).updateQuantity(h).updateUnitPrice(20),await o.auditAs("seed browser order item").save(d)}}}async function tt(d){const t=JSON.parse(lt.value),e=E.customerOrdersWithMinimalFields().filterByJson(t);d.evidence.enableAll(),d.diagnostics.length=0,d.client.setRuntimeTelemetrySink(d.evidence).setQueryLoggingEnabled(dt.checked).setDiagnosticSQLLogSink({write:o=>d.diagnostics.push(o)});const r=await e.countAs("totalOrders").facetByStatusAs("statusCounts",E.orderStatusesWithMinimalFields().selectName().selectColor().countAs("orderCount").sumTotalAmountOfCustomerOrdersAs("orderTotalAmount",E.customerOrdersWithMinimalFields()).orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(E.orderStatusesWithMinimalFields().selectName().selectColor().comment("load status")).selectOrderItemListWith(E.orderItemsWithMinimalFields().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countOrderItemsAs("itemCount").orderByOrderDateDescending().orderByIdDescending().offset(1).limit(1).comment("load order list").purpose("render order list page").executeForList(d.context),i={data:r.data.map(o=>{const p=et.customerOrder(o),l=p.orderItemList().size().eval();if(l==null)throw new Error("Selected item list unexpectedly has a null size");return{id:o.id,version:o.version,orderNumber:p.orderNumber().eval(),orderDate:p.orderDate().eval(),status:{name:p.status().name().eval(),color:p.status().color().eval()},items:Array.from({length:l},(a,u)=>({productName:p.orderItemList().get(u).productName().eval(),quantity:p.orderItemList().get(u).quantity().eval()})),itemCount:o.itemCount}}),metadata:{totalCount:r.totalCount,pageOffset:1,pageSize:1,aggregations:r.data.aggregations,searchWarnings:e.dynamicSearchWarnings},facets:{statusCounts:r.data.facets.statusCounts.map(o=>({id:o.id,name:et.orderStatus(S.fromRecord(o)).name().eval(),color:et.orderStatus(S.fromRecord(o)).color().eval(),orderCount:o.orderCount,orderTotalAmount:o.orderTotalAmount}))}};St.textContent=JSON.stringify(i,null,2);const s=d.evidence.snapshot(),h=s.map(o=>{const p=o.traceChain??[],l=p.filter(m=>m.kind==="purpose"),a=l.length===1?`${l[0].detail}: ${p.filter(m=>m.kind==="comment").map(m=>m.detail).join(" → ")}`:"TraceChain unavailable",u=document.createElement("tr");for(const m of[`${o.elapsedMicros} µs`,o.tracePath.find(C=>C.kind==="request")?.name??"—",a,o.debugSQL]){const C=document.createElement("td");C.textContent=m,u.append(C)}return{row:u,businessTrace:a}});bt.replaceChildren(...h.map(o=>o.row)),Nt.textContent=h.map(o=>o.businessTrace).join(` `),$t.textContent=JSON.stringify(s,null,2),it.textContent=`${d.client.storage.toUpperCase()} · ${r.totalCount} matches · ${s.length} SQL statements · ${d.diagnostics.length} diagnostics · policy installed · ready`}async function mt(d){it.textContent=`Opening ${d.toUpperCase()} SQLite/WASM…`;const t=R;R=void 0,await t?.client.close();const e=await Qt(d);R=e,await ct(e),await tt(e)}function X(d){it.textContent=d instanceof Error?`${d.name}: ${d.message}`:String(d)}Y.addEventListener("click",async()=>{if(R){Y.disabled=!0;try{await tt(R)}catch(d){X(d)}finally{Y.disabled=!1}}});document.querySelector("#preset").addEventListener("click",()=>{lt.value=JSON.stringify(Tt,null,2),Y.click()});dt.addEventListener("change",()=>{R&&tt(R).catch(X)});Z.addEventListener("change",()=>{const d=Z.checked?"opfs":"memory";localStorage.setItem("teaql-browser-order-storage",d),mt(d).catch(X)});rt.addEventListener("click",async()=>{if(R){rt.disabled=!0;try{await R.client.reset(R.context),await ct(R),await tt(R)}catch(d){X(d)}finally{rt.disabled=!1}}});mt(Z.checked?"opfs":"memory").catch(X); diff --git a/assets/style-DVG2mb5q.css b/assets/style-DVG2mb5q.css new file mode 100644 index 0000000000000000000000000000000000000000..157f87557015f22314aed6b4a1d4dfaa73445f8e --- /dev/null +++ b/assets/style-DVG2mb5q.css @@ -0,0 +1 @@ +:root{font:16px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;color:#17231b;background:#f5f4ed;font-synthesis:none;--ink: #17231b;--muted: #677067;--paper: #fffef8;--line: #d8ddd3;--green: #145b37;--green-deep: #0e4329;--lime: #dff45c;--orange: #ef8354;--blue: #2b66d9}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;min-width:320px;background:#f5f4ed}button,input{font:inherit}button,a{-webkit-tap-highlight-color:transparent}.page-shell{width:min(1440px,100%);margin:0 auto;padding:0 42px}.site-header{height:76px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand,.docs-link{color:var(--ink);text-decoration:none;font-weight:750}.brand{display:inline-flex;align-items:center;gap:11px;letter-spacing:-.02em}.brand-mark{width:30px;height:30px;display:grid;place-items:center;border-radius:50%;color:var(--lime);background:var(--green-deep);font-family:Georgia,serif;font-style:italic}.docs-link{color:var(--green);font-size:14px}.header-actions{display:flex;align-items:center;gap:18px}.language-switch{display:flex;gap:3px;padding:3px;border:1px solid var(--line);border-radius:8px}.language-switch button{padding:3px 7px;border:0;border-radius:5px;color:var(--muted);background:transparent;font-size:11px;cursor:pointer}.language-switch button.active{color:#fff;background:var(--green)}.hero{min-height:460px;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(440px,.9fr);align-items:center;gap:72px;padding:76px 0 66px}.eyebrow,.section-index,.query-card-label{margin:0 0 14px;color:var(--green);font-size:11px;font-weight:850;letter-spacing:.18em}h1{margin:0;max-width:820px;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(42px,5.6vw,78px);font-weight:500;line-height:1.08;letter-spacing:-.055em}.hero-intro{max-width:680px;margin:26px 0 0;color:var(--muted);font-size:18px}.model-map{position:relative;min-height:310px;padding:38px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:12px;border:1px solid #bfc8bb;border-radius:28px;background:linear-gradient(145deg,#fdfdf8,#e9eee5);box-shadow:0 18px 48px #213c280f;overflow:hidden}.model-map:before{content:"DOMAIN MODEL";position:absolute;top:18px;left:22px;color:#708073;font-size:10px;font-weight:800;letter-spacing:.16em}.model-flow{width:100%;display:grid;grid-template-columns:1fr auto 1fr auto 1fr;align-items:center;gap:10px}.model-flow>span:not(.model-arrow),.model-leaves span{min-width:0;padding:15px 17px;border:1px solid #b8c2b7;border-radius:12px;background:#fffffadb;font:750 14px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;box-shadow:0 8px 22px #1e3a260d}.model-map small{display:block;margin-top:7px;color:var(--muted);font:12px/1.2 Inter,sans-serif}.model-flow>span.model-root{color:#fff;border-color:var(--green);background:var(--green)}.model-map .model-root small{color:#cce4d4}.model-arrow{color:#809087;font-size:22px;text-align:center}.model-arrow-split{height:22px;line-height:18px}.model-leaves{width:100%;display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.runtime-language-panel{margin-bottom:28px;padding:24px;display:grid;grid-template-columns:minmax(240px,.72fr) minmax(0,1.8fr);align-items:center;gap:30px;border:1px solid var(--line);border-radius:18px;background:var(--paper)}.runtime-language-copy .section-index{margin-bottom:8px}.runtime-language-copy h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(22px,2.4vw,31px);font-weight:500;line-height:1.15;letter-spacing:-.035em}.runtime-language-copy p:last-child{margin:11px 0 0;color:var(--muted);font-size:13px}.runtime-language-selector{display:grid;grid-template-columns:repeat(7,minmax(82px,1fr));gap:8px}.runtime-language{min-width:0;padding:13px 8px 11px;display:flex;align-items:center;flex-direction:column;gap:4px;border:1px solid #d7ddd5;border-radius:12px;color:var(--ink);background:#fafbf7;text-align:center;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.runtime-language:hover{border-color:#98aa9d;background:#fff;transform:translateY(-2px)}.runtime-language.active{color:#fff;border-color:var(--green);background:var(--green);box-shadow:0 8px 20px #145b3724}.runtime-language-icon{font-size:25px;line-height:1.1}.runtime-language strong{overflow:hidden;max-width:100%;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.runtime-language small{color:#78837a;font-size:8px;line-height:1.25}.runtime-language.active small{color:#d5e7da}.runtime-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.runtime-language-panel{grid-template-columns:1fr}.runtime-language-selector{grid-template-columns:repeat(4,minmax(100px,1fr))}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-language-panel{padding:20px 16px;gap:20px}.runtime-language-selector{grid-template-columns:repeat(2,minmax(0,1fr))}.runtime-language:last-child{grid-column:1 / -1}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}} diff --git a/assets/style-SCdXWqgK.css b/assets/style-SCdXWqgK.css deleted file mode 100644 index 8274d2f8ef8b83862a47b0c69f23f755fda89d67..0000000000000000000000000000000000000000 --- a/assets/style-SCdXWqgK.css +++ /dev/null @@ -1 +0,0 @@ -:root{font:16px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;color:#17231b;background:#f5f4ed;font-synthesis:none;--ink: #17231b;--muted: #677067;--paper: #fffef8;--line: #d8ddd3;--green: #145b37;--green-deep: #0e4329;--lime: #dff45c;--orange: #ef8354;--blue: #2b66d9}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;min-width:320px;background:#f5f4ed}button,input{font:inherit}button,a{-webkit-tap-highlight-color:transparent}.page-shell{width:min(1440px,100%);margin:0 auto;padding:0 42px}.site-header{height:76px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand,.docs-link{color:var(--ink);text-decoration:none;font-weight:750}.brand{display:inline-flex;align-items:center;gap:11px;letter-spacing:-.02em}.brand-mark{width:30px;height:30px;display:grid;place-items:center;border-radius:50%;color:var(--lime);background:var(--green-deep);font-family:Georgia,serif;font-style:italic}.docs-link{color:var(--green);font-size:14px}.header-actions{display:flex;align-items:center;gap:18px}.language-switch{display:flex;gap:3px;padding:3px;border:1px solid var(--line);border-radius:8px}.language-switch button{padding:3px 7px;border:0;border-radius:5px;color:var(--muted);background:transparent;font-size:11px;cursor:pointer}.language-switch button.active{color:#fff;background:var(--green)}.hero{min-height:460px;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(440px,.9fr);align-items:center;gap:72px;padding:76px 0 66px}.eyebrow,.section-index,.query-card-label{margin:0 0 14px;color:var(--green);font-size:11px;font-weight:850;letter-spacing:.18em}h1{margin:0;max-width:820px;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(42px,5.6vw,78px);font-weight:500;line-height:1.08;letter-spacing:-.055em}.hero-intro{max-width:680px;margin:26px 0 0;color:var(--muted);font-size:18px}.model-map{position:relative;min-height:310px;padding:38px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:12px;border:1px solid #bfc8bb;border-radius:28px;background:linear-gradient(145deg,#fdfdf8,#e9eee5);box-shadow:0 18px 48px #213c280f;overflow:hidden}.model-map:before{content:"DOMAIN MODEL";position:absolute;top:18px;left:22px;color:#708073;font-size:10px;font-weight:800;letter-spacing:.16em}.model-flow{width:100%;display:grid;grid-template-columns:1fr auto 1fr auto 1fr;align-items:center;gap:10px}.model-flow>span:not(.model-arrow),.model-leaves span{min-width:0;padding:15px 17px;border:1px solid #b8c2b7;border-radius:12px;background:#fffffadb;font:750 14px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;box-shadow:0 8px 22px #1e3a260d}.model-map small{display:block;margin-top:7px;color:var(--muted);font:12px/1.2 Inter,sans-serif}.model-flow>span.model-root{color:#fff;border-color:var(--green);background:var(--green)}.model-map .model-root small{color:#cce4d4}.model-arrow{color:#809087;font-size:22px;text-align:center}.model-arrow-split{height:22px;line-height:18px}.model-leaves{width:100%;display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.runtime-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}} diff --git a/assets/workItems-DraVJWt7.js b/assets/workItems-B6je_A1X.js similarity index 99% rename from assets/workItems-DraVJWt7.js rename to assets/workItems-B6je_A1X.js index b0ae6062d03594b1ac8317d6b745a9cb72d5e143..5058f7c29922f93499efbf63d1d76571fef79cc6 100644 --- a/assets/workItems-DraVJWt7.js +++ b/assets/workItems-B6je_A1X.js @@ -1 +1 @@ -import{S as G,L as c,M as k,C as v,a as I,d as O,e as C,Q as K,R as U,B as z,U as H,D as J,c as Y}from"./dynamic-search-BBmdgl4H.js";import{E as $,O as g}from"./object-location-xgYMemK6.js";class L extends G{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",s=!0,a){return super.relationQuery(t,e,i,r,s,a)}}class m{static teaqlTemporaryId=0;id;title;description;platform;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const i={...t};Object.assign(this,i),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof y?t.platform:y.fromRecord(t.platform),this.markLoaded("platform"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=new m(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new m({id:String(t)})}static teaqlBootstrapNew(t){return new m().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new v([{ruleId:"invalid_type",location:g.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n),n.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"WorkItem",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);for(const[S,f]of Object.entries(n.payload))S!=="id"&&S!=="version"&&this._root.set(this.teaqlEntityKey(),S,f);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();return this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update"),d.scopeFor(p),e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}class y{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--y.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:t?.id?I.empty():new I,writable:!0,enumerable:!1}),t){const i={...t};if(delete i.workItemList,Object.assign(this,i),Array.isArray(t.workItemList)){const r=t.workItemList;this._workItemList=new I(r.map(s=>s instanceof m?s:m.fromRecord(s)),{totalCount:r.totalCount,aggregations:r.aggregations,summary:r.summary,facets:r.facets,isLoaded:r.isLoaded??!0}),this.markLoaded("workItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._workItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const i=new y(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new y({id:String(t)})}static teaqlBootstrapNew(t){return new y().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(h=>!this.isLoaded(h.member));if(u)throw new v([{ruleId:"invalid_type",location:g.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n);const d=n.scopeFor(this.teaqlEntityKey());for(const[u,h]of this._workItemList.entries()){h.teaqlAttachRoot(this._root);const l=h.platform;(this.id===void 0||!h.isLoaded("platform")||(typeof l=="object"&&l!==null?l.id:l)!==this.id)&&h.updatePlatform(this);try{h.teaqlPreflightGraph(t,e,i,d)}catch(p){if(!(p instanceof v))throw p;const S=g.property("work_item_list").index(u);throw new v(p.violations.map(f=>({...f,location:f.location.prefixedBy(S)})))}}}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"Platform",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=d.scopeFor(this.teaqlEntityKey());for(const[q,w]of this._workItemList.entries()){w.teaqlAttachRoot(this._root);const _=w.platform;(this.id===void 0||!w.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&w.updatePlatform(this);try{await w.teaqlSaveWithinGraph(t,e,i,f)}catch(N){if(!(N instanceof v))throw N;const P=g.property("work_item_list").index(q);throw new v(N.violations.map(B=>({...B,location:B.location.prefixedBy(P)})))}}return this}const u=await e.executeMutation(d);for(const[f,q]of Object.entries(n.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,q);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update");const S=d.scopeFor(p);for(const[f,q]of this._workItemList.entries()){q.teaqlAttachRoot(this._root);const w=q.platform;(this.id===void 0||!q.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,i,S)}catch(_){if(!(_ instanceof v))throw _;const N=g.property("work_item_list").index(f);throw new v(_.violations.map(P=>({...P,location:P.location.prefixedBy(N)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const D=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class A{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new X(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({toQuery:()=>new L("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({toQuery:()=>new L("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new L("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof y?n:y.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof y?l:y.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof y?n:y.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class X{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new y}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class x{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Z(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title"),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof m?n:m.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof m?l:m.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof m?n:m.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class Z{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new m}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class R{static platforms(){return new A(!1)}static platformsWithMinimalFields(){return new A(!0)}static workItems(){return new x(!1)}static workItemsWithMinimalFields(){return new x(!0)}}const tt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function et(o){let t=(await R.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(o))[0];t||(t=y.teaqlBootstrapNew("1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(o)),o.withActiveRoot({entity:"Platform",id:t.id})}const it=new U(tt,{Platform:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:g.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:g.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:g.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:g.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:g.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:g.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:g.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:et}),rt={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},F=document.querySelector("#status"),st=document.querySelector("#result"),T=document.querySelector("#persist"),E=document.querySelector("#reset");let b;const M=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";T.checked=M==="opfs";async function nt(o){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await z.open(t,{...rt},{storage:o,databaseName:"teaql-browser-example.sqlite3"});e.install(it);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new H().insertResource("dataService",e).withMutationPolicyRegistry(new J(()=>({identity:i,review:(s,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Y(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Q({context:o}){if(!(await R.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(o)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await new m().updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(o)}async function V(o){const t=await R.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(o.context);st.textContent=JSON.stringify(t,null,2),F.textContent=`${o.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function j(o){F.textContent=`Opening ${o.toUpperCase()} SQLite/WASM…`;const t=b;b=void 0,await t?.client.close();const e=await nt(o);b=e,await Q(e),await V(e)}T.addEventListener("change",()=>{const o=T.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",o),j(o).catch(W)});E.addEventListener("click",async()=>{if(b){E.disabled=!0;try{await b.client.reset(b.context),await Q(b),await V(b)}catch(o){W(o)}finally{E.disabled=!1}}});function W(o){const t=o instanceof Error?o:new Error(String(o));F.textContent=`${t.name}: ${t.message}`}j(M).catch(W); +import{S as G,L as c,M as k,C as v,a as I,d as O,e as C,Q as K,R as U,B as z,U as H,D as J,c as Y}from"./dynamic-search-Ch_QcWVU.js";import{E as $,O as g}from"./object-location-CJfVWqJC.js";class L extends G{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",s=!0,a){return super.relationQuery(t,e,i,r,s,a)}}class m{static teaqlTemporaryId=0;id;title;description;platform;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const i={...t};Object.assign(this,i),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof y?t.platform:y.fromRecord(t.platform),this.markLoaded("platform"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=new m(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new m({id:String(t)})}static teaqlBootstrapNew(t){return new m().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new v([{ruleId:"invalid_type",location:g.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n),n.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"WorkItem",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);for(const[S,f]of Object.entries(n.payload))S!=="id"&&S!=="version"&&this._root.set(this.teaqlEntityKey(),S,f);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();return this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update"),d.scopeFor(p),e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}class y{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--y.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:t?.id?I.empty():new I,writable:!0,enumerable:!1}),t){const i={...t};if(delete i.workItemList,Object.assign(this,i),Array.isArray(t.workItemList)){const r=t.workItemList;this._workItemList=new I(r.map(s=>s instanceof m?s:m.fromRecord(s)),{totalCount:r.totalCount,aggregations:r.aggregations,summary:r.summary,facets:r.facets,isLoaded:r.isLoaded??!0}),this.markLoaded("workItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._workItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const i=new y(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new y({id:String(t)})}static teaqlBootstrapNew(t){return new y().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(h=>!this.isLoaded(h.member));if(u)throw new v([{ruleId:"invalid_type",location:g.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n);const d=n.scopeFor(this.teaqlEntityKey());for(const[u,h]of this._workItemList.entries()){h.teaqlAttachRoot(this._root);const l=h.platform;(this.id===void 0||!h.isLoaded("platform")||(typeof l=="object"&&l!==null?l.id:l)!==this.id)&&h.updatePlatform(this);try{h.teaqlPreflightGraph(t,e,i,d)}catch(p){if(!(p instanceof v))throw p;const S=g.property("work_item_list").index(u);throw new v(p.violations.map(f=>({...f,location:f.location.prefixedBy(S)})))}}}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"Platform",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=d.scopeFor(this.teaqlEntityKey());for(const[q,w]of this._workItemList.entries()){w.teaqlAttachRoot(this._root);const _=w.platform;(this.id===void 0||!w.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&w.updatePlatform(this);try{await w.teaqlSaveWithinGraph(t,e,i,f)}catch(N){if(!(N instanceof v))throw N;const P=g.property("work_item_list").index(q);throw new v(N.violations.map(B=>({...B,location:B.location.prefixedBy(P)})))}}return this}const u=await e.executeMutation(d);for(const[f,q]of Object.entries(n.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,q);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update");const S=d.scopeFor(p);for(const[f,q]of this._workItemList.entries()){q.teaqlAttachRoot(this._root);const w=q.platform;(this.id===void 0||!q.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,i,S)}catch(_){if(!(_ instanceof v))throw _;const N=g.property("work_item_list").index(f);throw new v(_.violations.map(P=>({...P,location:P.location.prefixedBy(N)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const D=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class A{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new X(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({toQuery:()=>new L("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({toQuery:()=>new L("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new L("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof y?n:y.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof y?l:y.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof y?n:y.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class X{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new y}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class x{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Z(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title"),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof m?n:m.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof m?l:m.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof m?n:m.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class Z{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new m}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class R{static platforms(){return new A(!1)}static platformsWithMinimalFields(){return new A(!0)}static workItems(){return new x(!1)}static workItemsWithMinimalFields(){return new x(!0)}}const tt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function et(o){let t=(await R.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(o))[0];t||(t=y.teaqlBootstrapNew("1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(o)),o.withActiveRoot({entity:"Platform",id:t.id})}const it=new U(tt,{Platform:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:g.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:g.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:g.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:g.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:g.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:g.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:g.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:et}),rt={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},F=document.querySelector("#status"),st=document.querySelector("#result"),T=document.querySelector("#persist"),E=document.querySelector("#reset");let b;const M=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";T.checked=M==="opfs";async function nt(o){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await z.open(t,{...rt},{storage:o,databaseName:"teaql-browser-example.sqlite3"});e.install(it);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new H().insertResource("dataService",e).withMutationPolicyRegistry(new J(()=>({identity:i,review:(s,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Y(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Q({context:o}){if(!(await R.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(o)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await new m().updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(o)}async function V(o){const t=await R.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(o.context);st.textContent=JSON.stringify(t,null,2),F.textContent=`${o.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function j(o){F.textContent=`Opening ${o.toUpperCase()} SQLite/WASM…`;const t=b;b=void 0,await t?.client.close();const e=await nt(o);b=e,await Q(e),await V(e)}T.addEventListener("change",()=>{const o=T.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",o),j(o).catch(W)});E.addEventListener("click",async()=>{if(b){E.disabled=!0;try{await b.client.reset(b.context),await Q(b),await V(b)}catch(o){W(o)}finally{E.disabled=!1}}});function W(o){const t=o instanceof Error?o:new Error(String(o));F.textContent=`${t.name}: ${t.message}`}j(M).catch(W); diff --git a/dist/assets/dynamic-search-BBmdgl4H.js b/dist/assets/dynamic-search-BBmdgl4H.js deleted file mode 100644 index 08ffb8822e2d0b40448ab09bc0b30e38c4ce5d16..0000000000000000000000000000000000000000 --- a/dist/assets/dynamic-search-BBmdgl4H.js +++ /dev/null @@ -1,8 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function t(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=t(r);fetch(r.href,o)}})();const Ae=Object.freeze({success:()=>{},failure:()=>{}}),rt=new Set(["teaql.entity.id","teaql.user.id","teaql.tenant.id","teaql.query.parameters","teaql.field.values","teaql.audit.reason","db.query.parameter_values","http.request.body","url.full"]);function st(i){const e={"teaql.operation.family":i.family,"teaql.operation.name":i.name};for(const[t,n]of Object.entries(i.attributes||{}))rt.has(t)||(e[t]=n);return Object.freeze({...i,attributes:Object.freeze(e)})}function N(i,e){if(!i)return Ae;try{const t=i.start(st(e));let n=!1;return{correlation:()=>{try{return t.correlation?.()}catch{return}},run:t.run?r=>t.run(r):r=>r(),success(r){if(!n){n=!0;try{t?.success(r)}catch{}}},failure(r){if(!n){n=!0;try{t?.failure(r)}catch{}}}}}catch{return Ae}}async function D(i,e,t,n){const r=N(i,e);try{const o=await(r.run?r.run(t):t());return r.success(n?.(o)),o}catch(o){throw r.failure(o),o}}class ot extends Error{constructor(e){super(`Check failed: ${e.map(t=>t.message??`${t.ruleId}:${t.location}`).join("; ")}`),this.violations=e,this.name="CheckException"}}const at="teaql.i18n/v1",ct="en",lt={en:{messages:{"checker.required":"The {location} is required","checker.min":"The {location} should be equal or greater than {system}, but input is {input}","checker.max":"The {location} should be equal or less than {system}, but input is {input}","checker.minLength":"The length of {location} should be equal or greater than {system}, but the length of {input} is {input_len}","checker.maxLength":"The length of {location} should be equal or less than {system}, but the length of {input} is {input_len}"},vocabulary:{}},"zh-CN":{messages:{"checker.required":"{location} 是必填项","checker.min":"{location} 应该大于等于 {system},但输入值为 {input}","checker.max":"{location} 应该小于等于 {system},但输入值为 {input}","checker.minLength":"{location} 的长度应大于等于 {system},但实际长度为 {input_len}","checker.maxLength":"{location} 的长度应小于等于 {system},但实际长度为 {input_len}"},vocabulary:{}},"zh-TW":{messages:{"checker.required":"{location} 是必填的","checker.min":"{location} 應該等於或大於 {system},但輸入為 {input}","checker.max":"{location} 應該等於或小於 {system},但輸入為 {input}","checker.minLength":"{location} 的長度應該等於或大於 {system},但 {input} 的長度是 {input_len}","checker.maxLength":"{location} 的長度應該等於或小於 {system},但 {input} 的長度是 {input_len}"},vocabulary:{}},ja:{messages:{"checker.required":"{location} は必須です","checker.min":"{location} は {system} 以上である必要があります。入力値は {input} です","checker.max":"{location} は {system} 以下である必要があります。入力値は {input} です","checker.minLength":"{location} の長さは {system} 以上である必要があります。実際の長さは {input_len} です","checker.maxLength":"{location} の長さは {system} 以下である必要があります。実際の長さは {input_len} です"},vocabulary:{}},ko:{messages:{"checker.required":"{location}은(는) 필수입니다","checker.min":"{location}은(는) {system} 이상이어야 하지만 입력값은 {input}입니다","checker.max":"{location}은(는) {system} 이하여야 하지만 입력값은 {input}입니다","checker.minLength":"{location}의 길이는 {system} 이상이어야 하지만 실제 길이는 {input_len}입니다","checker.maxLength":"{location}의 길이는 {system} 이하여야 하지만 실제 길이는 {input_len}입니다"},vocabulary:{}},de:{messages:{"checker.required":"{location} ist erforderlich","checker.min":"{location} muss mindestens {system} sein, aber die Eingabe ist {input}","checker.max":"{location} darf höchstens {system} sein, aber die Eingabe ist {input}","checker.minLength":"Die Länge von {location} muss mindestens {system} sein, ist aber {input_len}","checker.maxLength":"Die Länge von {location} darf höchstens {system} sein, ist aber {input_len}"},vocabulary:{}},fr:{messages:{"checker.required":"{location} est obligatoire","checker.min":"{location} doit être supérieur ou égal à {system}, mais la valeur saisie est {input}","checker.max":"{location} doit être inférieur ou égal à {system}, mais la valeur saisie est {input}","checker.minLength":"La longueur de {location} doit être supérieure ou égale à {system}, mais elle est {input_len}","checker.maxLength":"La longueur de {location} doit être inférieure ou égale à {system}, mais elle est {input_len}"},vocabulary:{}},es:{messages:{"checker.required":"{location} es requerido/a","checker.min":"{location} debe ser mayor o igual que {system}, pero el valor ingresado es {input}","checker.max":"{location} debe ser menor o igual que {system}, pero el valor ingresado es {input}","checker.minLength":"La longitud de {location} debe ser mayor o igual que {system}, pero es {input_len}","checker.maxLength":"La longitud de {location} debe ser menor o igual que {system}, pero es {input_len}"},vocabulary:{}},pt:{messages:{"checker.required":"{location} é obrigatório","checker.min":"{location} deve ser maior ou igual a {system}, mas a entrada é {input}","checker.max":"{location} deve ser menor ou igual a {system}, mas a entrada é {input}","checker.minLength":"O comprimento de {location} deve ser maior ou igual a {system}, mas é {input_len}","checker.maxLength":"O comprimento de {location} deve ser menor ou igual a {system}, mas é {input_len}"},vocabulary:{}},ar:{messages:{"checker.required":"{location} مطلوب","checker.min":"يجب أن يكون {location} مساويًا أو أكبر من {system}، لكن المُدخل هو {input}","checker.max":"يجب أن يكون {location} مساويًا أو أصغر من {system}، لكن المُدخل هو {input}","checker.minLength":"يجب أن يكون طول {location} مساويًا أو أكبر من {system}، لكن الطول هو {input_len}","checker.maxLength":"يجب أن يكون طول {location} مساويًا أو أصغر من {system}، لكن الطول هو {input_len}"},vocabulary:{}},th:{messages:{"checker.required":"{location} เป็นสิ่งจำเป็น","checker.min":"{location} ควรจะเท่ากับหรือมากกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.max":"{location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.minLength":"ความยาวของ {location} ควรจะเท่ากับหรือมากกว่า {system} แต่ความยาวคือ {input_len}","checker.maxLength":"ความยาวของ {location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ความยาวคือ {input_len}"},vocabulary:{}},id:{messages:{"checker.required":"{location} wajib diisi","checker.min":"{location} harus sama dengan atau lebih besar dari {system}, tetapi input adalah {input}","checker.max":"{location} harus sama dengan atau lebih kecil dari {system}, tetapi input adalah {input}","checker.minLength":"Panjang {location} harus sama dengan atau lebih besar dari {system}, tetapi panjangnya {input_len}","checker.maxLength":"Panjang {location} harus sama dengan atau lebih kecil dari {system}, tetapi panjangnya {input_len}"},vocabulary:{}},fil:{messages:{"checker.required":"Ang {location} ay kinakailangan","checker.min":"Ang {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang input ay {input}","checker.max":"Ang {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang input ay {input}","checker.minLength":"Ang haba ng {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang haba ay {input_len}","checker.maxLength":"Ang haba ng {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang haba ay {input_len}"},vocabulary:{}},uk:{messages:{"checker.required":"{location} є обов'язковим","checker.min":"{location} повинен бути рівним або більшим за {system}, але ввідне значення {input}","checker.max":"{location} повинен бути рівним або меншим за {system}, але ввідне значення {input}","checker.minLength":"Довжина {location} повинна бути рівною або більшою за {system}, але довжина становить {input_len}","checker.maxLength":"Довжина {location} повинна бути рівною або меншою за {system}, але довжина становить {input_len}"},vocabulary:{}},vi:{messages:{"checker.required":"{location} là bắt buộc","checker.min":"{location} phải lớn hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.max":"{location} phải nhỏ hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.minLength":"Độ dài của {location} phải lớn hơn hoặc bằng {system}, nhưng độ dài là {input_len}","checker.maxLength":"Độ dài của {location} phải nhỏ hơn hoặc bằng {system}, nhưng độ dài là {input_len}"},vocabulary:{}}},ut={schema:at,defaultLocale:ct,locales:lt},ht=["en","zh-CN","zh-TW","ja","ko","de","fr","es","pt","ar","th","id","fil","uk","vi"];class Oe extends Error{constructor(e){super(`Unsupported locale: ${e}`),this.localeCode=e}}const dt={"en-us":"en","en-gb":"en",zh:"zh-CN","zh-hans":"zh-CN","zh-sg":"zh-CN",cn:"zh-CN","zh-hant":"zh-TW","zh-hk":"zh-TW","zh-mo":"zh-TW",tw:"zh-TW","ja-jp":"ja","ko-kr":"ko","de-de":"de","fr-fr":"fr","es-mx":"es","pt-br":"pt","pt-pt":"pt","ar-sa":"ar","th-th":"th","id-id":"id",tl:"fil","fil-ph":"fil","uk-ua":"uk","vi-vn":"vi"};function Be(i){if(typeof i!="string"||!i.trim())throw new Oe(i);const e=i.trim().replace(/_/g,"-").toLowerCase(),t=ht.find(r=>r.toLowerCase()===e);if(t)return t;const n=dt[e];if(!n)throw new Oe(i);return n}const ce=class ce{constructor(e,t){if(this.data=e,this.fallback=t,e.schema!=="teaql.i18n/v1")throw new Error("Unsupported i18n schema");Object.keys(e.locales).forEach(Be)}message(e,t){return this.data.locales[e]?.messages[t]??this.fallback?.data.locales[e]?.messages[t]??this.data.locales.en?.messages[t]??this.fallback?.data.locales.en?.messages[t]??t}translate(e,t){const r={required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"}[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,o=String(e.inputValue),s=typeof e.inputValue=="string"?[...e.inputValue].length:0;return e.message=this.message(t,r).split("{location}").join(e.location.nativePath()).split("{system}").join(String(e.systemValue)).split("{input}").join(o).split("{input_len}").join(String(s)),e}};ce.builtin=new ce(ut);let me=ce;const Qe=Symbol("teaql.context.schema-capability");function C(i){return Object.freeze(i.map(e=>Object.freeze({...e})))}class ft{#e;#t;constructor(e,t){this.#e=e,this.#t=Object.freeze({...t}),Object.freeze(this)}recover(){const e=[];let t=this;for(;t;)e.push(t.#t),t=t.#e;return C(e.reverse())}}function gt(i,e,t,n,r){const o=i?r:n;if(i&&(typeof o!="string"||new RegExp("^\\p{White_Space}*$","u").test(o)))return i;const s=String(t),a=/^(0|[1-9][0-9]*)$/.test(s)&&BigInt(s)<=18446744073709551615n?t:void 0;return new ft(i,{kind:"auditReason",name:e,entityId:a,detail:o})}const pt=new Set(["comment","purpose","auditReason"]),ue=i=>!new RegExp("^\\p{White_Space}*$","u").test(i);function ye(i,e,t){const n=s=>{for(let a=i.length-1;a>=0;a--)if(i[a].kind===s)return i[a].detail??""},r=["operation","provider","sql"].every(s=>i.some(a=>a.kind===s));let o;if(r)o=i.filter(s=>!pt.has(s.kind));else{const s=i.find(c=>ue(c.name))?.name??"unknown";let a=s;if(t!=="select")for(const c of i)c.kind==="entity"&&ue(c.name)&&(a=c.name);o=[{kind:"operation",name:s,detail:t==="select"?"query":"mutation"},{kind:t==="select"?"request":"entity",name:t==="select"?s:a,detail:""},...i.filter(c=>c.kind==="relation"),{kind:"provider",name:ue(e)?e:"unknown",detail:""},{kind:"sql",name:t,detail:""}]}return Object.freeze({tracePath:C(o),comment:n("comment"),purpose:n("purpose"),auditReason:n("auditReason")})}function ze(i,e,t){return C([{kind:"comment",name:i,detail:e},{kind:"purpose",name:i,detail:t}])}function mt(i,e,t,n){if(n&&!i.trim())throw new Error("Missing SQL template");let r=0;const o=new Set,s=u=>{if(u<0||u>=e.length)throw new Error("SQL bind count mismatch");return o.add(u),n?n(u):Ue(e[u],t)};let a="",c="sql";for(let u=0;u=0&&h=0&&ht.toString(16).padStart(2,"0")).join("")}'`:_(typeof i=="object"?JSON.stringify(i):String(i))}function _(i){return`'${i.replace(/'/g,"''")}'`}var yt={};const wt="TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS",bt="I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK",te="[REDACTED]",he="[REDACTED SQL; NOT REPLAYABLE]",St=`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN -`;let Re=!1;function vt(i){const e=Array.from(i);return e.length<8||/^[0-9]+$/.test(i)?"*".repeat(e.length):e.slice(0,2).join("")+"*".repeat(e.length-4)+e.slice(-2).join("")}function Et(){const e=yt?.[wt]===bt;return e&&!Re&&(Re=!0,console.warn("TeaQL: sensitive plaintext logging enabled; application data may be written to disk. Authentication secrets remain redacted.")),e}function W(i){const e=i.toLowerCase().replace(/[^a-z0-9]/g,"");return["password","passwd","passphrase","privatekey","secret","accesstoken","refreshtoken","idtoken","apikey","authorization","credential","sessiontoken","magiclinktoken"].some(t=>e.includes(t))}function we(i){return Array.isArray(i)?i.some(we):i&&typeof i=="object"?Object.entries(i).some(([e,t])=>W(e)||we(t)):!1}function q(i){return i==null||i===""?[]:Array.isArray(i)?i.flatMap(q):i instanceof Date?[i.toISOString()]:typeof i=="object"?Object.values(i).flatMap(q):[String(i)]}function V(i,e){return[...new Set(e)].sort((t,n)=>n.length-t.length).reduce((t,n)=>t?.split(n).join(te),i)}const K=new WeakMap,be=new WeakMap,Ve=new WeakMap;function ke(i,e,t=[]){Ve.set(i,{bindings:e?R(e):void 0,intentValues:Object.freeze(t.map(G))})}function ie(i){const e=i.parameterLogPolicies,t=!!e&&e.length===i.parameters.length,n=W(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!t);return i.parameters.map((r,o)=>{if(n||we(r))return"credential";const s=t?e[o]:void 0;return s==="plain"||s==="masked"||s==="credential"?s:"unknown"})}function Se(i,e){return i==="credential"||i==="unknown"||!e&&i!=="plain"}function Ce(i){if(!i)return[];const e=ie(i);return i.parameters.flatMap((t,n)=>Se(e[n],!1)?q(t):[])}function G(i){return i instanceof Date?new Date(i.getTime()):i instanceof Uint8Array?new Uint8Array(i):Array.isArray(i)?Object.freeze(i.map(G)):i&&typeof i=="object"?Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,G(t)]))):i}function R(i,e){const t=e?[e,i]:[i];return Object.freeze({parameterizedSQL:"",sqlOrigin:"generated",parameters:Object.freeze(t.flatMap(n=>n.parameters.map(G))),parameterLogPolicies:Object.freeze(t.flatMap(ie))})}function ve(i){return i==null?null:Array.isArray(i)?i.map(ve):i&&typeof i=="object"&&"type"in i?ve(i.value):typeof i=="object"&&!(i instanceof Date)?te:vt(i instanceof Date?i.toISOString():String(i))}function Ke(i,e,t=[]){const n=Et()&&i.logMode!=="masked",r=K.get(i);if(r!==void 0&&(!r||n))return i;const o=be.get(i);if(!n&&o)return o;const s=ne(i,n,e,t);if(K.set(s,n),n){const a=ne(i,!1,e,t);K.set(a,!1),be.set(s,a)}return s}function It(i){const e=be.get(i);if(e)return e;if(K.get(i)===!1)return i;const t=ne(i,!1);return K.set(t,!1),t}function ne(i,e,t,n=[]){const r=Ve.get(i);r?.bindings&&(t=R(r.bindings,t)),r&&(n=[...n,...r.intentValues]);const o=i.parameterLogPolicies,s=!o||o.length===i.parameters.length,a=W(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!o||!s),c=ie(i),u=c.map(w=>Se(w,e)),l=i.parameters.flatMap((w,v)=>u[v]?q(w):[]);if(t){const w=ie(t);l.push(...t.parameters.flatMap((v,I)=>Se(w[I],e)?q(v):[]))}const f=[...l,...n.flatMap(q)],g=!e&&i.logMode==="debug-plaintext"&&!t,h=w=>g&&w?te:V(w,f),p=i.parameters.map((w,v)=>u[v]?c[v]==="masked"?ve(w):te:G(w)),m=i.parameterizedSQL.replace(/\$[0-9]+|@p[0-9]+/gi,"?"),y=(!e||a)&&i.sqlOrigin!=="generated"&&/['"`$]|--|\/\*|\b\d+\b|:[A-Za-z_]/.test(m),d=i.databaseKind??"sqlite";let b=he,E=y?"untrusted-literal-sql":s?void 0:"policy-count-mismatch";if(!y&&s)try{b=mt(i.parameterizedSQL,p,d,w=>Ue(p[w],d)+(u[w]?" /* masked */":"")),b=(e?u.some(Boolean)?`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN; PARTIALLY MASKED; NOT REPLAYABLE -`:St:`-- TeaQL MASKED; NOT REPLAYABLE -`)+b}catch{b=he,E="unsupported-or-mismatched-bindings"}return Object.freeze({...i,...i.statements?{statements:Object.freeze(i.statements.map(w=>ne(w,e,R(i,t),n)))}:{},parameterizedSQL:y?he:i.sqlOrigin==="generated"?i.parameterizedSQL:V(i.parameterizedSQL,l),parameters:Object.freeze(p),parameterLogPolicies:Object.freeze(c),maskedParameters:Object.freeze(u),logMode:e?"debug-plaintext":"masked",omissionReason:E,debugSQL:b,comment:h(i.comment),purpose:h(i.purpose),auditReason:h(i.auditReason),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},resultSummary:i.resultCount!==void 0?`${i.resultCount} rows returned`:i.affectedRows!==void 0?`${i.affectedRows} rows affected`:V(i.resultSummary,l),tracePath:Object.freeze(i.tracePath.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I]))))),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},...i.mutationLineage?{mutationLineage:Object.freeze(i.mutationLineage.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{}})}const H=new WeakMap,re=new WeakMap;function _e(i){return re.get(i)}function Lt(i,e){re.set(i,e)}function $t(i){return H.get(i)}function Q(i,e){H.set(e,H.get(i)??M(i))}function M(i,e=new Map){if(!i||typeof i!="object")return i;if(e.has(i))return e.get(i);if(i instanceof Date)return new Date(i.getTime());if(i instanceof Uint8Array)return new Uint8Array(i);const t=Array.isArray(i)?[]:Object.create(Object.getPrototypeOf(i));e.set(i,t);for(const o of Reflect.ownKeys(i)){const s=Object.getOwnPropertyDescriptor(i,o);"value"in s&&s.enumerable&&(s.value=M(s.value,e)),Object.defineProperty(t,o,s)}const n=H.get(i);n&&H.set(t,n);const r=re.get(i);return r&&re.set(t,r),t}const X=new WeakMap;class Le{#e;constructor(e={}){this.#e=M(e),Object.freeze(this)}values(){return M(this.#e)}static captureFor(e,t){const n=new Le(t);return X.set(e,n),n}static forEntity(e){return X.get(e)}static restoreFor(e,t){t?X.set(e,t):X.delete(e)}}const Pe=new WeakMap,de=new WeakMap,Ee=new WeakMap,We=new WeakMap;function Ge(i){if(!["named-count","facet","relation-count","relation-select","aggregate","pagination"].includes(i.kind)||i.method!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i.method)||i.alias!==void 0&&typeof i.alias!="string"||i.relation!==void 0&&typeof i.relation!="string")throw new Error("QUERY_OPERATION_INVALID: invalid generated operation descriptor");return Object.freeze({kind:i.kind,method:i.method,alias:i.alias,relation:i.relation})}function Tt(i){const e=Ge(i),t=n=>"'"+n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+"'";return e.method?e.method+"("+(e.alias!==void 0?t(e.alias):e.kind==="relation-select"?"...":"")+")":"framework: "+e.kind+(e.relation?" "+e.relation:"")+(e.alias!==void 0?" "+t(e.alias):"")}const F=Symbol("runtime request binding");class At extends Error{constructor(e,t,n){super(`${e}: ${n} request requires a non-blank ${t}; supply it at the request entry point`),this.code=e,this.field=t,this.requestKind=n,this.name="RequestIntentError"}}function B(i,e,t){if(typeof i!="string"||new RegExp("^\\p{White_Space}*$","u").test(i))throw new At(e==="comment"?"REQUEST_COMMENT_REQUIRED":"QUERY_PURPOSE_REQUIRED",e,t);return i}class se{#e;#t;constructor(e,t){this.#e=B(e,"comment","query"),this.#t=B(t,"purpose","query"),Object.freeze(this)}get comment(){return this.#e}get purpose(){return this.#t}}class z{#e;constructor(e){this.#e=B(e,"comment","mutation"),Object.freeze(this)}get comment(){return this.#e}get auditReason(){return this.#e}readbackIntent(){return new se(this.#e,"verify persisted mutation result")}}class L{#e;#t;#n;#r;#s;#o;#i;constructor(e,t,n){const r=e,o=_e(e),s=o instanceof L?o:void 0;if(this.#e=t===void 0?s?.intent??new se(r?._comment??r?.commentText,r?._purpose??r?.purposeText):new se(t?.comment,t?.purpose),n&&n[F]!==!0)throw new Error("QUERY_REQUEST_OWNERSHIP_INVALID: request binding is runtime-owned");const a=s&&s.intent.comment===this.#e.comment&&s.purpose===this.#e.purpose?s:void 0;this.#i=n?.invocation??(n?.parent?n.parent.#i:void 0)??(a?a.#i:void 0)??Object.freeze({}),this.#n=n?n.parent:a?.parentRequest,this.#r=B(n?.comment??a?.comment??this.#e.comment,"comment","query"),this.#s=n?.name??a?.requestName??String(r.entity??"query"),this.#o=n?.operation??a?.operation,this.#t=M(e);const c=this.#t;for(const[u,l]of[["commentText",this.comment],["purposeText",this.purpose],["_comment",this.comment],["_purpose",this.purpose]])Object.defineProperty(c,u,{value:l,enumerable:!u.startsWith("_"),configurable:!0,writable:!1});de.set(c,C(n?.source??a?.traceSource??de.get(e)??ze(String(r.entity),this.intent.comment,this.purpose))),Lt(c,this),Object.freeze(this)}get intent(){return this.#e}get query(){return this.#t}get comment(){return this.#r}get purpose(){return this.#e.purpose}get traceSource(){return de.get(this.#t)}get parentRequest(){return this.#n}get rootRequest(){let e=this;for(;e.parentRequest;)e=e.parentRequest;return e}get requestName(){return this.#s}get operation(){return this.#o}get traceChain(){const e=[];for(let t=this;t;t=t.parentRequest)e.push({kind:"comment",name:t.requestName,detail:t.comment});return C([{kind:"purpose",name:this.rootRequest.requestName,detail:this.purpose},...e.reverse()])}withQuery(e){const t=_e(e);if(t instanceof L&&t.#i!==this.#i)throw new Error("QUERY_SCOPE_OWNER_MISMATCH: replacement belongs to another query invocation");return new L(e,this.intent,{[F]:!0,parent:this.parentRequest,comment:this.comment,name:this.requestName,operation:this.operation,source:this.traceSource,invocation:this.#i})}deriveOperation(e,t){const n=Ge(t);return new L(e,this.intent,{[F]:!0,parent:this,comment:Tt(n),name:String(e.entity??this.requestName),operation:n,source:this.traceSource})}deriveHelper(e,t){return new L(e,this.intent,{[F]:!0,parent:this,comment:B(t,"comment","query"),name:String(e.entity??this.requestName),source:this.traceSource})}derive(e,t,n){if(n)return this.deriveOperation(this.query,n).deriveChild(e,t);const r=`${String(this.query.entity)}.${t}`;return this.deriveChild(e,t,void 0,r)}deriveAggregate(e,t,n){const r=this.parentRequest?.operation?.kind==="facet"?this.parentRequest:void 0,o=r?r.deriveHelper(e,"aggregate "+r.operation.relation):this.deriveOperation(e,n),s=[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}],a=new L(e,this.intent,{[F]:!0,parent:o.parentRequest,comment:o.comment,name:o.requestName,operation:o.operation,source:s});return(e._comment??e.commentText)===void 0?a:a.deriveChild(e)}deriveChild(e,t,n,r){const o=e,s=o._comment??o.commentText;return new L(e,this.intent,{[F]:!0,parent:this,comment:s===void 0?n??`load ${String(o.entity)}`:B(s,"comment","query"),name:r??String(o.entity),source:t===void 0?this.traceSource:[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}]})}}class x{#e;#t;constructor(e,t){this.#e=new z(t===void 0?e?.comment:t?.comment),this.#t={...e},Object.defineProperty(this.#t,"comment",{value:this.#e.comment,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get intent(){return this.#e}get mutation(){return this.#t}get comment(){return this.#e.comment}withLoadedSnapshot(e){return Pe.set(this,new Le(e.values())),this}loadedValues(){return Pe.get(this)?.values()??{}}get graphSession(){return Ee.get(this)?.session}scopeFor(e){const t=Ee.get(this),n=gt(t?.parent,e.entity,e.id,this.comment,t?.localComment);return t&&We.set(n,t.session),n}traceFor(e){const t=this.#t,n=t.ledgerRoot?.traceChain(t.ledgerKey??e);return n?.length?C(n):this.scopeFor(e).recover()}auditProjection(e,t,n){const r=[...q(t),...q(this.#t.id),...n?Ce(n):q(this.loadedValues()),...Ce(this.graphSession?.logBindings)];return Object.freeze({reason:V(this.comment,r),mutationLineage:C(this.traceFor(e).map(o=>({...o,detail:V(o.detail,r)})))})}}class Ot{#e;#t;constructor(e){this.#e=new z(e?.comment),Object.freeze(this)}get intent(){return this.#e}request(e,t,n){if(t&&We.get(t)!==this)throw new Error("GRAPH_TRACE_SCOPE_MISMATCH: parent scope belongs to another graph invocation");const r=new x(e,this.#e);return Ee.set(r,{session:this,parent:t,localComment:n}),r}captureLogBindings(e){this.#t=R(e,this.#t)}get logBindings(){return this.#t}}class qe extends Error{constructor(e){super("GRAPH_ALREADY_COMMITTED: post-commit processing failed; do not retry as an uncommitted mutation"),this.cause=e,this.committed=!0,this.name="GraphCommittedError"}}const Rt="MUTATION-POLICY-001",kt="MUTATION-POLICY-002";class k extends Error{constructor(e){super(e),this.name="MutationPolicyError"}}class ci{constructor(e){this.resolver=e}resolve(e){return this.resolver(e)}}class li{constructor(e){this.finder=e}findApproval(e){return this.finder(e)}}class Ct{onWarning(e,t){!t.firstOccurrence||typeof console>"u"||console.warn(`TeaQL mutation policy warning code=${t.warningCode} requestKey=${t.snapshot.requestKey} source=${t.snapshot.source} approval=${t.snapshot.approvalStatus}`)}}let Ne=0;class _t{constructor(){this.profile={warningSink:new Ct},this.emittedWarnings=new Set,this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.remaining=new Map}setRegistry(e){this.profile.registry=e}setApprovalProvider(e){this.profile.approvalProvider=e}setWarningSink(e){this.profile.warningSink=e}beginGraph(){if(this.graphActive)throw new k("mutation policy graph is already active");this.graphActive=!0,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}endGraph(){this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}recordPreflight(e){if(!this.graphActive)return;if(this.graphReviewed)throw new k("mutation preflight cannot change after policy review");const t=xe(e);this.rootEntity??=t.entity,this.auditReason??=J(e),this.preflight.push(t),this.preflightKeys.push(Me(e,t))}enterMutation(e,t){const n=xe(t);if(!this.graphActive)return{snapshot:this.review(e,this.plan(n.entity,J(t),[n]))};if(!this.graphReviewed){if(this.profile.registry&&this.preflight.length===0)throw new k("customer mutation policy requires complete graph preflight before provider mutation");if(!this.profile.registry&&this.preflight.length===0)return{snapshot:this.review(e,this.plan(n.entity,J(t),[n]))};const r=this.preflight.length?this.preflight:[n];this.graphSnapshot=this.review(e,this.plan(this.rootEntity??r[0].entity,this.auditReason??J(t),r)),this.remaining.clear();const o=this.preflight.length?this.preflightKeys:r.map(Ye);for(const s of o)this.remaining.set(s,(this.remaining.get(s)??0)+1);this.graphReviewed=!0}return this.consume(Me(t,n)),{snapshot:this.graphSnapshot}}ensureGraphComplete(){if(this.graphReviewed&&this.remaining.size)throw new k("reviewed mutation plan contains operations that were not executed")}review(e,t){Pt(t);const n=je(t),r=this.profile.registry?.resolve(n.requestKey);let o,s,a,c;if(!r)o="generated_default",a="not_applicable",c=[Rt];else{s=qt(r.identity);const l=r.review(e,n);if(!l||l.verdict!=="allow"&&l.verdict!=="deny")throw new k("customer mutation policy returned an invalid decision");if(l.verdict==="deny")throw new k(`[MUTATION POLICY DENIED] ${l.code||"MUTATION-POLICY-DENIED"}: ${l.message||"mutation rejected"}`);o="customer";const f=this.profile.approvalProvider?.findApproval(s);a=Nt(f,s)?"approved":"missing",c=a==="approved"?[]:[kt]}const u=Object.freeze({executionId:n.executionId,requestKey:n.requestKey,source:o,policy:s,approvalStatus:a,warningCodes:Object.freeze([...c]),operations:Object.freeze(n.operations.map(l=>Object.freeze({kind:l.kind,entity:l.entity,entityId:j(l.entityId),changedFields:Object.freeze(Object.keys(l.changedValues).sort())})))});for(const l of c)this.emitWarning(e,u,l);return u}plan(e,t,n){return Ne+=1,je({executionId:`teaql-mutation-${Ne}`,requestKey:`${e}.saveGraph`,rootEntityType:e,auditReason:new z(t).comment,operations:n})}consume(e){const t=this.remaining.get(e)??0;if(t<1)throw new k("provider mutation is not present in the reviewed graph plan");t===1?this.remaining.delete(e):this.remaining.set(e,t-1)}emitWarning(e,t,n){const r=t.policy?`${t.policy.policyId}:${t.policy.version}:${t.policy.fingerprint}`:"none",o=`${t.requestKey}|${r}|${n}`,s=!this.emittedWarnings.has(o);this.emittedWarnings.add(o);try{this.profile.warningSink.onWarning(e,Object.freeze({snapshot:t,warningCode:n,firstOccurrence:s}))}catch{}}}function xe(i){const e=String(i?.entity??"").trim(),t=String(i?.action??"").toLowerCase(),n={create:"create",update:"update",delete:"delete",recover:"recover"};if(!e||!n[t])throw new k("mutation must contain a supported entity operation");const r=i?.payload&&typeof i.payload=="object"?i.payload:{};return Object.freeze({kind:n[t],entity:e,entityId:j(i?.id??r.id),originalVersion:i?.version??i?.expectedVersion,changedValues:He(r)})}function J(i){return new z(i?.comment).comment}function Pt(i){if(new z(i?.auditReason),!i.executionId?.trim())throw new k("execution id is required");if(!i.requestKey?.trim())throw new k("request key is required");if(!i.rootEntityType?.trim())throw new k("root entity type is required");if(!i.operations.length)throw new k("mutation plan is empty")}function qt(i){if(!i||!i.policyId?.trim()||!i.version?.trim()||!i.fingerprint?.trim())throw new k("customer mutation policy identity is invalid");return Object.freeze({policyId:i.policyId.trim(),version:i.version.trim(),fingerprint:i.fingerprint.trim()})}function Nt(i,e){return!!i&&xt(i.policy,e)&&!!i.approvedBy?.trim()&&i.approvedAt instanceof Date&&Number.isFinite(i.approvedAt.getTime())&&i.approvedAt.getTime()!==0}function xt(i,e){return i.policyId===e.policyId&&i.version===e.version&&i.fingerprint===e.fingerprint}function je(i){return Object.freeze({executionId:i.executionId,requestKey:i.requestKey,rootEntityType:i.rootEntityType,auditReason:i.auditReason,operations:Object.freeze(i.operations.map(e=>Object.freeze({kind:e.kind,entity:e.entity,entityId:j(e.entityId),originalVersion:e.originalVersion,changedValues:He(e.changedValues)})))})}function j(i,e=new WeakSet){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||typeof i=="bigint")return i;if(i instanceof Date)return i.toISOString();if(typeof i=="object"){if(e.has(i))throw new k("mutation policy values must not contain cycles");e.add(i);try{if(Array.isArray(i))return Object.freeze(i.map(n=>j(n,e)));const t=i;return"id"in t&&Object.keys(t).some(n=>n!=="id")?j(t.id,e):Object.freeze(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,j(r,e)])))}finally{e.delete(i)}}return String(i)}function He(i){return Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,j(t)])))}function Ye(i){return oe({kind:i.kind,entity:i.entity,entityId:i.entityId,originalVersion:i.originalVersion,changedValues:i.changedValues})}function Me(i,e){const t=i?.ledgerKey;return t&&typeof t=="object"&&String(t.entity??"").trim()&&t.id!==void 0&&t.id!==null?`ledger:${String(t.entity).trim()}:${oe(t.id)}`:`operation:${Ye(e)}`}function oe(i){return typeof i=="bigint"?JSON.stringify(`${i.toString()}n`):i===void 0?'""':i===null||typeof i!="object"?JSON.stringify(i):Array.isArray(i)?`[${i.map(oe).join(",")}]`:`{${Object.entries(i).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${oe(t)}`).join(",")}}`}const De=new WeakMap;let jt=1;function Mt(i){if(!i||typeof i!="object"&&typeof i!="function")return String(i);const e=i;let t=De.get(e);return t||(t=jt++,De.set(e,t)),String(t)}class Fe extends Error{constructor(e,t,n){super(`context root ${e}: expected ${t}`),this.reason=e,this.expectedType=t,this.activeRoot=n,this.name="ContextRootError"}}class Dt{constructor(){this.mutationPolicy=new _t,this.resources=new Map,this.continuousPageCursors=new Map,this.retainedIdSets=new Map,this.idSetBuilds=new Map,this.continuousPageRuntime={owner:"",get:(e,t)=>this.getContinuousPageCursor(e,t),put:(e,t,n)=>this.putContinuousPageCursor(e,t,n),observe:(e,t)=>{this.continuousPagePlan=e,this.continuousPageCursorId=t}},this.idSetPaginationRuntime={owner:"",scope:"",get:e=>this.idSetStore().get(e),put:(e,t)=>this.idSetStore().put(e,t),build:(e,t)=>this.singleFlightIdSetBuild(e,t),observe:(e,t)=>{this.idSetPaginationPlan=e,this.idSetPaginationCount=t,this.idSetPaginationCountAccuracy=e==="ID_SET_BUILD"||e==="ID_SET_HIT"?"EXACT":e==="ID_SET_FALLBACK_LIMIT_EXCEEDED"?"LOWER_BOUND":"UNKNOWN"}},this.userIdentifier="",this.continuousPagePlan="DISABLED",this.idSetPaginationPlan="ID_SET_DISABLED",this.idSetPaginationCountAccuracy="UNKNOWN",this.locale="en",this.i18nCatalog=me.builtin}async withQueryRequest(e,t){const n=this.requireResource("dataService");return n.withQueryRequest?n.withQueryRequest(e,t):t()}setLocaleCode(e){const t=Be(e);return this.locale=t,this}setLanguageCode(e){return this.setLocaleCode(e)}installI18nCatalog(e){if(!e)throw new Error("catalog is required");return this.i18nCatalog=e,this}installIdSetPaginationStore(e){if(!e)throw new Error("ID set pagination store is required");return this.insertResource("idSetPaginationStore",e)}translateCheckResults(e){return e.map(t=>this.i18nCatalog.translate(t,this.locale))}withMutationPolicyRegistry(e){if(!e||typeof e.resolve!="function")throw new TypeError("mutation policy registry must expose resolve(requestKey)");return this.mutationPolicy.setRegistry(e),this}withMutationPolicyApprovalProvider(e){if(!e||typeof e.findApproval!="function")throw new TypeError("mutation policy approval provider must expose findApproval(identity)");return this.mutationPolicy.setApprovalProvider(e),this}withMutationGovernanceSink(e){if(!e||typeof e.onWarning!="function")throw new TypeError("mutation governance sink must expose onWarning(context, warning)");return this.mutationPolicy.setWarningSink(e),this}reviewMutationPlan(e){return this.mutationPolicy.review(this,e)}beginMutationPolicyGraph(){this.mutationPolicy.beginGraph()}recordMutationPolicyPreflight(e){this.mutationPolicy.recordPreflight(e)}enterMutationPolicy(e){return this.mutationPolicy.enterMutation(this,e).snapshot}ensureMutationPolicyGraphComplete(){this.mutationPolicy.ensureGraphComplete()}endMutationPolicyGraph(){this.mutationPolicy.endGraph()}beginFixEvidence(){return this.insertResource("fixEvidenceCurrent",[])}recordFixEvidence(e){const t=String(e.sourceLabel||""),n=t.toLowerCase();if(!e.entityType||!e.modelPath||!t||n.includes("authorization")||n.includes("cookie")||n.includes("token="))throw new TypeError("Fix evidence must contain only safe framework provenance labels");const r=this.getResource("fixEvidenceCurrent")??[];return this.getResource("fixEvidenceCurrent")||this.insertResource("fixEvidenceCurrent",r),r.push(Object.freeze({...e})),this}finishFixEvidence(){const e=this.getResource("fixEvidenceCurrent")??[];return this.insertResource("fixEvidenceLast",Object.freeze([...e])),this.removeResource("fixEvidenceCurrent")}lastFixEvidence(){return this.getResource("fixEvidenceLast")??[]}insertResource(e,t){return this.resources.set(e,t),this}getResource(e){return this.resources.get(e)}removeResource(e){return this.resources.delete(e),this}requireResource(e){const t=this.getResource(e);if(t===void 0)throw new Error(`Required UserContext resource is missing: ${e}`);return t}ensureSchema(){const e=this.requireResource("dataService"),t=e[Qe];if(!t)throw new Error("Configured dataService is not a schema-aware TeaQL provider");return t.call(e,this)}withActiveRoot(e){if(!e||!e.entity||e.id===void 0||e.id===null)throw new TypeError("active root must be a typed entity reference");return this.insertResource("activeRoot",Object.freeze({...e}))}requireActiveRoot(e){const t=this.getResource("activeRoot");if(!t)throw new Fe("missing",e);if(t.entity!==e)throw new Fe("type_mismatch",e,t);return t}prepareQuery(e){this.continuousPageRuntime.owner=this.userIdentifier,this.idSetPaginationRuntime.owner=this.userIdentifier;const t=this.getResource("activeRoot");return this.idSetPaginationRuntime.scope=[this.userIdentifier,t?`${t.entity}:${String(t.id)}`:"-",Mt(this.getResource("dataService"))].join("|"),e.bindContinuousPageRuntime(this.continuousPageRuntime).bindIdSetPaginationRuntime(this.idSetPaginationRuntime)}getContinuousPageCursor(e,t){const n=`${e}:${t}`,r=this.continuousPageCursors.get(n);if(r&&r.expiresAt<=Date.now()){this.continuousPageCursors.delete(n);return}return r}putContinuousPageCursor(e,t,n){if(this.continuousPageCursors.size>=4096){const r=[...this.continuousPageCursors.entries()].sort((o,s)=>o[1].expiresAt-s[1].expiresAt)[0];r&&this.continuousPageCursors.delete(r[0])}this.continuousPageCursors.set(`${e}:${t}`,n)}getRetainedIdSet(e){const t=this.retainedIdSets.get(e);if(t&&t.expiresAt<=Date.now()){this.retainedIdSets.delete(e);return}return t}idSetStore(){return this.getResource("idSetPaginationStore")??{get:e=>this.getRetainedIdSet(e),put:(e,t)=>this.putRetainedIdSet(e,t),invalidate:e=>{this.retainedIdSets.delete(e)}}}putRetainedIdSet(e,t){if(t.ids.byteLength>268435456)throw new Error("ID set exceeds the process-local store memory ceiling");const r=()=>[...this.retainedIdSets.values()].reduce((o,s)=>o+s.ids.byteLength,0);for(;this.retainedIdSets.size>=64||r()+t.ids.byteLength>268435456;){const o=[...this.retainedIdSets.entries()].sort((s,a)=>s[1].expiresAt-a[1].expiresAt)[0];if(!o)break;this.retainedIdSets.delete(o[0])}this.retainedIdSets.set(e,t)}async singleFlightIdSetBuild(e,t){const n=this.idSetBuilds.get(e);if(n)return{value:await n,built:!1};const r=t();this.idSetBuilds.set(e,r);try{return{value:await r,built:!0}}finally{this.idSetBuilds.delete(e)}}}function Xe(i,e){const t=i.defaultDomainRoot,n=e.defaultDomainRoot;if(t&&n&&(t.entity!==n.entity||t.id!==n.id))throw new Error("Cannot compose Runtime Modules with different Default Domain Roots");const r=new Map;for(const o of[...i.constants??[],...e.constants??[]])r.set(`${o.entity}:${o.id}`,o);return{defaultDomainRoot:n??t,constants:[...r.values()],ensure:i.ensure&&e.ensure?async o=>{await i.ensure(o),await e.ensure(o)}:e.ensure??i.ensure}}class Je{constructor(e={},t={},n={}){this.schemas=Object.freeze({...e}),this.checkers=Object.freeze({...t}),this.bootstrap=Object.freeze({defaultDomainRoot:n.defaultDomainRoot,constants:Object.freeze([...n.constants??[]]),ensure:n.ensure})}and(e){return new Je({...this.schemas,...e.schemas},{...this.checkers,...e.checkers},Xe(this.bootstrap,e.bootstrap))}}class P{constructor(e,t,n){this.field=e,this.expr=t,this.direction=n}static new(e,t){return new P(e,null,t)}static expr(e,t){return new P("",e,t)}static asc(e){return P.new(e,"Asc")}static desc(e){return P.new(e,"Desc")}}class ae{constructor(e,t,n,r){this.enabledValue=e,this.cacheExpiredMillis=t,this.propagateValue=n,this.propagateCacheExpiredMillis=r}static enabled(e){return new ae(!0,e,!1,0)}propagate(e){return this.propagateValue=!0,this.propagateCacheExpiredMillis=e,this}}let Ft=class Ze{constructor(e){this.hardLimitValue=1e4,this.filterCondition=null,this.limitValue=0,this.offsetValue=0,this.orderItems=[],this.selectItems=[],this.properties=[],this.joins=[],this.groupByItems=[],this.aggregateItems=[],this.facets=[],this.relations=[],this.relationAggregates=[],this.entity=e,Object.defineProperty(this,"hardLimitValue",{enumerable:!1,writable:!0,value:1e4}),Object.defineProperty(this,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"topNProbeThreshold",{enumerable:!1,writable:!0,value:void 0})}comment(e){return this.commentText=e,this}purpose(e){return this.purposeText=e,this}facetBy(e,t,n,r=!0,o){return this.facets.push({facetName:e,relationName:t,query:n.toQuery(),includeAllFacets:r,operation:o}),this}clone(){const e=M(this);for(const t of["commentText","purposeText","_comment","_purpose"]){const n=Object.getOwnPropertyDescriptor(e,t);n&&"value"in n&&n.configurable&&Object.defineProperty(e,t,{...n,writable:!0})}return e}filter(e){return this.filterCondition=e,this}limit(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.limitValue=e,this}optimizeForContinuousPageFetch(){return this.optimizeForContinuousPageFetchWith("default",600)}optimizeForContinuousPageFetchWith(e,t){if(!e?.trim())throw new Error("continuous page namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("continuous page ttlSeconds must be a positive integer");return this.continuousPageFetchOptions={namespace:e,ttlSeconds:t},this}bindContinuousPageRuntime(e){return this.continuousPageRuntimeContext=e,this}localContinuousPageOptions(){return this.continuousPageFetchOptions}localContinuousPageRuntime(){return this.continuousPageRuntimeContext}clearContinuousPageRuntime(){return this.continuousPageRuntimeContext=void 0,this}optimizePaginationWithIdSet(){return this.optimizePaginationWithIdSetConfig("default",600,3e6)}optimizePaginationWithIdSetConfig(e,t,n){if(!e?.trim())throw new Error("ID set namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("ID set ttlSeconds must be a positive integer");if(!Number.isSafeInteger(n)||n<=0)throw new Error("ID set maxIds must be a positive integer");return this.idSetPaginationOptions={namespace:e,ttlSeconds:t,maxIds:n},this}bindIdSetPaginationRuntime(e){return this.idSetPaginationRuntimeContext=e,this}localIdSetPaginationOptions(){return this.idSetPaginationOptions}localIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext}clearIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext=void 0,this}topNProbeParentThreshold(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("topNProbeParentThreshold must be a non-negative safe integer");return this.topNProbeThreshold=e,this}localTopNProbeParentThreshold(){return this.topNProbeThreshold}prepareForList(){if(!Number.isSafeInteger(this.offsetValue)||this.offsetValue<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");if(this.limitValue&&(!Number.isSafeInteger(this.limitValue)||this.limitValue<1))throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.applyListLimit(this.hardLimitValue),this}forExactCount(e="__teaql_total"){const t=new Ze(this.entity);return t.filterCondition=M(this.filterCondition),t.commentText=this.commentText,t.purposeText=this.purposeText,t.aggregate("Count","id",e),Q(this,t),t}applyListLimit(e){if(this.limitValue||(this.limitValue=e),this.limitValue>e)throw new Error(`QUERY_HARD_LIMIT_EXCEEDED: requested limit ${this.limitValue} exceeds hard limit ${e}`);for(const t of this.relations)t.query?.applyListLimit(1e4)}offset(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");return this.offsetValue=e,this}relation(e){return this.relations.push({name:e}),this}relationQuery(e,t,n="id",r="id",o=!0,s){return this.relations.push({name:e,query:t,localKey:n,foreignKey:r,many:o,operation:s}),this}relationAggregate(e,t,n,r=!0,o){return this.relationAggregates.push({relationName:e,alias:t,query:n,singleResult:r,operation:o}),this}order(e){return this.orderItems.push(e),this}select(e){return this.selectItems.push(...e),this}enableAggregationCacheFor(e){return this.aggregationCache=ae.enabled(e),this}propagateAggregationCache(e){return this.aggregationCache||(this.aggregationCache=ae.enabled(0)),this.aggregationCache.propagate(e),this}aggregate(e,t,n){return this.aggregateItems.push({function:e,field:t,alias:n}),this}groupBy(e){return this.groupByItems.push(e),this}};function Bt(i,e){if(i.logMode!=="masked")throw new Error("Telemetry requires safe SQL projection");const t=(n=[])=>JSON.stringify(n.map(r=>({kind:r.kind,name:r.name,detail:r.detail??""})));return Object.freeze({body:"TeaQL SQL execution",correlation:e,attributes:Object.freeze({"teaql.trace_chain":t(i.traceChain),"teaql.trace_path":t(i.tracePath),"teaql.mutation_lineage":t(i.mutationLineage),"teaql.intent.comment":i.comment??i.auditReason??"","teaql.intent.purpose":i.purpose??"","teaql.sql.debug":i.debugSQL,"teaql.sql.log_mode":i.logMode,"teaql.sql.operation":i.operation,"teaql.sql.outcome":i.executionOutcome??"unknown","teaql.sql.elapsed_us":i.elapsedMicros,...i.resultCount===void 0?{}:{"teaql.sql.result_count":i.resultCount},...i.affectedRows===void 0?{}:{"teaql.sql.affected_rows":i.affectedRows}})})}function fe(i,e=!1){try{e?console.warn(i):console.info(i)}catch{}}class Y extends Array{static get[Symbol.species](){return Array}constructor(e=[],t={}){typeof e=="number"?super(e):super(...e),Object.setPrototypeOf(this,Y.prototype),this.totalCount=t.totalCount,this.aggregations=t.aggregations??{},this.summary=t.summary??{},this.facets=t.facets??{},this.isLoaded=t.isLoaded??!0}static empty(){return new Y([],{isLoaded:!1})}get data(){return this}withTotalCount(e){return this.totalCount=e,this}withFacet(e,t){return this.facets[e]=t,this}facet(e){return this.facets[e]}totalCountOrLength(){return this.totalCount??this.length}}function Qt(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Ie(i){if(i&&typeof i=="object"){const e=i;return e.id??e.Id}return i}function zt(i,e){const t=Qt(e);for(const n of[e,`${e}Id`,t,`${t}_id`]){const r=Ie(i[n]);if(r!=null)return r}}function Ut(i){const e=i.function.toLowerCase();return e==="count"||e==="sum"?0:null}function Vt(i,e){return typeof i=="number"&&typeof e=="number"?i-e:i instanceof Date&&e instanceof Date?i.getTime()-e.getTime():String(i).localeCompare(String(e))}async function Kt(i,e,t,n,r,o){const s=n.clone();s.facets=[],s.relations=[],s.relationAggregates=[],s.orderItems=[],s.aggregateItems=[],s.groupByItems=[],s.offsetValue=0,s.limitValue=0,s.selectItems=[...new Set([r,...o.map(l=>l.field)])],s.comment(`aggregate ${r}`),Q(n,s);const a=await i.executeQuery(t.deriveHelper(e(s),`aggregate ${r}`).query),c=new Map,u=new Map;for(const l of a){const f=zt(l,r);if(f==null)continue;const g=String(f),h=c.get(g)??{},p=u.get(g)??{};for(const m of o){const y=m.function.toLowerCase(),d=l[m.field];if(y==="count")d!=null&&(h[m.alias]=Number(h[m.alias]??0)+1);else if(y==="sum"||y==="avg"){if(d!=null){const b=Number(d);if(!Number.isFinite(b))throw new Error(`Facet aggregate ${m.alias} requires numeric values`);h[m.alias]=Number(h[m.alias]??0)+b,y==="avg"&&(p[m.alias]=(p[m.alias]??0)+1)}}else if(y==="min"||y==="max"){if(d!=null){const b=h[m.alias],E=b==null?0:Vt(d,b);(b==null||y==="min"&&E<0||y==="max"&&E>0)&&(h[m.alias]=d)}}else throw new Error(`Unsupported facet aggregate: ${m.function}`)}c.set(g,h),u.set(g,p)}for(const[l,f]of c){const g=u.get(l)??{};for(const h of o){if(h.function.toLowerCase()!=="avg")continue;const p=g[h.alias]??0;f[h.alias]=p?Number(f[h.alias]??0)/p:null}}return c}async function et(i,e,t,n){const r=new L(t);t=r.query;const o={};for(const s of n){const a=r.deriveOperation(t,s.operation??{kind:"facet",relation:s.relationName,alias:s.facetName}),c=a.deriveChild(s.query.clone(),s.relationName),u=c.query,l=u.facets;u.facets=[];const f=u.aggregateItems.map(d=>({function:String(d.function),field:String(d.field),alias:String(d.alias)})),g=f.length?f:[{function:"Count",field:"id",alias:"__teaql_facet_membership_count"}];let h;if(i.executeFacetAggregates)h=await i.executeFacetAggregates(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName,g);else if(i.executeFacetMembership&&g.every(d=>d.function.toLowerCase()==="count")){const d=await i.executeFacetMembership(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName);h=new Map([...d].map(([b,E])=>[b,Object.fromEntries(g.map(S=>[S.alias,E]))]))}else h=await Kt(i,e,a,t,s.relationName,g);u.aggregateItems=[],u.groupByItems=[];for(const d of u.relationAggregates){if(d.query.entity!==t.entity)continue;const b=t.clone();b.selectItems=["id"],b.properties=[],b.relations=[],b.relationAggregates=[],b.facets=[],b.aggregateItems=[],b.groupByItems=[],b.orderItems=[],b.offsetValue=0,b.limitValue=0;const E={id:{$inSubquery:{query:b,field:"id"}}};d.query.filterCondition=d.query.filterCondition?{$and:[d.query.filterCondition,E]}:E,Q(t,d.query)}if(!s.includeAllFacets){const d={id:{$in:[...h.keys()]}};u.filterCondition=u.filterCondition?{$and:[u.filterCondition,d]}:d}Q(t,u);const m=(await i.executeQuery(c.withQuery(e(u)).query)).map(d=>{const b=String(Ie(d.id??d.Id)),E=h.get(b),S={...d};for(const w of f)S[w.alias]=E?.[w.alias]??Ut(w);return S}).filter(d=>s.includeAllFacets||h.has(String(Ie(d.id??d.Id)))),y=new Y(m);l.length&&(y.facets=await et(i,e,c.withQuery(u).query,l)),o[s.facetName]=y}return o}function Wt(i){const e=new Map;for(const t of Object.values(i))for(const n of Object.values(t.relations||{})){if(!n.many)continue;const r=i[n.targetEntity],o=r?.columns[n.foreignKey]?.columnName,s=r?.columns.id?.columnName;if(!r||!o||!s)continue;const a=`idx_${r.table}_${o}_${s}`;let c=2166136261;for(let f=0;f>>0).toString(36),l=a.length<=30?a:`${a.slice(0,Math.max(1,29-u.length))}_${u}`;e.set(l,{name:l,table:r.table,foreignColumn:o,idColumn:s})}return[...e.values()]}async function Gt(i,e,t,n){const r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ID space floor ${n} for ${t}`);for(let o=1;o<=100;o+=1){const s=await i.query(`SELECT current_level AS id FROM teaql_id_space WHERE type_name = ${e(1)}`,[t]);if(!s.rowCount){try{if((await i.query(`INSERT INTO teaql_id_space(type_name, current_level) VALUES (${e(1)}, ${e(2)})`,[t,r])).rowCount===1)return}catch(u){if(!(await i.query(`SELECT current_level FROM teaql_id_space WHERE type_name = ${e(1)}`,[t])).rowCount)throw u}continue}const a=Number(s.rows[0].id);if(a>=r)return;const c=await i.query(`UPDATE teaql_id_space SET current_level = ${e(1)} WHERE type_name = ${e(2)} AND current_level = ${e(3)}`,[r,t,a]);if(c.rowCount===1)return;if(c.rowCount!==0)throw new Error(`ID space floor update for ${t} changed ${c.rowCount} rows on attempt ${o}`)}throw new Error(`Unable to synchronize ID space floor for ${t} after 100 optimistic-lock attempts`)}function Ht(i,e){return i===e?!0:(i instanceof Date&&(i=i.getTime()),e instanceof Date&&(e=e.getTime()),i!=null&&e!==null&&e!==void 0&&String(i)===String(e))}function ee(i){return Object.freeze(i.map((e,t)=>Object.freeze({...e,level:t})))}function ge(i,e,t,n,r,o){const s=i.traceFor({entity:String(e.entity),id:r}),a=ye([...s,{kind:"entity",name:String(e.entity),entityId:r,detail:""}],t,n);return{auditReason:i.comment,tracePath:ee(a.tracePath),mutationLineage:s,targetID:r,inheritedBindings:R(o,i.graphSession?.logBindings)}}class Yt{constructor(e=t=>console.debug(t)){this.writer=e}write(e){e=Ke(e),this.writer(`[TeaQL SQL][${e.operation}][${e.elapsedMicros}us] ${e.resultSummary}${e.executionOutcome?` outcome=${e.executionOutcome}`:""} -comment=${e.comment??""} purpose=${e.purpose??""} auditReason=${e.auditReason??""} tracePath=${pe(e.tracePath)} traceChain=${pe(e.traceChain??[])} mutationLineage=${pe(e.mutationLineage??[])} -`+(e.omissionReason?`SQL omitted: ${e.omissionReason} -`:"")+`Debug SQL: ${e.debugSQL}`)}}function pe(i){return JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString():t)}class ui{constructor(){this.mode="all",this.entries=[]}record(e){const t=e.operation==="select";this.mode==="disabled"||this.mode==="select"&&!t||this.mode==="mutation"&&t||this.entries.push(Object.freeze({...e,...e.traceChain?{traceChain:C(e.traceChain)}:{},parameters:Object.freeze([...e.parameters])}))}setMode(e){return this.mode=e,this.entries=[],this}enableAll(){return this.setMode("all")}enableSelect(){return this.setMode("select")}enableMutation(){return this.setMode("mutation")}disable(){return this.setMode("disabled")}snapshot(){return[...this.entries]}}class Xt{constructor(e,t){this.driver=e,this.bootstrapTail=Promise.resolve(),this.sqlTrace=[],this.internalQueryToken=Symbol("teaql-internal-query"),this.bindLogPolicies=new WeakMap,this.bindOperandSources=new WeakMap,this.derivedQueryBindings=new WeakMap,this.derivedRelationAssembly=new WeakMap,this.auditEvents=[],this.diagnosticSQLLogSink=new Yt,this.queryLoggingEnabled=!0,this.mutationLoggingEnabled=!0,this.customTelemetry=!1,this.checkers={},this.userContext=new Dt,this.bootstrap={},this.graphAuditActions=[],this.graphCommitActions=[],this.graphRollbackActions=[],this.graphSaveTail=Promise.resolve(),this.schemas={...t}}fieldLogPolicy(e,t){const n=e.columns[t],r=n?.modelName??n?.columnName??t;return W(r)||W(t)?"credential":e.auditMaskFields?e.auditMaskFields?.includes(r)||e.auditMaskFields?.includes(t)?"masked":n?.logPolicy??"unknown":"unknown"}bindValue(e,t,n,r){const o=this.bindLogPolicies.get(e)??e.map(()=>"unknown");e.push(t),o.push(n),this.bindLogPolicies.set(e,o),r!==void 0&&this.bindOperandSources.set(e,R({parameterizedSQL:"",parameters:[r],parameterLogPolicies:[n],sqlOrigin:"generated"},this.bindOperandSources.get(e)))}queryLogBindings(e,t){return R({parameterizedSQL:e,parameters:t,parameterLogPolicies:this.bindLogPolicies.get(t),sqlOrigin:"generated"},this.bindOperandSources.get(t))}install(e){return Object.assign(this.schemas,e.schemas),Object.assign(this.checkers,e.checkers),this.bootstrap=Xe(this.bootstrap,e.bootstrap),this}setUserContext(e){return this.userContext=e,this}schema(e){const t=this.schemas[e];if(!t)throw new Error(`Unknown TeaQL entity: ${e}`);return t}toRuntimeMutationRecord(e,t){const n={};for(const[r,o]of Object.entries(t)){const s=e.columns[r]?r:Object.keys(e.columns).find(a=>e.columns[a].modelName===r||e.columns[a].columnName===r);s&&(n[s]=o)}return n}encode(e,t){const n=e?.id??e;if(n!==void 0)return this.driver.encode(n,t)}decodeRow(e,t,n=[]){const r=this.schema(e),o={...t};for(const[s,a]of Object.entries(r.columns)){const c=o[s];c!=null&&(a.decode==="number"&&(o[s]=Number(c)),a.decode==="string"&&(o[s]=String(c)),a.decode==="date"&&c instanceof Date&&(o[s]=c.toISOString()),a.logicalType==="boolean"&&(o[s]=!!c))}for(const s of n)o[s]!==null&&o[s]!==void 0&&(o[s]=Number(o[s]));return o}get auditTrace(){return[...this.auditEvents]}setAuditSink(e){return this.auditSink=e,this}setRuntimeTelemetrySink(e){return this.telemetrySink=e,this}setDiagnosticSQLLogSink(e){return this.diagnosticSQLLogSink=e,this}setQueryLoggingEnabled(e){return this.queryLoggingEnabled=e,this}setMutationLoggingEnabled(e){return this.mutationLoggingEnabled=e,this}setRuntimeTelemetry(e){return this.customTelemetry=!0,this.runtimeTelemetry=e,this}attachStandardTelemetryStartup(e){this.telemetryStartup=e.then(async t=>{if(t){if(this.customTelemetry){await t.release();return}this.standardTelemetryHandle=t,this.runtimeTelemetry=t.telemetry}}).catch(()=>{fe("TeaQL telemetry: initialization failed; business continues without export.",!0)})}async flushTelemetry(){await this.telemetryStartup;try{await this.standardTelemetryHandle?.flush()}catch{fe("TeaQL telemetry: export flush failed; business outcome unchanged.",!0)}}async withQueryRequest(e,t){return new L(e),await this.telemetryStartup,D(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.request`,attributes:{"teaql.entity.type":String(e.entity)}},t)}recordSQL(e,t,n,r,o,s,a={},c="success",u,l){const g=e==="select"?this.queryLoggingEnabled:this.mutationLoggingEnabled,{targetID:h,inheritedBindings:p,...m}=a,y=Object.freeze({operation:e,...m,executionOutcome:c,traceChain:C(a.traceChain??[]),tracePath:ee(a.tracePath??[]),...a.traceChain?{traceChain:C(a.traceChain)}:{},...a.mutationLineage?{mutationLineage:C(a.mutationLineage)}:{},parameterizedSQL:t,parameters:Object.freeze([...n]),debugSQL:"",databaseKind:this.driver.databaseKind,sqlOrigin:"generated",parameterLogPolicies:Object.freeze([...this.bindLogPolicies.get(n)??n.map(()=>"unknown")]),elapsedMicros:Math.max(0,(Date.now()-r)*1e3),resultCount:o,affectedRows:s,resultSummary:o!==void 0?`${o} rows returned`:s!==void 0?`${s} rows affected`:`statement ${c}; row count unknown`}),d=p&&u?R(u,p):p??u,b=this.bindOperandSources.get(n),E=b?R(b,d):d;if(ke(y,E,h===void 0?[]:[h]),this.runtimeTelemetry?.recordDiagnostic)try{this.runtimeTelemetry.recordsSQLDiagnostics?.()!==!1&&this.runtimeTelemetry.recordDiagnostic(Bt(It(y),l))}catch{fe("TeaQL telemetry: SQL diagnostic rejected; business outcome unchanged.",!0)}if(!this.telemetrySink&&!(g&&this.diagnosticSQLLogSink))return y;try{const S=Ke(y);try{this.telemetrySink?.record(S)}catch{}if(g)try{this.diagnosticSQLLogSink?.write(S)}catch{}}catch{}return y}queryLogIntent(e){const t=new L(e),n=ye(t.traceSource,this.driver.databaseKind,"select");return{comment:t.intent.comment,purpose:t.purpose,traceChain:t.traceChain,tracePath:ee(n.tracePath)}}async executeLoggedSQL(e,t,n,r,o,s,a){await this.telemetryStartup;const c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.${e}`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":e==="select"?"query":e}}),u=c.correlation?.(),l=Date.now();let f;try{f=await(c.run?c.run(o):o())}catch(h){try{const p=this.recordSQL(e,t,n,l,void 0,void 0,r,"failure",s,u);a?.push(p)}finally{throw c.failure(h),h}}const g=this.recordSQL(e,t,n,l,e==="select"?f.rowCount:void 0,e==="select"?void 0:f.rowCount,r,"success",s,u);return a?.push(g),c.success({attributes:{"teaql.result.cardinality":f.rowCount}}),f}async[Qe](e){await this.telemetryStartup,this.schemaReady||(this.schemaReady=this.driver.ensureSchema(this.schemas)),await this.schemaReady;const t=this.bootstrapTail;let n;this.bootstrapTail=new Promise(s=>{n=s}),await t,this.userContext=e;const r=e.getResource("bootstrapActor"),o=e.getResource("bootstrapCategory");e.insertResource("bootstrapActor","teaql-generated-bootstrap"),e.insertResource("bootstrapCategory","runtime-bootstrap");try{this.bootstrap.ensure?await this.bootstrap.ensure(e):await this.ensureBootstrapData()}finally{r===void 0?e.removeResource("bootstrapActor"):e.insertResource("bootstrapActor",r),o===void 0?e.removeResource("bootstrapCategory"):e.insertResource("bootstrapCategory",o),n()}}invalidateSchemaState(){this.schemaReady=void 0}async ensureBootstrapData(){const e=[...this.bootstrap.defaultDomainRoot?[this.bootstrap.defaultDomainRoot]:[],...this.bootstrap.constants??[]];e.length&&await this.executeGraphSave(new z("reconcile model bootstrap data"),async t=>{const n=this.graphMutationSession,r=[];for(const o of e){const s=await this.planBootstrapMutation(n,o);s&&r.push({record:o,request:t.request(s)})}for(const{request:o}of r)this.preflightMutation(o);for(const{request:o}of r)await this.executeMutation(o);for(const o of e)await this.driver.ensureIdFloor(n,o.entity,o.id)})}async planBootstrapMutation(e,t){const n=this.schema(t.entity),r=Object.entries(t.values??{}).map(([g,h])=>{const p=n.columns[g];if(!p)throw new Error(`Unknown bootstrap field ${t.entity}.${g}`);return{column:p.columnName,value:this.driver.encode(h,p)}}),o=new Ft(t.entity).filter({id:{$eq:t.id}}).limit(1).comment("inspect model bootstrap record").purpose("ensure model-defined root and constants");o.prepareForList();const s=new L(o),a=`SELECT * FROM ${this.driver.identifier(n.table)} WHERE ${this.driver.identifier(n.columns.id?.columnName??"id")} = ${this.driver.placeholder(1)}`,c=[t.id];this.bindLogPolicies.set(c,[this.fieldLogPolicy(n,"id")]);const u=await this.executeLoggedSQL("select",a,c,this.queryLogIntent(s.query),()=>e.query(a,c));if(!u.rowCount)return{entity:t.entity,action:"Create",id:t.id,version:0,payload:{...t.values}};const l=u.rows[0];if(r.filter(g=>!Ht(l[g.column],g.value)).length)return{entity:t.entity,action:"Update",id:t.id,version:Number(l[n.columns.version?.columnName??"version"]),payload:{...this.decodeRowForSchema(n,l),...t.values}}}async executeGraphSave(e,t){const n=new Ot(e);await this.telemetryStartup;const r=async()=>{const o=this.graphSaveTail;let s;this.graphSaveTail=new Promise(l=>{s=l}),await o;let a=!1,c=!1,u=!1;try{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],this.userContext.insertResource("fixTime",new Date),this.userContext.beginFixEvidence(),a=!0,this.userContext.beginMutationPolicyGraph(),c=!0;const l=await this.driver.transaction(async h=>{this.graphMutationSession=h,this.activeGraph=n;try{const p=await t(n);return this.userContext.ensureMutationPolicyGraphComplete(),p}finally{this.graphMutationSession=void 0,this.activeGraph=void 0}});u=!0;let f,g=!1;for(const h of[...this.graphCommitActions,...this.graphAuditActions])try{await h()}catch(p){g||(f=p),g=!0}if(g)throw new qe(f);return l}catch(l){if(!u)for(const f of[...this.graphRollbackActions].reverse())try{f()}catch{}throw l}finally{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],c&&this.userContext.endMutationPolicyGraph(),this.userContext.removeResource("fixTime"),a&&this.userContext.finishFixEvidence(),s()}};return D(this.runtimeTelemetry,{family:"mutation",name:"graph.save",attributes:{"teaql.entity.type":"graph","teaql.mutation.kind":"graph"}},r)}afterGraphCommit(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphCommitActions.push(e)}afterGraphRollback(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphRollbackActions.push(e)}requireGraphOwnership(e){if(e.graphSession!==this.activeGraph||this.graphMutationSession!==void 0&&e.graphSession===void 0)throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability")}async withMutationSession(e,t){return this.requireGraphOwnership(e),e.graphSession?t(this.graphMutationSession):this.driver.transaction(t)}preflightMutation(e){const t=e instanceof x?e:new x(e);if(this.requireGraphOwnership(t),e=this.checkAndFixMutation(t),t.graphSession){const n=this.schema(e.entity);t.graphSession.captureLogBindings(this.mutationLogBindings(t,e,n))}return this.userContext.recordMutationPolicyPreflight(e),e}mutationLogBindings(e,t,n){const r=o=>{const s=this.toRuntimeMutationRecord(n,o),a=Object.keys(s);return{parameterizedSQL:"",sqlOrigin:"generated",parameters:a.map(c=>s[c]),parameterLogPolicies:a.map(c=>this.fieldLogPolicy(n,c))}};return R(r(t.payload||{}),r(e.loadedValues()))}checkAndFixMutation(e){const t=e instanceof x?e:new x(e);this.requireGraphOwnership(t),e=t.mutation,e={...e,payload:{...e?.payload??{}}},Object.defineProperty(e,"comment",{value:t.comment,enumerable:!0});const n=this.checkers[String(e.entity)];if(!n)return e;const r=[],o=this.userContext.getResource("fixTime")===void 0;o&&this.userContext.insertResource("fixTime",new Date).beginFixEvidence();try{if(n.checkAndFix(this.userContext,e,r),e.ledgerKey&&e.ledgerRoot)for(const[s,a]of Object.entries(e.payload||{}))e.ledgerRoot.set(e.ledgerKey,s,a);if(this.userContext.translateCheckResults(r),r.length)throw new ot(r);return e}finally{o&&this.userContext.removeResource("fixTime").finishFixEvidence()}}async executeMutation(e){await this.telemetryStartup;const t=e instanceof x?e:new x(e);this.requireGraphOwnership(t),e=t.mutation;const n=N(this.runtimeTelemetry,{family:"mutation",name:`${String(e?.entity||"unknown")}.${String(e?.action||"unknown").toLowerCase()}`,attributes:{"teaql.entity.type":String(e?.entity||"unknown"),"teaql.mutation.kind":String(e?.action||"unknown").toLowerCase()}}),r=async()=>{try{e=this.checkAndFixMutation(t);const o=this.userContext.enterMutationPolicy(e),s=this.schema(e.entity),a=this.toRuntimeMutationRecord(s,e.payload||{}),c=this.mutationLogBindings(t,e,s),u=this.driver.identifier(s.table),l=[],f=await D(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.mutation`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":String(e.action).toLowerCase()}},()=>this.withMutationSession(t,async y=>{if(e.action==="Create"){const d=e.id?String(e.id):await this.driver.nextId(y,e.entity);e.id&&await this.driver.ensureIdFloor(y,e.entity,d);const b=Number(e.version||0)+1,E={...a,id:d,version:b},S=Object.keys(s.columns).filter($=>E[$]!==void 0),w=S.map($=>this.driver.identifier(s.columns[$].columnName)).join(", "),v=S.map(($,A)=>this.driver.placeholder(A+1)).join(", "),I=S.map($=>this.encode(E[$],s.columns[$]));this.bindLogPolicies.set(I,S.map($=>this.fieldLogPolicy(s,$)));const T=`INSERT INTO ${u} (${w}) VALUES (${v})`,O=ge(t,e,this.driver.databaseKind,"insert",d,c);return await this.executeLoggedSQL("insert",T,I,O,()=>y.query(T,I),void 0,l),{success:!0,id:d,version:b,persistedRecord:await this.readPersistedRecord(y,s,d,O,T,I,l)}}if(e.action==="Update"){const d=Object.keys(s.columns).filter($=>$!=="id"&&$!=="version"&&a[$]!==void 0),b=d.map($=>this.encode(a[$],s.columns[$]));this.bindLogPolicies.set(b,d.map($=>this.fieldLogPolicy(s,$)));const E=d.map(($,A)=>`${this.driver.identifier(s.columns[$].columnName)} = `+this.driver.placeholder(A+1)),S=this.driver.identifier("version");E.push(`${S} = ${S} + 1`),this.bindValue(b,String(e.id),this.fieldLogPolicy(s,"id"));const w=[`${this.driver.identifier("id")} = ${this.driver.placeholder(b.length)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),w.push(`${S} = ${this.driver.placeholder(b.length)}`));const v=`UPDATE ${u} SET ${E.join(", ")} WHERE ${w.join(" AND ")}`,I=ge(t,e,this.driver.databaseKind,"update",String(e.id),c);if((await this.executeLoggedSQL("update",v,b,I,()=>y.query(v,b),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const O=await this.readPersistedRecord(y,s,String(e.id),I,v,b,l);return{success:!0,id:String(e.id),version:Number(O.version),persistedRecord:O}}if(e.action==="Delete"){const d=this.driver.identifier("version"),b=[String(e.id)];this.bindLogPolicies.set(b,[this.fieldLogPolicy(s,"id")]);const E=[`${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),E.push(`${this.driver.identifier("version")} = `+this.driver.placeholder(b.length)));const S=`UPDATE ${u} SET ${d} = -(${d} + 1) WHERE ${E.join(" AND ")}`,w=ge(t,e,this.driver.databaseKind,"delete",String(e.id),c);if((await this.executeLoggedSQL("delete",S,b,w,()=>y.query(S,b),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const I=await this.readPersistedRecord(y,s,String(e.id),w,S,b,l);return{success:!0,id:String(e.id),version:Number(I.version),deleted:!0,persistedRecord:I}}throw new Error(`Unsupported mutation action: ${e.action}`)})),g=t.auditProjection({entity:String(e.entity),id:f.id},e.payload,c),h=Object.freeze({entity:e.entity,action:e.action,id:String(f.id),...g,recordedAt:new Date().toISOString(),actor:this.userContext.getResource("bootstrapActor"),category:this.userContext.getResource("bootstrapCategory"),changedFields:Object.freeze(Object.keys(e.payload||{}).sort()),version:f.version,mutationGovernance:o}),p=async()=>{this.auditEvents.push(h),this.auditSink&&await D(this.runtimeTelemetry,{family:"audit",name:`${e.entity}.audit`,attributes:{"teaql.entity.type":String(e.entity),"teaql.mutation.kind":String(e.action).toLowerCase(),"teaql.audit.changed_field_count":Object.keys(e.payload||{}).length}},async()=>this.auditSink(h))};if(t.graphSession)this.graphAuditActions.push(p);else try{await p()}catch(y){throw new qe(y)}n.success();const m=Object.freeze({...l[0],statements:Object.freeze([...l])});return ke(m,R(c,t.graphSession?.logBindings),[f.id]),{...f,metadata:m}}catch(o){throw n.failure(o),o}};return n.run?n.run(r):r()}async readPersistedRecord(e,t,n,r,o,s,a){const u=`SELECT ${Object.entries(t.columns).map(([S,w])=>`${this.driver.identifier(w.columnName)} AS ${this.driver.identifier(S)}`).join(", ")} FROM ${this.driver.identifier(t.table)} WHERE ${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`,l=[n];this.bindLogPolicies.set(l,[this.fieldLogPolicy(t,"id")]);const f=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.readback`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}}),g=Date.now();let h;const p={parameterizedSQL:o,parameters:s,parameterLogPolicies:this.bindLogPolicies.get(s),sqlOrigin:"generated"},m=r.tracePath?.find(S=>S.kind==="operation")?.name??"unknown",y=ye([...ze(m,r.auditReason,"verify persisted mutation result"),...(r.tracePath??[]).filter(S=>S.kind==="relation")],this.driver.databaseKind,"select"),d={...r,tracePath:ee(y.tracePath),comment:r.auditReason,purpose:"verify persisted mutation result"},b=S=>a.push(this.recordSQL("select",u,l,g,h?.rowCount,void 0,d,S,p,f.correlation?.()));let E;try{if(h=await(f.run?f.run(()=>e.query(u,l)):e.query(u,l)),f.success({attributes:{"teaql.result.cardinality":h.rowCount}}),h.rowCount!==1)throw new Error(`Persisted ${t.table}(${n}) could not be read back`);E=this.decodeRowForSchema(t,h.rows[0])}catch(S){h||f.failure(S);const w=h?"success":S instanceof Error&&(S.name==="AbortError"||S.name==="TimeoutError")?"cancelled":"failure";try{b(w)}finally{throw S}}return b("success"),E}decodeRowForSchema(e,t){const n={...t};for(const[r,o]of Object.entries(e.columns)){const s=n[r];s!=null&&(o.decode==="number"&&(n[r]=Number(s)),o.decode==="string"&&(n[r]=String(s)),o.decode==="date"&&s instanceof Date&&(n[r]=s.toISOString()),o.logicalType==="boolean"&&(n[r]=!!s))}return n}compileExpression(e,t,n){if(Array.isArray(e?.$and))return`(${e.$and.map(s=>this.compileExpression(s,t,n)).join(" AND ")})`;const r=Object.entries(e||{}).map(([o,s])=>{const a=t.columns[o];if(!a)throw new Error(`Unknown field ${o} for SQL query`);const c=this.driver.identifier(a.columnName),u=this.fieldLogPolicy(t,o);if(s?.$eq!==void 0){const l=s.$eq?.id??s.$eq;return l===null?`${c} IS NULL`:(this.bindValue(n,this.encode(l,a),u),`${c} = ${this.driver.placeholder(n.length)}`)}if(s?.$ne!==void 0){const l=s.$ne?.id??s.$ne;return l===null?`${c} IS NOT NULL`:(this.bindValue(n,this.encode(l,a),u),`${c} <> ${this.driver.placeholder(n.length)}`)}if(s?.$soundLike!==void 0)return this.bindValue(n,String(s.$soundLike),u),`SOUNDEX(${c}) = SOUNDEX(${this.driver.placeholder(n.length)})`;if(s?.$contains!==void 0)return this.bindValue(n,String(s.$contains),u),this.driver.contains(c,this.driver.placeholder(n.length));if(s?.$notContains!==void 0)return this.bindValue(n,String(s.$notContains),u),`NOT (${this.driver.contains(c,this.driver.placeholder(n.length))})`;for(const[l,f,g,h]of[["$startsWith","","%",!1],["$notStartsWith","","%",!0],["$endsWith","%","",!1],["$notEndsWith","%","",!0]])if(s?.[l]!==void 0){const p=String(s[l]);this.bindValue(n,`${f}${p}${g}`,u,p);const m=`${c} LIKE ${this.driver.placeholder(n.length)}`;return h?`NOT (${m})`:m}if(Array.isArray(s?.$in)){if(!s.$in.length)return"FALSE";const l=s.$in.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),u),this.driver.placeholder(n.length)));return`${c} IN (${l.join(", ")})`}if(Array.isArray(s?.$notIn)){if(!s.$notIn.length)return"TRUE";const l=s.$notIn.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),u),this.driver.placeholder(n.length)));return`${c} NOT IN (${l.join(", ")})`}for(const[l,f]of[["$inSubquery",!1],["$notInSubquery",!0]]){const g=s?.[l];if(g!==void 0){const h=g.query,p=this.schema(h?.entity),m=String(g.field),y=p.columns[m];if(!y)throw new Error(`Unknown subquery projection ${m} for ${h?.entity}`);const d=this.filters(h).map(S=>this.compileExpression(S,p,n));p.columns.version&&d.push(`${this.driver.identifier(p.columns.version.columnName)} > 0`),f&&d.push(`${this.driver.identifier(y.columnName)} IS NOT NULL`);const b=d.length?` WHERE ${d.join(" AND ")}`:"",E=`SELECT ${this.driver.identifier(y.columnName)} FROM ${this.driver.identifier(p.table)}${b}`;return`${c} ${f?"NOT IN":"IN"} (${E})`}}if(Array.isArray(s?.$between)&&s.$between.length===2){this.bindValue(n,this.encode(s.$between[0],a),u);const l=this.driver.placeholder(n.length);this.bindValue(n,this.encode(s.$between[1],a),u);const f=this.driver.placeholder(n.length);return`${c} BETWEEN ${l} AND ${f}`}if(s?.$isNull===!0)return`${c} IS NULL`;if(s?.$isNull===!1)return`${c} IS NOT NULL`;if(s?.$gte!==void 0)return this.bindValue(n,this.encode(s.$gte,a),u),`${c} >= ${this.driver.placeholder(n.length)}`;if(s?.$lte!==void 0)return this.bindValue(n,this.encode(s.$lte,a),u),`${c} <= ${this.driver.placeholder(n.length)}`;if(s?.$gt!==void 0)return this.bindValue(n,this.encode(s.$gt,a),u),`${c} > ${this.driver.placeholder(n.length)}`;if(s?.$lt!==void 0)return this.bindValue(n,this.encode(s.$lt,a),u),`${c} < ${this.driver.placeholder(n.length)}`;throw new Error(`Unsupported query predicate for ${o}: ${JSON.stringify(s)}`)});return r.length?`(${r.join(" AND ")})`:"TRUE"}filters(e){return Array.isArray(e._filters)&&e._filters.length?e._filters:e.filterCondition?[e.filterCondition]:[]}groupBy(e){return e._groupBy||e.groupByItems||[]}aggregates(e){return Array.isArray(e._aggregates)?e._aggregates:(e.aggregateItems||[]).map(t=>({func:t.function,field:t.field,retName:t.alias}))}orders(e){return Array.isArray(e._orderBy)?e._orderBy.map(t=>({field:t.f,direction:t.d})):(e.orderItems||[]).map(t=>({field:t.field,direction:t.direction}))}async compileQuery(e,t=!0,n=[]){new se(e?.commentText??e?._comment,e?.purposeText??e?._purpose);const r=this.schema(e.entity),o=[],s=this.groupBy(e),a=s.map(w=>{if(!r.columns[w])throw new Error(`Unknown group field: ${w}`);return this.driver.identifier(r.columns[w].columnName)}),c=s.map(w=>`${this.driver.identifier(r.columns[w].columnName)} AS `+this.driver.identifier(w)),u=[],l=Array.isArray(e.selectItems)&&e.selectItems.length?[...new Set(["id","version",...e.selectItems])]:Object.keys(r.columns);if(!s.length&&!this.aggregates(e).length){for(const v of n)l.includes(v)||l.push(v);const w=[...(e.relations??[]).map(v=>v.name),...(e.relationAggregates??[]).map(v=>v.relationName)];for(const v of w){const I=r.relations?.[v];if(!I)throw new Error(`Missing relation ${e.entity}.${v}`);l.includes(I.localKey)||l.push(I.localKey)}}for(const w of l)if(!r.columns[w])throw new Error(`Unknown selected field: ${w}`);let f=l.map(w=>{const v=r.columns[w];return`${this.driver.identifier(v.columnName)} AS ${this.driver.identifier(w)}`}).join(", ");const g=this.aggregates(e);if(g.length){const w=g.map(v=>{if(!r.columns[v.field])throw new Error(`Unknown aggregate field: ${v.field}`);return u.push(v.retName),`${this.driver.aggregateFunction(v.func)}(${this.driver.identifier(r.columns[v.field].columnName)}) AS `+this.driver.identifier(v.retName)});f=[...c,...w].join(", ")}const h=e.__teaqlPartitionBy,p=this.orders(e),m=p.map(w=>{if(!r.columns[w.field])throw new Error(`Unknown order field: ${w.field}`);const v=String(w.direction).toLowerCase()==="desc"?"DESC":"ASC";return`${this.driver.identifier(r.columns[w.field].columnName)} ${v}`});if(h){const w=r.columns[h];if(!w)throw new Error(`Unknown partition field: ${h}`);const v=m.length?` ORDER BY ${m.join(", ")}`:"";f+=`, ROW_NUMBER() OVER (PARTITION BY ${this.driver.identifier(w.columnName)}${v}) AS `+this.driver.identifier("__teaql_partition_rank")}let y=`SELECT ${f} FROM ${this.driver.identifier(r.table)}`;const b=this.filters(e).map(w=>this.compileExpression(w,r,o));r.columns.version&&b.push(`${this.driver.identifier(r.columns.version.columnName)} > 0`),b.length&&(y+=` WHERE ${b.join(" AND ")}`),a.length&&(y+=` GROUP BY ${a.join(", ")}`);const E=e._limit!==void 0?Number(e._limit):Number(e.limitValue||0),S=e._offset!==void 0?Number(e._offset):Number(e.offsetValue||0);if(h){const w=this.driver.identifier("__teaql_partition_rank"),v=[];this.bindValue(o,S,"plain"),v.push(`${w} > ${this.driver.placeholder(o.length)}`),E>0&&(this.bindValue(o,S+E,"plain"),v.push(`${w} <= ${this.driver.placeholder(o.length)}`)),y=`SELECT * FROM (${y}) AS ${this.driver.identifier("__teaql_partitioned")} WHERE ${v.join(" AND ")} ORDER BY ${w}`}else p.length&&(y+=` ORDER BY ${m.join(", ")}`);return!h&&E>0&&(this.bindValue(o,E,"plain"),y+=` LIMIT ${this.driver.placeholder(o.length)}`),!h&&S>0&&(this.bindValue(o,S,"plain"),y+=` OFFSET ${this.driver.placeholder(o.length)}`),t&&this.sqlTrace.push(y),{sql:y,values:o,aggregateNames:u}}async executeQuery(e){const t=e instanceof L?e:new L(e);return!(e instanceof L)&&e?.[this.internalQueryToken]!==!0&&typeof e?.prepareForList=="function"&&e.prepareForList(),this.executeQueryWithIntent(t.query,this.derivedQueryBindings.get(e),this.derivedRelationAssembly.get(e))}async executeDerivedQuery(e,t,n,r){const o=new L(e,n).query;t&&this.derivedQueryBindings.set(o,t),r&&this.derivedRelationAssembly.set(o,r);try{return await this.executeQuery(o)}finally{this.derivedQueryBindings.delete(o),this.derivedRelationAssembly.delete(o)}}descendantBindings(e,t,n,r){if(!(!e.relations?.length&&!e.relationAggregates?.length))return R(this.queryLogBindings(t,n),r)}async queryTreeBindings(e,t,n,r){let o=R(this.queryLogBindings(t,n),r);const s=new L(e).intent,a=[e],c=new Set;for(;a.length;){const u=a.pop();if(!u||c.has(u))continue;if(c.add(u),u!==e){const f=await this.compileQuery(new L(u,s).query,!1);o=R(this.queryLogBindings(f.sql,f.values),o)}const l=$t(u);l&&a.push(l);for(const f of[...u.relations??[],...u.relationAggregates??[]])f.query&&a.push(f.query);for(const f of u.facets??[]){if(!f.query)continue;const g=f.query.clone();g.aggregateItems=[],g.groupByItems=[],a.push(g)}}return o}async executeQueryWithIntent(e,t,n){await this.telemetryStartup;const r=N(this.runtimeTelemetry,{family:"query",name:`${String(e?.entity||"unknown")}.list`,attributes:{"teaql.entity.type":String(e?.entity||"unknown")}}),o=async()=>{try{const s=e?.[this.internalQueryToken]===!0;if(!s){if(typeof e?.prepareForList!="function")throw new Error("TeaQL list execution requires the formal runtime SelectQuery");e.prepareForList()}const a=s?{query:e,execution:void 0}:await this.prepareIdSetPage(e,t),c=s?a:await this.prepareContinuousPage(a.query);e=new L(e).withQuery(c.query).query;const{sql:u,values:l,aggregateNames:f}=await this.compileQuery(e,!0,n?[n.field]:[]);t=await this.queryTreeBindings(e,u,l,t);const h=(await this.executeLoggedSQL("select",u,l,this.queryLogIntent(e),()=>this.driver.query(u,l),t)).rows.map(m=>this.decodeRow(e.entity,m,f));if(a.execution?.pageIds){const m=new Map(a.execution.pageIds.map((y,d)=>[String(y),d]));h.sort((y,d)=>(m.get(String(y.id))??Number.MAX_SAFE_INTEGER)-(m.get(String(d.id))??Number.MAX_SAFE_INTEGER))}const p=this.descendantBindings(e,u,l,t);if(n)for(const m of h)n.keys.set(m,m[n.field]);if(await this.enhanceQueryRows(h,e,p),n&&Array.isArray(e.selectItems)&&e.selectItems.length&&!["id","version",...e.selectItems,...this.groupBy(e)].includes(n.field)){const m=this.schema(e.entity);if(![...(e.relations??[]).map(d=>d.name),...(e.relationAggregates??[]).map(d=>d.relationName)].some(d=>m.relations?.[d]?.localKey===n.field))for(const d of h)delete d[n.field]}return s||await this.registerContinuousPage(e,c.execution,h),r.success({attributes:{"teaql.result.cardinality":h.length}}),h}catch(s){throw r.failure(s),s}};return r.run?r.run(o):o()}async prepareIdSetPage(e,t){const n=e.localIdSetPaginationOptions?.(),r=e.localIdSetPaginationRuntime?.();if(!n||!r)return r?.observe("ID_SET_DISABLED"),{query:e};const o=this.queryLimit(e);if(!o||e.localContinuousPageOptions?.()||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return r.observe("ID_SET_FALLBACK_UNSUPPORTED_SHAPE"),{query:e};if((e.orderItems||[]).some(m=>m.expr!=null))return r.observe("ID_SET_FALLBACK_NON_DETERMINISTIC_ORDER"),{query:e};this.orders(e).some(m=>m.field==="id")||(e=e.clone().order(P.asc("id")));const s=e.clone();s.offsetValue=0,s.limitValue=0,s.selectItems=[],s.relations=[],s.commentText=void 0,s.purposeText=void 0,s.clearIdSetPaginationRuntime(),s.clearContinuousPageRuntime();const a=`${n.namespace}|${r.scope}|${JSON.stringify(s)}`;let c=2166136261;for(let m=0;m>>0).toString(16)}`;let l,f=!1;try{l=r.get(u)}catch{return r.observe("ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l)f=!0,r.observe("ID_SET_HIT",l.ids.length);else{let m;try{m=await r.build(u,async()=>{const y=r.get(u);if(y)return y;const d=e.clone();d.selectItems=["id"],d.relations=[],d.relationAggregates=[],d.facets=[],d.offsetValue=0,d.limitValue=n.maxIds+1,d.clearIdSetPaginationRuntime(),d.clearContinuousPageRuntime(),d[this.internalQueryToken]=!0;const b=new L(e).deriveHelper(d,`collect ${e.entity} IDs for pagination`),E=await this.compileQuery(e,!1),S=await this.queryTreeBindings(e,E.sql,E.values,t),w=await this.executeDerivedQuery(b.query,S,b.intent);if(w.length>n.maxIds)return;let v;try{v=BigUint64Array.from(w.map(T=>BigInt(T.id)))}catch{throw new Error("ID_SET_UNSUPPORTED_ID")}const I={ids:v,expiresAt:Date.now()+n.ttlSeconds*1e3};return r.put(u,I),I})}catch(y){return r.observe(y instanceof Error&&y.message==="ID_SET_UNSUPPORTED_ID"?"ID_SET_FALLBACK_UNSUPPORTED_SHAPE":"ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l=m.value,!l)return r.observe("ID_SET_FALLBACK_LIMIT_EXCEEDED",n.maxIds+1),{query:e};f=!m.built,r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length)}const g=Number(e.offsetValue||e._offset||0),h=Array.from(l.ids.slice(g,g+o)),p=e.clone();return p.offsetValue=0,p.limitValue=Math.max(h.length,1),p.filterCondition=p.filterCondition?{$and:[p.filterCondition,{id:{$in:h}}]}:{id:{$in:h}},p.clearIdSetPaginationRuntime(),r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length),{query:p,execution:{pageIds:h,totalCount:l.ids.length}}}async executeFacetMembership(e,t,n=[]){const r=await this.executeFacetAggregates(e,t,[{function:"Count",field:"id",alias:"__teaql_facet_count"}]);return new Map([...r].map(([o,s])=>[o,Number(s.__teaql_facet_count??0)]))}async executeFacetAggregates(e,t,n){const r=new L(e);e=r.query;const o=r.withQuery(e.clone()).query;Q(e,o),o.facets=[],o.relations=[],o.relationAggregates=[],o.orderItems=[],o.offsetValue=0,o.limitValue=0,o.selectItems=[],o.groupByItems=[t],o.aggregateItems=n.map(a=>({...a})),o[this.internalQueryToken]=!0;const s=await this.executeQuery(o);return new Map(s.flatMap(a=>{const c=a[t];if(c==null)return[];const u={};for(const l of n)u[l.alias]=a[l.alias];return[[String(c),u]]}))}async executeCount(e,t,n){const r=e instanceof L?e:new L(e);if(e=r.query,typeof e?.forExactCount!="function")throw new Error("TeaQL exact count requires the formal runtime SelectQuery");const o=t??"__teaql_total",s=r.deriveOperation(e.forExactCount(o),n??{kind:"named-count",...t!==void 0?{alias:t}:{}}),c=(await this.executeQuery(s.query))[0]?.[o];if(typeof c!="number"||!Number.isFinite(c))throw new Error(`TeaQL provider did not return exact count alias ${o}`);return c}async prepareContinuousPage(e){const t=e.localContinuousPageOptions?.(),n=e.localContinuousPageRuntime?.();if(!t||!n)return n?.observe("DISABLED"),{query:e};const r=this.orders(e),o=this.queryLimit(e);if(!o||r.length!==1||r[0].field!=="id"||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return n.observe("OFFSET_FALLBACK:UNSUPPORTED_QUERY_SHAPE"),{query:e};const s=Object.assign(Object.create(Object.getPrototypeOf(e)),e);s.orderItems=[...e.orderItems||[]],s.relations=[...e.relations||[]],Object.defineProperty(s,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:t}),Object.defineProperty(s,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:n});const a=Number(e.offsetValue||e._offset||0),c={...JSON.parse(JSON.stringify(s)),offsetValue:0,_offset:0,commentText:void 0,purposeText:void 0},u=`${t.namespace}|${n.owner}|${JSON.stringify(c)}`;let l=2166136261;for(let m=0;m>>0).toString(16)}`,g={queryKey:f,offset:a,limit:o,direction:String(r[0].direction).toLowerCase(),ttlSeconds:t.ttlSeconds,runtime:n,optimized:!1};if(a===0)return n.observe("OFFSET_FALLBACK:FIRST_PAGE"),{query:s,execution:g};let h;try{h=await D(this.runtimeTelemetry,{family:"cache",name:"continuous_page.get",attributes:{"teaql.cache.operation":"get"}},()=>n.get(f,a))}catch{return n.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE"),{query:s,execution:g}}if(!h)return n.observe("OFFSET_FALLBACK:CACHE_MISS"),{query:s,execution:g};const p={id:{[g.direction==="desc"?"$lt":"$gt"]:h.boundary}};return s.filterCondition=s.filterCondition?{$and:[s.filterCondition,p]}:p,s.offsetValue=0,s._offset!==void 0&&(s._offset=0),g.optimized=!0,g.cursorId=h.cursorId,n.observe("CURSOR_SEEK",h.cursorId),{query:s,execution:g}}async registerContinuousPage(e,t,n){if(!(!t||n.length!==t.limit||!n.length||n[n.length-1].id===void 0)){try{await D(this.runtimeTelemetry,{family:"cache",name:"continuous_page.put",attributes:{"teaql.cache.operation":"put"}},()=>t.runtime.put(t.queryKey,t.offset+n.length,{cursorId:`cpg_${Date.now().toString(16)}_${Math.random().toString(16).slice(2)}`,boundary:n[n.length-1].id,expiresAt:Date.now()+t.ttlSeconds*1e3}))}catch{t.runtime.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE");return}t.optimized&&t.runtime.observe("CURSOR_SEEK",t.cursorId)}}executeForStream(e,t=1e3){try{const n=e instanceof L?new L(e.query,e.intent):new L(e);return this.executeCapturedStream(n.query,t)}catch(n){return(async function*(){throw n})()}}async*executeCapturedStream(e,t){if(await this.telemetryStartup,!Number.isInteger(t)||t<=0)throw new Error("stream chunk size must be a positive integer");if(Array.isArray(e.facets)&&e.facets.length>0)throw new Error("QRY-F01_STREAM_UNSUPPORTED: execute facets with executeForList");const{sql:n,values:r,aggregateNames:o}=await this.compileQuery(e),s=await this.queryTreeBindings(e,n,r),a=N(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.stream`,attributes:{"teaql.entity.type":String(e.entity)}});let c;const u=async()=>{c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.stream`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}})};await(a.run?a.run(u):u());const l=c.correlation?.(),f=this.driver.stream(n,r)[Symbol.asyncIterator](),g=Date.now();let h="cancelled",p=0,m=[];const y=this.descendantBindings(e,n,r,s);try{for(;;){const d=await(c.run?c.run(()=>f.next()):f.next());if(d.done)break;m.push(this.decodeRow(e.entity,d.value,o)),m.length===t&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m,m=[])}m.length&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m),h="success"}catch(d){throw h="failure",c.failure(d),a.failure(d),d}finally{try{await f.return?.()}catch(d){if(h!=="failure")throw h="failure",c.failure(d),a.failure(d),d}finally{if(h==="failure")try{this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,l)}catch{}else this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,l),c.success({attributes:{"teaql.result.cardinality":p}}),a.success({attributes:{"teaql.result.cardinality":p}})}}}async enhanceQueryRows(e,t,n){if(!e.length)return;const r=[...(t.relations??[]).map(a=>a.name),...(t.relationAggregates??[]).map(a=>a.relationName)];if(!r.length)return;const o=this.schema(t.entity),s=new Map;for(const a of r){const c=o.relations?.[a];if(!c)throw new Error(`Missing relation ${t.entity}.${a}`);s.has(c.localKey)||s.set(c.localKey,e.map(u=>u[c.localKey]))}await this.enhanceRelationAggregates(e,t,s,n),await this.enhanceRelations(e,t,s,n)}async enhanceRelations(e,t,n,r){if(!e.length||!Array.isArray(t.relations)||!t.relations.length)return;const o=this.schema(t.entity),s=new L(t).intent;for(const a of t.relations){const c=o.relations?.[a.name];if(!c)throw new Error(`Missing relation ${t.entity}.${a.name}`);const u=n.get(c.localKey),l=u.filter(S=>S!=null),f=a.query?this.queryLimit(a.query):void 0,g=a.query?.localTopNProbeParentThreshold?.(),h=c.many&&f!==void 0,p=Array.isArray(a.query?.selectItems)?a.query.selectItems:[],m=p.length>0&&!p.includes(c.foreignKey),y=this.driver.topNRelationPlanPolicy==="alwaysProbe",d=h&&(g===void 0?y:g>0&&l.length<=g),b=d?"bounded_probes":"window",E=N(this.runtimeTelemetry,{family:"relation_load",name:`${t.entity}.${String(a.name)}`,attributes:{"teaql.entity.type":String(t.entity),"teaql.relation.name":String(a.name),"teaql.relation.parent_count":l.length,"teaql.relation.per_parent_limit":f??0,"teaql.relation.configured_probe_threshold":g??"provider-default","teaql.relation.selected_plan":b,"teaql.relation.probe_count":d?l.length:0}});try{if(!l.length&&!(c.many&&a.query?.facets?.length)){for(const T of e)T[a.name]=c.many?[]:null;E.success({attributes:{"teaql.result.cardinality":0}});continue}const S={...a.query||{},entity:c.targetEntity,selectItems:m?[...p,c.foreignKey]:p,_filters:[...this.filters(a.query||{})],relations:[...a.query?.relations||[]],orderItems:[...a.query?.orderItems||[]],__teaqlPartitionBy:h&&!d?c.foreignKey:void 0};if(h){const T=this.groupBy(S),O=T.length||this.aggregates(S).length?T:["id"];for(const $ of O)S.orderItems.some(A=>A.field===$)||S.orderItems.push(P.asc($))}typeof S.clearContinuousPageRuntime=="function"&&S.clearContinuousPageRuntime(),S[this.internalQueryToken]=!0;const w=[],v={field:c.foreignKey,keys:new WeakMap};if(d)for(const T of l){const O={...S,_filters:[...S._filters,{[c.foreignKey]:{$eq:T}}],__teaqlPartitionBy:void 0};w.push(...await this.executeDerivedQuery(new L(t).derive(O,a.name,a.operation).query,r,s,v))}else S._filters.push({[c.foreignKey]:{$in:l}}),w.push(...await this.executeDerivedQuery(new L(t).derive(S,a.name,a.operation).query,r,s,v));for(const T of w)delete T.__teaql_partition_rank;const I=new Map;for(const T of w){if(!v.keys.has(T))throw new Error("Relation assembly lost its captured row identity");const O=v.keys.get(T),$=I.get(O)||[];$.push(T),I.set(O,$)}if(m)for(const T of w)delete T[c.foreignKey];for(const[T,O]of e.entries()){const $=I.get(u[T])||[];if(c.many&&a.query?.facets?.length){const A=a.query.clone();A.entity=c.targetEntity;const le=u[T],Te={[c.foreignKey]:le==null?{$in:[]}:{$eq:le}};A.filterCondition=A.filterCondition?{$and:[A.filterCondition,Te]}:Te,Q(t,A);const it=new L(t).derive(A,a.name,a.operation).query;O[a.name]=new Y($,{facets:await et(this,nt=>nt,it,A.facets)})}else{const A=u[T];O[a.name]=c.many?$:$[0]??(A==null?null:{[c.foreignKey]:A})}}E.success({attributes:{"teaql.result.cardinality":w.length}})}catch(S){throw E.failure(S),S}}}async enhanceRelationAggregates(e,t,n,r){const o=t.relationAggregates;if(!e.length||!Array.isArray(o)||!o.length)return;const s=this.schema(t.entity),a=new L(t).intent;for(const c of o){const u=s.relations?.[c.relationName];if(!u)throw new Error(`Missing relation ${t.entity}.${c.relationName}`);const l=n.get(u.localKey),f=l.filter(y=>y!=null);if(!f.length){for(const y of e)y[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{};continue}const g=c.query.clone();g.entity=u.targetEntity,g.selectItems=[],g.properties=[],g.orderItems=[],g.limitValue=0,g.offsetValue=0,g.relations=[],g.relationAggregates=[],g.aggregateItems.length||g.aggregate("Count","id",c.alias),g.groupByItems.includes(u.foreignKey)||g.groupBy(u.foreignKey);const h={[u.foreignKey]:{$in:f}};g.filterCondition=g.filterCondition?{$and:[g.filterCondition,h]}:h,g[this.internalQueryToken]=!0;const p=await this.executeDerivedQuery(new L(t).deriveAggregate(g,c.relationName,c.operation??{kind:"relation-count",relation:c.relationName,alias:c.alias}).query,r,a),m=new Map;for(const y of p)m.set(y[u.foreignKey],y);for(const[y,d]of e.entries()){const b=m.get(l[y]);b?c.singleResult?d[c.alias]=b[g.aggregateItems[0].alias]??null:d[c.alias]=Object.fromEntries(Object.entries(b).filter(([E])=>E!==u.foreignKey)):d[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{}}}}emptyAggregateValue(e){const t=e.aggregateItems[0];return!t||String(t.function).toLowerCase()==="count"?0:null}queryLimit(e){if(e._limit!==void 0)return Number(e._limit);if(e.limitValue!==void 0&&Number(e.limitValue)>0)return Number(e.limitValue)}async close(){try{await this.driver.close()}finally{await this.telemetryStartup,await this.standardTelemetryHandle?.release(),this.standardTelemetryHandle=void 0}}}function Jt(i){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))throw new Error(`Unsafe SQL identifier: ${i}`);return i}function Zt(i){const t={count:"COUNT",sum:"SUM",avg:"AVG",min:"MIN",max:"MAX"}[String(i).toLowerCase()];if(!t)throw new Error(`Unsupported aggregate: ${i}`);return t}class ei{constructor(e){this.worker=e,this.nextRequestId=1,this.pending=new Map,this.closed=!1,this.onMessage=t=>{const n=t.data;if(!n||n.type!=="teaql-browser-sqlite-response")return;const r=this.pending.get(n.requestId);if(r)if(this.pending.delete(n.requestId),n.error){const o=new Error(n.error.message);o.name=n.error.name,n.error.code&&(o.code=n.error.code),r.reject(o)}else r.resolve(n.result)},this.onError=t=>{const n=new Error(t.message||"Browser SQLite worker failed");n.name="BrowserSQLiteWorkerError";for(const r of this.pending.values())r.reject(n);this.pending.clear()},e.addEventListener("message",this.onMessage),e.addEventListener("error",this.onError)}request(e,t){if(this.closed)return Promise.reject(new Error("Browser SQLite worker is closed"));const n=this.nextRequestId++;return new Promise((r,o)=>{this.pending.set(n,{resolve:s=>r(s),reject:o}),this.worker.postMessage({type:"teaql-browser-sqlite-request",requestId:n,operation:e,payload:t})})}async close(e){if(!this.closed)try{await this.request("close")}finally{this.closed=!0,this.worker.removeEventListener("message",this.onMessage),this.worker.removeEventListener("error",this.onError),e&&this.worker.terminate?.();const t=new Error("Browser SQLite worker is closed");for(const n of this.pending.values())n.reject(t);this.pending.clear()}}}class ti{constructor(e){this.transport=e}query(e,t=[]){return this.transport.request("query",{sql:e,values:t})}}class $e{constructor(e,t){this.transport=e,this.options=t,this.databaseKind="sqlite",this.accessTail=Promise.resolve()}static async open(e,t={}){const n={storage:t.storage??"memory",databaseName:ni(t.databaseName??"teaql-browser.sqlite3"),terminateWorkerOnClose:t.terminateWorkerOnClose??!0},r=new ei(e);return await r.request("open",n),new $e(r,n)}identifier(e){return`"${Jt(e)}"`}placeholder(e){return"?"}contains(e,t){return`CAST(${e} AS TEXT) LIKE '%' || ${t} || '%'`}aggregateFunction(e){return Zt(e)}encode(e,t){return e==null?e:t?.logicalType==="json"&&typeof e!="string"?JSON.stringify(e):t?.logicalType==="boolean"?e?1:0:e instanceof Date?e.toISOString():e}async exclusive(e){const t=this.accessTail;let n;this.accessTail=new Promise(r=>{n=r}),await t;try{return await e()}finally{n()}}query(e,t=[]){return this.exclusive(()=>this.transport.request("query",{sql:e,values:t}))}async*stream(e,t=[]){const n=await this.query(e,t);for(const r of n.rows)yield r}transaction(e){return this.exclusive(async()=>{const t=new ti(this.transport);await t.query("BEGIN IMMEDIATE");try{const n=await e(t);return await t.query("COMMIT"),n}catch(n){try{await t.query("ROLLBACK")}catch{}throw n}})}async ensureSchema(e){for(const t of Object.values(e)){const n=this.identifier(t.table);await this.query(`CREATE TABLE IF NOT EXISTS ${n} ("id" INTEGER PRIMARY KEY, "version" INTEGER NOT NULL)`);const r=await this.query(`PRAGMA table_info(${n})`),o=new Set(r.rows.map(s=>String(s.name)));for(const[s,a]of Object.entries(t.columns))s==="id"||s==="version"||o.has(a.columnName)||await this.query(`ALTER TABLE ${n} ADD COLUMN ${this.identifier(a.columnName)} ${ii(a.logicalType)}${a.nullable===!1?" NOT NULL":""}`)}for(const t of Wt(e))await this.query(`CREATE INDEX IF NOT EXISTS ${this.identifier(t.name)} ON ${this.identifier(t.table)} (${this.identifier(t.foreignColumn)}, ${this.identifier(t.idColumn)} DESC)`);await this.query("CREATE TABLE IF NOT EXISTS teaql_id_space (type_name TEXT PRIMARY KEY, current_level INTEGER NOT NULL)")}async nextId(e,t){for(let n=1;n<=100;n+=1){const r=await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t]);if(!r.rowCount){try{if((await e.query("INSERT INTO teaql_id_space(type_name, current_level) VALUES (?, 1)",[t])).rowCount===1)return"1"}catch(c){if(!(await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t])).rowCount)throw c}continue}const o=Number(r.rows[0].id),s=o+1,a=await e.query("UPDATE teaql_id_space SET current_level = ? WHERE type_name = ? AND current_level = ?",[s,t,o]);if(a.rowCount===1)return String(s);if(a.rowCount!==0)throw new Error(`ID space update for ${t} changed ${a.rowCount} rows`)}throw new Error(`Unable to allocate ID for ${t} after 100 optimistic-lock attempts`)}ensureIdFloor(e,t,n){return Gt(e,r=>this.placeholder(r),t,n)}reset(){return this.exclusive(()=>this.transport.request("reset",this.options))}close(){return this.exclusive(()=>this.transport.close(this.options.terminateWorkerOnClose))}}class tt extends Xt{constructor(e,t){super(e,t),this.browserDriver=e}static async open(e,t,n={}){return new tt(await $e.open(e,n),t)}get storage(){return this.browserDriver.options.storage}async reset(e){await this.browserDriver.reset(),this.invalidateSchemaState(),await e.ensureSchema()}}function ii(i){return{boolean:"INTEGER",double:"REAL",decimal:"NUMERIC",date:"TEXT",datetime:"TEXT",json:"TEXT",integer:"INTEGER",text:"TEXT"}[i]}function ni(i){const e=i.trim();if(!e||e.includes("/")||e.includes("\\")||e==="."||e==="..")throw new TypeError("Browser SQLite databaseName must be a simple file name");return e}function hi(i,e,t,n){const r=o=>{if(o.includes("."))throw new Error("Dynamic search requires a trusted relation binding");const s=t[i.entity]?.queryFields;if(!s||!Object.prototype.hasOwnProperty.call(s,o))throw new Error("Missing generated scalar search binding");return s[o]};return ri(i,e,t,{filter:(o,s)=>{const[a,c]=Object.entries(s)[0];if(c===null&&a!=="$eq"&&a!=="$ne")throw new Error("Null supports only equality predicates");return{[r(o)]:s}},order:(o,s)=>s==="asc"?P.asc(r(o)):P.desc(r(o))},n)}function ri(i,e,t,n,r=o=>console.warn({...o,fieldPath:""})){const o=ai(e,i.entity,t,()=>{}),s=Object.entries(o.search.filter??{}).map(([f,g])=>n.filter(f,g)),a=(o.search.orderBy??[]).map(f=>n.order(f.field,f.direction));if(s.some(f=>!U(f)))throw new Error("Invalid trusted search filter binding");if(a.some(f=>!(f instanceof P)))throw new Error("Invalid trusted search order binding");const c=i.clone(),u=i._filters??[],l=[...u,...i.filterCondition?[i.filterCondition]:[]];return(s.length||u.length)&&c.filter({$and:[...l,...s]}),c.orderItems.push(...a),o.warnings.forEach(f=>r({...f})),{query:c,warnings:o.warnings}}const Z=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),U=i=>typeof i=="object"&&i!==null&&!Array.isArray(i),si=new Set(["__proto__","prototype","constructor"]),oi=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$notIn","$contains"]);function ai(i,e,t,n=o=>console.warn({...o,fieldPath:""}),r=100){if(!Number.isSafeInteger(r)||r<1)throw new Error("Invalid search limit");if(!Z(t,e))throw new Error("Unknown search entity");let o;try{o=typeof i=="string"?JSON.parse(i):i}catch{throw new Error("Dynamic search requires valid JSON")}if(!U(o)||Object.keys(o).some(h=>!["filter","orderBy"].includes(h)))throw new Error("Unsupported dynamic search input or control");if(o.filter!==void 0&&!U(o.filter))throw new Error("Invalid search filter");if(o.orderBy!==void 0&&!Array.isArray(o.orderBy))throw new Error("Invalid search ordering");const s=Object.entries(o.filter??{}),a=o.orderBy??[];if(s.length+a.length>r)throw new Error("Dynamic search exceeds clause limit");const c=[],u={filter:Object.create(null),orderBy:[]};function l(h){const p=h.split(".");if(p.length>16||p.some(d=>!d||d.startsWith("$")||si.has(d)))throw new Error("Invalid dynamic search field path");let m=t[e];for(const d of p.slice(0,-1)){if(!Z(m.relations,d))return;const b=m.relations[d];if(!Z(t,b))throw new Error("Invalid trusted search relation metadata");m=t[b]}const y=p[p.length-1];return Z(m.fields,y)?m.fields[y]:void 0}function f(h,p){c.push({code:"DYNAMIC_SEARCH_UNKNOWN_FIELD",entity:e,clause:p,fieldPath:h})}function g(h,p){if(h===null)return;if(!(p==="date"?typeof h=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(h)&&!h.startsWith("0000-")&&Number.isFinite(Date.parse(h+"T00:00:00Z"))&&new Date(h+"T00:00:00Z").toISOString().slice(0,10)===h:p==="decimal"?typeof h=="string"&&/^[+-]?\d+(?:\.\d+)?$/.test(h)||typeof h=="number"&&Number.isFinite(h):p==="integer"||p==="timestamp"?typeof h=="number"&&Number.isSafeInteger(h):p==="number"?typeof h=="number"&&Number.isFinite(h):typeof h===p))throw new Error("Invalid value for known search field")}for(const[h,p]of s){const m=U(p)?Object.entries(p):[["$eq",p]];if(m.length!==1||!oi.has(m[0][0]))throw new Error("Unsupported or malformed dynamic search operator");const[y,d]=m[0];if((y==="$in"||y==="$notIn")&&(!Array.isArray(d)||d.length>1e3))throw new Error("Invalid or oversized search value list");const b=l(h);if(b===void 0){f(h,"FILTER");continue}if(b==="unsupported")throw new Error("Known search field has no supported scalar binding");if(y==="$contains"&&b!=="string")throw new Error("String operator requires a string field");if(Array.isArray(d)){if(y!=="$in"&&y!=="$notIn")throw new Error("Unexpected search value list");d.forEach(E=>g(E,b))}else g(d,b);u.filter[h]={[y]:Array.isArray(d)?[...d]:d}}for(const h of a){if(!U(h)||Object.keys(h).some(m=>!["field","direction"].includes(m))||typeof h.field!="string"||!["asc","desc"].includes(h.direction))throw new Error("Invalid dynamic search ordering");const p=l(h.field);if(p===void 0){f(h.field,"ORDER_BY");continue}if(p==="unsupported")throw new Error("Known search field has no supported scalar binding");u.orderBy.push({field:h.field,direction:h.direction})}return c.forEach(h=>n({...h})),{search:u,warnings:c}}export{tt as B,ot as C,ci as D,Le as L,z as M,P as O,se as Q,Je as R,Ft as S,Dt as U,Y as a,ui as b,li as c,hi as d,et as e,C as f,ri as m}; diff --git a/dist/assets/dynamic-search-Ch_QcWVU.js b/dist/assets/dynamic-search-Ch_QcWVU.js new file mode 100644 index 0000000000000000000000000000000000000000..8aa6295624fcd4cc13d4a4e38c05a81cc8a45ca9 --- /dev/null +++ b/dist/assets/dynamic-search-Ch_QcWVU.js @@ -0,0 +1,8 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function t(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=t(r);fetch(r.href,o)}})();const Re=Object.freeze({success:()=>{},failure:()=>{}}),ut=new Set(["teaql.entity.id","teaql.user.id","teaql.tenant.id","teaql.query.parameters","teaql.field.values","teaql.audit.reason","db.query.parameter_values","http.request.body","url.full"]);function ht(i){const e={"teaql.operation.family":i.family,"teaql.operation.name":i.name};for(const[t,n]of Object.entries(i.attributes||{}))ut.has(t)||(e[t]=n);return Object.freeze({...i,attributes:Object.freeze(e)})}function N(i,e){if(!i)return Re;try{const t=i.start(ht(e));let n=!1;return{correlation:()=>{try{return t.correlation?.()}catch{return}},run:t.run?r=>t.run(r):r=>r(),success(r){if(!n){n=!0;try{t?.success(r)}catch{}}},failure(r){if(!n){n=!0;try{t?.failure(r)}catch{}}}}}catch{return Re}}async function F(i,e,t,n){const r=N(i,e);try{const o=await(r.run?r.run(t):t());return r.success(n?.(o)),o}catch(o){throw r.failure(o),o}}class dt extends Error{constructor(e){super(`Check failed: ${e.map(t=>t.message??`${t.ruleId}:${t.location}`).join("; ")}`),this.violations=e,this.name="CheckException"}}class C extends Error{constructor(e){super(`Object storage: ${e}`),this.code=e,this.name="StorageError"}}const Ke=Symbol.for("nodejs.util.inspect.custom"),G=()=>{throw new C("InvalidInput")};function ft(i){return(typeof i!="string"||!i||/[^\x20-\x7e]/.test(i))&&G(),i}class gt{#e;#t;constructor(e=300,t,n){(!Number.isInteger(e)||e<=0||e>604800||t!==void 0&&!["inline","attachment"].includes(t))&&G(),n!==void 0&&(ft(n),(!t||/[\/\\"]/.test(n))&&G()),this.#e=e,this.#t=t+(n===void 0?"":`; filename="${n}"`),t===void 0&&(this.#t=void 0)}get seconds(){return this.#e}get contentDisposition(){return this.#t}toString(){return"ObjectReadUrlOptions[details=masked]"}[Ke](){return this.toString()}}function ke(i){return i instanceof C?i:new C("Unavailable")}const Ce=i=>String(i??"").replace(/[\x00-\x1f\x7f-\x9f]/g," ");class _e{constructor(e,t){this.invocation=e,this.operation=t,this.scope=N(e.context.getResource("runtimeTelemetry"),{family:"object_storage",name:t})}#e=!1;#t=performance.now();finish(e){if(this.#e)return;this.#e=!0,e==="success"?this.scope.success():this.scope.failure(new C(e==="cancelled"?"Io":e));const t=Object.freeze({operation:this.operation,comment:Ce(this.invocation.comment),traceId:Ce(this.invocation.context.getResource("traceId")),outcome:e,elapsedMs:performance.now()-this.#t});try{const n=this.invocation.context.getResource("objectStorageObserver");n?n(t):console.info(`ObjectStorage operation=${t.operation} comment=${t.comment} trace=${t.traceId} outcome=${t.outcome} elapsedMs=${t.elapsedMs.toFixed(3)}`)}catch{}}}class pt{#e;#t;#i;constructor(e,t,n){this.#e=e,this.#t=t,this.#i=n}get metadata(){return this.#e}get stream(){return this.#t}close(){return this.#i()}toString(){return"ObjectContent[masked]"}[Ke](){return this.toString()}}class mt{#e;#t;constructor(e,t){(typeof t!="string"||!t.trim())&&G();const n=e.getResource("objectStorageProvider");if(!n)throw new C("NotConfigured");this.#e=Object.freeze({context:e,comment:t}),this.#t=n}async#i(e,t){const n=new _e(this.#e,e);try{const r=await(n.scope.run?n.scope.run(t):t());return n.finish("success"),r}catch(r){const o=ke(r);throw n.finish(o.code),o}}async put(e,t,n){const r=t[Symbol.asyncIterator]();let o=!1;const s={next:async()=>{const a=await r.next();return a.done&&(o=!0),a},return:async()=>(o||(o=!0,await r.return?.()),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}};return this.#i("put",async()=>{try{return await this.#t.put(this.#e,e,s,n)}finally{await s.return()}})}async putBytes(e,t,n){return this.put(e,(async function*(){yield t})(),n)}async get(e){const t=new _e(this.#e,"get");let n;try{n=await(t.scope.run?t.scope.run(()=>this.#t.get(this.#e,e)):this.#t.get(this.#e,e))}catch(c){const l=ke(c);throw t.finish(l.code),l}let r=!1,o=!1;const s=async()=>{if(!r){r=!0;try{await n.close(),t.finish("cancelled")}catch{throw t.finish("Io"),new C("Io")}}},a={[Symbol.asyncIterator]:async function*(){if(o||r)throw new C("Io");o=!0;let c=n.metadata.size;try{for await(const l of n.stream){if(!(l instanceof Uint8Array)||l.byteLength>c)throw new C("Io");c-=l.byteLength,yield l}if(c!==0)throw new C("Io");t.finish("success")}catch{throw t.finish("Io"),new C("Io")}finally{await s()}}};return new pt(n.metadata,a,s)}async getBytes(e,t){(!Number.isSafeInteger(t)||t<0)&&G();const n=await this.get(e);try{if(n.metadata.size>t)throw new C("TooLarge");const r=[];let o=0;for await(const c of n.stream){if(c.byteLength>t-o)throw new C("TooLarge");o+=c.byteLength,r.push(c)}const s=new Uint8Array(o);let a=0;for(const c of r)s.set(c,a),a+=c.byteLength;return s}finally{await n.close()}}head(e){return this.#i("head",()=>this.#t.head(this.#e,e))}async exists(e){return await this.head(e)!==void 0}delete(e){return this.#i("delete",()=>this.#t.delete(this.#e,e))}getReadUrl(e,t=new gt){return this.#i("read_url",()=>this.#t.getReadUrl(this.#e,e,t))}}const yt="teaql.i18n/v1",wt="en",bt={en:{messages:{"checker.required":"The {location} is required","checker.min":"The {location} should be equal or greater than {system}, but input is {input}","checker.max":"The {location} should be equal or less than {system}, but input is {input}","checker.minLength":"The length of {location} should be equal or greater than {system}, but the length of {input} is {input_len}","checker.maxLength":"The length of {location} should be equal or less than {system}, but the length of {input} is {input_len}"},vocabulary:{}},"zh-CN":{messages:{"checker.required":"{location} 是必填项","checker.min":"{location} 应该大于等于 {system},但输入值为 {input}","checker.max":"{location} 应该小于等于 {system},但输入值为 {input}","checker.minLength":"{location} 的长度应大于等于 {system},但实际长度为 {input_len}","checker.maxLength":"{location} 的长度应小于等于 {system},但实际长度为 {input_len}"},vocabulary:{}},"zh-TW":{messages:{"checker.required":"{location} 是必填的","checker.min":"{location} 應該等於或大於 {system},但輸入為 {input}","checker.max":"{location} 應該等於或小於 {system},但輸入為 {input}","checker.minLength":"{location} 的長度應該等於或大於 {system},但 {input} 的長度是 {input_len}","checker.maxLength":"{location} 的長度應該等於或小於 {system},但 {input} 的長度是 {input_len}"},vocabulary:{}},ja:{messages:{"checker.required":"{location} は必須です","checker.min":"{location} は {system} 以上である必要があります。入力値は {input} です","checker.max":"{location} は {system} 以下である必要があります。入力値は {input} です","checker.minLength":"{location} の長さは {system} 以上である必要があります。実際の長さは {input_len} です","checker.maxLength":"{location} の長さは {system} 以下である必要があります。実際の長さは {input_len} です"},vocabulary:{}},ko:{messages:{"checker.required":"{location}은(는) 필수입니다","checker.min":"{location}은(는) {system} 이상이어야 하지만 입력값은 {input}입니다","checker.max":"{location}은(는) {system} 이하여야 하지만 입력값은 {input}입니다","checker.minLength":"{location}의 길이는 {system} 이상이어야 하지만 실제 길이는 {input_len}입니다","checker.maxLength":"{location}의 길이는 {system} 이하여야 하지만 실제 길이는 {input_len}입니다"},vocabulary:{}},de:{messages:{"checker.required":"{location} ist erforderlich","checker.min":"{location} muss mindestens {system} sein, aber die Eingabe ist {input}","checker.max":"{location} darf höchstens {system} sein, aber die Eingabe ist {input}","checker.minLength":"Die Länge von {location} muss mindestens {system} sein, ist aber {input_len}","checker.maxLength":"Die Länge von {location} darf höchstens {system} sein, ist aber {input_len}"},vocabulary:{}},fr:{messages:{"checker.required":"{location} est obligatoire","checker.min":"{location} doit être supérieur ou égal à {system}, mais la valeur saisie est {input}","checker.max":"{location} doit être inférieur ou égal à {system}, mais la valeur saisie est {input}","checker.minLength":"La longueur de {location} doit être supérieure ou égale à {system}, mais elle est {input_len}","checker.maxLength":"La longueur de {location} doit être inférieure ou égale à {system}, mais elle est {input_len}"},vocabulary:{}},es:{messages:{"checker.required":"{location} es requerido/a","checker.min":"{location} debe ser mayor o igual que {system}, pero el valor ingresado es {input}","checker.max":"{location} debe ser menor o igual que {system}, pero el valor ingresado es {input}","checker.minLength":"La longitud de {location} debe ser mayor o igual que {system}, pero es {input_len}","checker.maxLength":"La longitud de {location} debe ser menor o igual que {system}, pero es {input_len}"},vocabulary:{}},pt:{messages:{"checker.required":"{location} é obrigatório","checker.min":"{location} deve ser maior ou igual a {system}, mas a entrada é {input}","checker.max":"{location} deve ser menor ou igual a {system}, mas a entrada é {input}","checker.minLength":"O comprimento de {location} deve ser maior ou igual a {system}, mas é {input_len}","checker.maxLength":"O comprimento de {location} deve ser menor ou igual a {system}, mas é {input_len}"},vocabulary:{}},ar:{messages:{"checker.required":"{location} مطلوب","checker.min":"يجب أن يكون {location} مساويًا أو أكبر من {system}، لكن المُدخل هو {input}","checker.max":"يجب أن يكون {location} مساويًا أو أصغر من {system}، لكن المُدخل هو {input}","checker.minLength":"يجب أن يكون طول {location} مساويًا أو أكبر من {system}، لكن الطول هو {input_len}","checker.maxLength":"يجب أن يكون طول {location} مساويًا أو أصغر من {system}، لكن الطول هو {input_len}"},vocabulary:{}},th:{messages:{"checker.required":"{location} เป็นสิ่งจำเป็น","checker.min":"{location} ควรจะเท่ากับหรือมากกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.max":"{location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.minLength":"ความยาวของ {location} ควรจะเท่ากับหรือมากกว่า {system} แต่ความยาวคือ {input_len}","checker.maxLength":"ความยาวของ {location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ความยาวคือ {input_len}"},vocabulary:{}},id:{messages:{"checker.required":"{location} wajib diisi","checker.min":"{location} harus sama dengan atau lebih besar dari {system}, tetapi input adalah {input}","checker.max":"{location} harus sama dengan atau lebih kecil dari {system}, tetapi input adalah {input}","checker.minLength":"Panjang {location} harus sama dengan atau lebih besar dari {system}, tetapi panjangnya {input_len}","checker.maxLength":"Panjang {location} harus sama dengan atau lebih kecil dari {system}, tetapi panjangnya {input_len}"},vocabulary:{}},fil:{messages:{"checker.required":"Ang {location} ay kinakailangan","checker.min":"Ang {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang input ay {input}","checker.max":"Ang {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang input ay {input}","checker.minLength":"Ang haba ng {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang haba ay {input_len}","checker.maxLength":"Ang haba ng {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang haba ay {input_len}"},vocabulary:{}},uk:{messages:{"checker.required":"{location} є обов'язковим","checker.min":"{location} повинен бути рівним або більшим за {system}, але ввідне значення {input}","checker.max":"{location} повинен бути рівним або меншим за {system}, але ввідне значення {input}","checker.minLength":"Довжина {location} повинна бути рівною або більшою за {system}, але довжина становить {input_len}","checker.maxLength":"Довжина {location} повинна бути рівною або меншою за {system}, але довжина становить {input_len}"},vocabulary:{}},vi:{messages:{"checker.required":"{location} là bắt buộc","checker.min":"{location} phải lớn hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.max":"{location} phải nhỏ hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.minLength":"Độ dài của {location} phải lớn hơn hoặc bằng {system}, nhưng độ dài là {input_len}","checker.maxLength":"Độ dài của {location} phải nhỏ hơn hoặc bằng {system}, nhưng độ dài là {input_len}"},vocabulary:{}}},St={schema:yt,defaultLocale:wt,locales:bt},vt=["en","zh-CN","zh-TW","ja","ko","de","fr","es","pt","ar","th","id","fil","uk","vi"];class Pe extends Error{constructor(e){super(`Unsupported locale: ${e}`),this.localeCode=e}}const Et={"en-us":"en","en-gb":"en",zh:"zh-CN","zh-hans":"zh-CN","zh-sg":"zh-CN",cn:"zh-CN","zh-hant":"zh-TW","zh-hk":"zh-TW","zh-mo":"zh-TW",tw:"zh-TW","ja-jp":"ja","ko-kr":"ko","de-de":"de","fr-fr":"fr","es-mx":"es","pt-br":"pt","pt-pt":"pt","ar-sa":"ar","th-th":"th","id-id":"id",tl:"fil","fil-ph":"fil","uk-ua":"uk","vi-vn":"vi"};function We(i){if(typeof i!="string"||!i.trim())throw new Pe(i);const e=i.trim().replace(/_/g,"-").toLowerCase(),t=vt.find(r=>r.toLowerCase()===e);if(t)return t;const n=Et[e];if(!n)throw new Pe(i);return n}const ue=class ue{constructor(e,t){if(this.data=e,this.fallback=t,e.schema!=="teaql.i18n/v1")throw new Error("Unsupported i18n schema");Object.keys(e.locales).forEach(We)}message(e,t){return this.data.locales[e]?.messages[t]??this.fallback?.data.locales[e]?.messages[t]??this.data.locales.en?.messages[t]??this.fallback?.data.locales.en?.messages[t]??t}translate(e,t){const r={required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"}[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,o=String(e.inputValue),s=typeof e.inputValue=="string"?[...e.inputValue].length:0;return e.message=this.message(t,r).split("{location}").join(e.location.nativePath()).split("{system}").join(String(e.systemValue)).split("{input}").join(o).split("{input_len}").join(String(s)),e}};ue.builtin=new ue(St);let we=ue;const Ge=Symbol("teaql.context.schema-capability");function _(i){return Object.freeze(i.map(e=>Object.freeze({...e})))}class It{#e;#t;constructor(e,t){this.#e=e,this.#t=Object.freeze({...t}),Object.freeze(this)}recover(){const e=[];let t=this;for(;t;)e.push(t.#t),t=t.#e;return _(e.reverse())}}function Lt(i,e,t,n,r){const o=i?r:n;if(i&&(typeof o!="string"||new RegExp("^\\p{White_Space}*$","u").test(o)))return i;const s=String(t),a=/^(0|[1-9][0-9]*)$/.test(s)&&BigInt(s)<=18446744073709551615n?t:void 0;return new It(i,{kind:"auditReason",name:e,entityId:a,detail:o})}const $t=new Set(["comment","purpose","auditReason"]),de=i=>!new RegExp("^\\p{White_Space}*$","u").test(i);function be(i,e,t){const n=s=>{for(let a=i.length-1;a>=0;a--)if(i[a].kind===s)return i[a].detail??""},r=["operation","provider","sql"].every(s=>i.some(a=>a.kind===s));let o;if(r)o=i.filter(s=>!$t.has(s.kind));else{const s=i.find(c=>de(c.name))?.name??"unknown";let a=s;if(t!=="select")for(const c of i)c.kind==="entity"&&de(c.name)&&(a=c.name);o=[{kind:"operation",name:s,detail:t==="select"?"query":"mutation"},{kind:t==="select"?"request":"entity",name:t==="select"?s:a,detail:""},...i.filter(c=>c.kind==="relation"),{kind:"provider",name:de(e)?e:"unknown",detail:""},{kind:"sql",name:t,detail:""}]}return Object.freeze({tracePath:_(o),comment:n("comment"),purpose:n("purpose"),auditReason:n("auditReason")})}function He(i,e,t){return _([{kind:"comment",name:i,detail:e},{kind:"purpose",name:i,detail:t}])}function Ot(i,e,t,n){if(n&&!i.trim())throw new Error("Missing SQL template");let r=0;const o=new Set,s=l=>{if(l<0||l>=e.length)throw new Error("SQL bind count mismatch");return o.add(l),n?n(l):Ye(e[l],t)};let a="",c="sql";for(let l=0;l=0&&h=0&&ht.toString(16).padStart(2,"0")).join("")}'`:P(typeof i=="object"?JSON.stringify(i):String(i))}function P(i){return`'${i.replace(/'/g,"''")}'`}var Tt={};const At="TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS",Rt="I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK",ne="[REDACTED]",fe="[REDACTED SQL; NOT REPLAYABLE]",kt=`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN +`;let qe=!1;function Ct(i){const e=Array.from(i);return e.length<8||/^[0-9]+$/.test(i)?"*".repeat(e.length):e.slice(0,2).join("")+"*".repeat(e.length-4)+e.slice(-2).join("")}function _t(){const e=Tt?.[At]===Rt;return e&&!qe&&(qe=!0,console.warn("TeaQL: sensitive plaintext logging enabled; application data may be written to disk. Authentication secrets remain redacted.")),e}function H(i){const e=i.toLowerCase().replace(/[^a-z0-9]/g,"");return["password","passwd","passphrase","privatekey","secret","accesstoken","refreshtoken","idtoken","apikey","authorization","credential","sessiontoken","magiclinktoken"].some(t=>e.includes(t))}function Se(i){return Array.isArray(i)?i.some(Se):i&&typeof i=="object"?Object.entries(i).some(([e,t])=>H(e)||Se(t)):!1}function x(i){return i==null||i===""?[]:Array.isArray(i)?i.flatMap(x):i instanceof Date?[i.toISOString()]:typeof i=="object"?Object.values(i).flatMap(x):[String(i)]}function K(i,e){return[...new Set(e)].sort((t,n)=>n.length-t.length).reduce((t,n)=>t?.split(n).join(ne),i)}const W=new WeakMap,ve=new WeakMap,Xe=new WeakMap;function Ne(i,e,t=[]){Xe.set(i,{bindings:e?R(e):void 0,intentValues:Object.freeze(t.map(Y))})}function re(i){const e=i.parameterLogPolicies,t=!!e&&e.length===i.parameters.length,n=H(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!t);return i.parameters.map((r,o)=>{if(n||Se(r))return"credential";const s=t?e[o]:void 0;return s==="plain"||s==="masked"||s==="credential"?s:"unknown"})}function Ee(i,e){return i==="credential"||i==="unknown"||!e&&i!=="plain"}function xe(i){if(!i)return[];const e=re(i);return i.parameters.flatMap((t,n)=>Ee(e[n],!1)?x(t):[])}function Y(i){return i instanceof Date?new Date(i.getTime()):i instanceof Uint8Array?new Uint8Array(i):Array.isArray(i)?Object.freeze(i.map(Y)):i&&typeof i=="object"?Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,Y(t)]))):i}function R(i,e){const t=e?[e,i]:[i];return Object.freeze({parameterizedSQL:"",sqlOrigin:"generated",parameters:Object.freeze(t.flatMap(n=>n.parameters.map(Y))),parameterLogPolicies:Object.freeze(t.flatMap(re))})}function Ie(i){return i==null?null:Array.isArray(i)?i.map(Ie):i&&typeof i=="object"&&"type"in i?Ie(i.value):typeof i=="object"&&!(i instanceof Date)?ne:Ct(i instanceof Date?i.toISOString():String(i))}function Je(i,e,t=[]){const n=_t()&&i.logMode!=="masked",r=W.get(i);if(r!==void 0&&(!r||n))return i;const o=ve.get(i);if(!n&&o)return o;const s=se(i,n,e,t);if(W.set(s,n),n){const a=se(i,!1,e,t);W.set(a,!1),ve.set(s,a)}return s}function Pt(i){const e=ve.get(i);if(e)return e;if(W.get(i)===!1)return i;const t=se(i,!1);return W.set(t,!1),t}function se(i,e,t,n=[]){const r=Xe.get(i);r?.bindings&&(t=R(r.bindings,t)),r&&(n=[...n,...r.intentValues]);const o=i.parameterLogPolicies,s=!o||o.length===i.parameters.length,a=H(i.parameterizedSQL)&&(i.sqlOrigin!=="generated"||!o||!s),c=re(i),l=c.map(w=>Ee(w,e)),u=i.parameters.flatMap((w,v)=>l[v]?x(w):[]);if(t){const w=re(t);u.push(...t.parameters.flatMap((v,I)=>Ee(w[I],e)?x(v):[]))}const f=[...u,...n.flatMap(x)],g=!e&&i.logMode==="debug-plaintext"&&!t,h=w=>g&&w?ne:K(w,f),p=i.parameters.map((w,v)=>l[v]?c[v]==="masked"?Ie(w):ne:Y(w)),m=i.parameterizedSQL.replace(/\$[0-9]+|@p[0-9]+/gi,"?"),y=(!e||a)&&i.sqlOrigin!=="generated"&&/['"`$]|--|\/\*|\b\d+\b|:[A-Za-z_]/.test(m),d=i.databaseKind??"sqlite";let b=fe,E=y?"untrusted-literal-sql":s?void 0:"policy-count-mismatch";if(!y&&s)try{b=Ot(i.parameterizedSQL,p,d,w=>Ye(p[w],d)+(l[w]?" /* masked */":"")),b=(e?l.some(Boolean)?`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN; PARTIALLY MASKED; NOT REPLAYABLE +`:kt:`-- TeaQL MASKED; NOT REPLAYABLE +`)+b}catch{b=fe,E="unsupported-or-mismatched-bindings"}return Object.freeze({...i,...i.statements?{statements:Object.freeze(i.statements.map(w=>se(w,e,R(i,t),n)))}:{},parameterizedSQL:y?fe:i.sqlOrigin==="generated"?i.parameterizedSQL:K(i.parameterizedSQL,u),parameters:Object.freeze(p),parameterLogPolicies:Object.freeze(c),maskedParameters:Object.freeze(l),logMode:e?"debug-plaintext":"masked",omissionReason:E,debugSQL:b,comment:h(i.comment),purpose:h(i.purpose),auditReason:h(i.auditReason),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},resultSummary:i.resultCount!==void 0?`${i.resultCount} rows returned`:i.affectedRows!==void 0?`${i.affectedRows} rows affected`:K(i.resultSummary,u),tracePath:Object.freeze(i.tracePath.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I]))))),...i.traceChain?{traceChain:Object.freeze(i.traceChain.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{},...i.mutationLineage?{mutationLineage:Object.freeze(i.mutationLineage.map(w=>Object.freeze(Object.fromEntries(Object.entries(w).map(([v,I])=>[v,v!=="entityId"&&typeof I=="string"?h(I):I])))))}:{}})}const X=new WeakMap,oe=new WeakMap;function je(i){return oe.get(i)}function qt(i,e){oe.set(i,e)}function Nt(i){return X.get(i)}function Q(i,e){X.set(e,X.get(i)??D(i))}function D(i,e=new Map){if(!i||typeof i!="object")return i;if(e.has(i))return e.get(i);if(i instanceof Date)return new Date(i.getTime());if(i instanceof Uint8Array)return new Uint8Array(i);const t=Array.isArray(i)?[]:Object.create(Object.getPrototypeOf(i));e.set(i,t);for(const o of Reflect.ownKeys(i)){const s=Object.getOwnPropertyDescriptor(i,o);"value"in s&&s.enumerable&&(s.value=D(s.value,e)),Object.defineProperty(t,o,s)}const n=X.get(i);n&&X.set(t,n);const r=oe.get(i);return r&&oe.set(t,r),t}const Z=new WeakMap;class Oe{#e;constructor(e={}){this.#e=D(e),Object.freeze(this)}values(){return D(this.#e)}static captureFor(e,t){const n=new Oe(t);return Z.set(e,n),n}static forEntity(e){return Z.get(e)}static restoreFor(e,t){t?Z.set(e,t):Z.delete(e)}}const Me=new WeakMap,ge=new WeakMap,Le=new WeakMap,Ze=new WeakMap;function et(i){if(!["named-count","facet","relation-count","relation-select","aggregate","pagination"].includes(i.kind)||i.method!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i.method)||i.alias!==void 0&&typeof i.alias!="string"||i.relation!==void 0&&typeof i.relation!="string")throw new Error("QUERY_OPERATION_INVALID: invalid generated operation descriptor");return Object.freeze({kind:i.kind,method:i.method,alias:i.alias,relation:i.relation})}function xt(i){const e=et(i),t=n=>"'"+n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+"'";return e.method?e.method+"("+(e.alias!==void 0?t(e.alias):e.kind==="relation-select"?"...":"")+")":"framework: "+e.kind+(e.relation?" "+e.relation:"")+(e.alias!==void 0?" "+t(e.alias):"")}const B=Symbol("runtime request binding");class jt extends Error{constructor(e,t,n){super(`${e}: ${n} request requires a non-blank ${t}; supply it at the request entry point`),this.code=e,this.field=t,this.requestKind=n,this.name="RequestIntentError"}}function z(i,e,t){if(typeof i!="string"||new RegExp("^\\p{White_Space}*$","u").test(i))throw new jt(e==="comment"?"REQUEST_COMMENT_REQUIRED":"QUERY_PURPOSE_REQUIRED",e,t);return i}class ae{#e;#t;constructor(e,t){this.#e=z(e,"comment","query"),this.#t=z(t,"purpose","query"),Object.freeze(this)}get comment(){return this.#e}get purpose(){return this.#t}}class U{#e;constructor(e){this.#e=z(e,"comment","mutation"),Object.freeze(this)}get comment(){return this.#e}get auditReason(){return this.#e}readbackIntent(){return new ae(this.#e,"verify persisted mutation result")}}class L{#e;#t;#i;#r;#s;#o;#n;constructor(e,t,n){const r=e,o=je(e),s=o instanceof L?o:void 0;if(this.#e=t===void 0?s?.intent??new ae(r?._comment??r?.commentText,r?._purpose??r?.purposeText):new ae(t?.comment,t?.purpose),n&&n[B]!==!0)throw new Error("QUERY_REQUEST_OWNERSHIP_INVALID: request binding is runtime-owned");const a=s&&s.intent.comment===this.#e.comment&&s.purpose===this.#e.purpose?s:void 0;this.#n=n?.invocation??(n?.parent?n.parent.#n:void 0)??(a?a.#n:void 0)??Object.freeze({}),this.#i=n?n.parent:a?.parentRequest,this.#r=z(n?.comment??a?.comment??this.#e.comment,"comment","query"),this.#s=n?.name??a?.requestName??String(r.entity??"query"),this.#o=n?.operation??a?.operation,this.#t=D(e);const c=this.#t;for(const[l,u]of[["commentText",this.comment],["purposeText",this.purpose],["_comment",this.comment],["_purpose",this.purpose]])Object.defineProperty(c,l,{value:u,enumerable:!l.startsWith("_"),configurable:!0,writable:!1});ge.set(c,_(n?.source??a?.traceSource??ge.get(e)??He(String(r.entity),this.intent.comment,this.purpose))),qt(c,this),Object.freeze(this)}get intent(){return this.#e}get query(){return this.#t}get comment(){return this.#r}get purpose(){return this.#e.purpose}get traceSource(){return ge.get(this.#t)}get parentRequest(){return this.#i}get rootRequest(){let e=this;for(;e.parentRequest;)e=e.parentRequest;return e}get requestName(){return this.#s}get operation(){return this.#o}get traceChain(){const e=[];for(let t=this;t;t=t.parentRequest)e.push({kind:"comment",name:t.requestName,detail:t.comment});return _([{kind:"purpose",name:this.rootRequest.requestName,detail:this.purpose},...e.reverse()])}withQuery(e){const t=je(e);if(t instanceof L&&t.#n!==this.#n)throw new Error("QUERY_SCOPE_OWNER_MISMATCH: replacement belongs to another query invocation");return new L(e,this.intent,{[B]:!0,parent:this.parentRequest,comment:this.comment,name:this.requestName,operation:this.operation,source:this.traceSource,invocation:this.#n})}deriveOperation(e,t){const n=et(t);return new L(e,this.intent,{[B]:!0,parent:this,comment:xt(n),name:String(e.entity??this.requestName),operation:n,source:this.traceSource})}deriveHelper(e,t){return new L(e,this.intent,{[B]:!0,parent:this,comment:z(t,"comment","query"),name:String(e.entity??this.requestName),source:this.traceSource})}derive(e,t,n){if(n)return this.deriveOperation(this.query,n).deriveChild(e,t);const r=`${String(this.query.entity)}.${t}`;return this.deriveChild(e,t,void 0,r)}deriveAggregate(e,t,n){const r=this.parentRequest?.operation?.kind==="facet"?this.parentRequest:void 0,o=r?r.deriveHelper(e,"aggregate "+r.operation.relation):this.deriveOperation(e,n),s=[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}],a=new L(e,this.intent,{[B]:!0,parent:o.parentRequest,comment:o.comment,name:o.requestName,operation:o.operation,source:s});return(e._comment??e.commentText)===void 0?a:a.deriveChild(e)}deriveChild(e,t,n,r){const o=e,s=o._comment??o.commentText;return new L(e,this.intent,{[B]:!0,parent:this,comment:s===void 0?n??`load ${String(o.entity)}`:z(s,"comment","query"),name:r??String(o.entity),source:t===void 0?this.traceSource:[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}]})}}class j{#e;#t;constructor(e,t){this.#e=new U(t===void 0?e?.comment:t?.comment),this.#t={...e},Object.defineProperty(this.#t,"comment",{value:this.#e.comment,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get intent(){return this.#e}get mutation(){return this.#t}get comment(){return this.#e.comment}withLoadedSnapshot(e){return Me.set(this,new Oe(e.values())),this}loadedValues(){return Me.get(this)?.values()??{}}get graphSession(){return Le.get(this)?.session}scopeFor(e){const t=Le.get(this),n=Lt(t?.parent,e.entity,e.id,this.comment,t?.localComment);return t&&Ze.set(n,t.session),n}traceFor(e){const t=this.#t,n=t.ledgerRoot?.traceChain(t.ledgerKey??e);return n?.length?_(n):this.scopeFor(e).recover()}auditProjection(e,t,n){const r=[...x(t),...x(this.#t.id),...n?xe(n):x(this.loadedValues()),...xe(this.graphSession?.logBindings)];return Object.freeze({reason:K(this.comment,r),mutationLineage:_(this.traceFor(e).map(o=>({...o,detail:K(o.detail,r)})))})}}class Mt{#e;#t;constructor(e){this.#e=new U(e?.comment),Object.freeze(this)}get intent(){return this.#e}request(e,t,n){if(t&&Ze.get(t)!==this)throw new Error("GRAPH_TRACE_SCOPE_MISMATCH: parent scope belongs to another graph invocation");const r=new j(e,this.#e);return Le.set(r,{session:this,parent:t,localComment:n}),r}captureLogBindings(e){this.#t=R(e,this.#t)}get logBindings(){return this.#t}}class De extends Error{constructor(e){super("GRAPH_ALREADY_COMMITTED: post-commit processing failed; do not retry as an uncommitted mutation"),this.cause=e,this.committed=!0,this.name="GraphCommittedError"}}const Dt="MUTATION-POLICY-001",Ft="MUTATION-POLICY-002";class k extends Error{constructor(e){super(e),this.name="MutationPolicyError"}}class wi{constructor(e){this.resolver=e}resolve(e){return this.resolver(e)}}class bi{constructor(e){this.finder=e}findApproval(e){return this.finder(e)}}class Bt{onWarning(e,t){!t.firstOccurrence||typeof console>"u"||console.warn(`TeaQL mutation policy warning code=${t.warningCode} requestKey=${t.snapshot.requestKey} source=${t.snapshot.source} approval=${t.snapshot.approvalStatus}`)}}let Fe=0;class zt{constructor(){this.profile={warningSink:new Bt},this.emittedWarnings=new Set,this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.remaining=new Map}setRegistry(e){this.profile.registry=e}setApprovalProvider(e){this.profile.approvalProvider=e}setWarningSink(e){this.profile.warningSink=e}beginGraph(){if(this.graphActive)throw new k("mutation policy graph is already active");this.graphActive=!0,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}endGraph(){this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}recordPreflight(e){if(!this.graphActive)return;if(this.graphReviewed)throw new k("mutation preflight cannot change after policy review");const t=Be(e);this.rootEntity??=t.entity,this.auditReason??=ee(e),this.preflight.push(t),this.preflightKeys.push(Qe(e,t))}enterMutation(e,t){const n=Be(t);if(!this.graphActive)return{snapshot:this.review(e,this.plan(n.entity,ee(t),[n]))};if(!this.graphReviewed){if(this.profile.registry&&this.preflight.length===0)throw new k("customer mutation policy requires complete graph preflight before provider mutation");if(!this.profile.registry&&this.preflight.length===0)return{snapshot:this.review(e,this.plan(n.entity,ee(t),[n]))};const r=this.preflight.length?this.preflight:[n];this.graphSnapshot=this.review(e,this.plan(this.rootEntity??r[0].entity,this.auditReason??ee(t),r)),this.remaining.clear();const o=this.preflight.length?this.preflightKeys:r.map(it);for(const s of o)this.remaining.set(s,(this.remaining.get(s)??0)+1);this.graphReviewed=!0}return this.consume(Qe(t,n)),{snapshot:this.graphSnapshot}}ensureGraphComplete(){if(this.graphReviewed&&this.remaining.size)throw new k("reviewed mutation plan contains operations that were not executed")}review(e,t){Qt(t);const n=ze(t),r=this.profile.registry?.resolve(n.requestKey);let o,s,a,c;if(!r)o="generated_default",a="not_applicable",c=[Dt];else{s=Ut(r.identity);const u=r.review(e,n);if(!u||u.verdict!=="allow"&&u.verdict!=="deny")throw new k("customer mutation policy returned an invalid decision");if(u.verdict==="deny")throw new k(`[MUTATION POLICY DENIED] ${u.code||"MUTATION-POLICY-DENIED"}: ${u.message||"mutation rejected"}`);o="customer";const f=this.profile.approvalProvider?.findApproval(s);a=Vt(f,s)?"approved":"missing",c=a==="approved"?[]:[Ft]}const l=Object.freeze({executionId:n.executionId,requestKey:n.requestKey,source:o,policy:s,approvalStatus:a,warningCodes:Object.freeze([...c]),operations:Object.freeze(n.operations.map(u=>Object.freeze({kind:u.kind,entity:u.entity,entityId:M(u.entityId),changedFields:Object.freeze(Object.keys(u.changedValues).sort())})))});for(const u of c)this.emitWarning(e,l,u);return l}plan(e,t,n){return Fe+=1,ze({executionId:`teaql-mutation-${Fe}`,requestKey:`${e}.saveGraph`,rootEntityType:e,auditReason:new U(t).comment,operations:n})}consume(e){const t=this.remaining.get(e)??0;if(t<1)throw new k("provider mutation is not present in the reviewed graph plan");t===1?this.remaining.delete(e):this.remaining.set(e,t-1)}emitWarning(e,t,n){const r=t.policy?`${t.policy.policyId}:${t.policy.version}:${t.policy.fingerprint}`:"none",o=`${t.requestKey}|${r}|${n}`,s=!this.emittedWarnings.has(o);this.emittedWarnings.add(o);try{this.profile.warningSink.onWarning(e,Object.freeze({snapshot:t,warningCode:n,firstOccurrence:s}))}catch{}}}function Be(i){const e=String(i?.entity??"").trim(),t=String(i?.action??"").toLowerCase(),n={create:"create",update:"update",delete:"delete",recover:"recover"};if(!e||!n[t])throw new k("mutation must contain a supported entity operation");const r=i?.payload&&typeof i.payload=="object"?i.payload:{};return Object.freeze({kind:n[t],entity:e,entityId:M(i?.id??r.id),originalVersion:i?.version??i?.expectedVersion,changedValues:tt(r)})}function ee(i){return new U(i?.comment).comment}function Qt(i){if(new U(i?.auditReason),!i.executionId?.trim())throw new k("execution id is required");if(!i.requestKey?.trim())throw new k("request key is required");if(!i.rootEntityType?.trim())throw new k("root entity type is required");if(!i.operations.length)throw new k("mutation plan is empty")}function Ut(i){if(!i||!i.policyId?.trim()||!i.version?.trim()||!i.fingerprint?.trim())throw new k("customer mutation policy identity is invalid");return Object.freeze({policyId:i.policyId.trim(),version:i.version.trim(),fingerprint:i.fingerprint.trim()})}function Vt(i,e){return!!i&&Kt(i.policy,e)&&!!i.approvedBy?.trim()&&i.approvedAt instanceof Date&&Number.isFinite(i.approvedAt.getTime())&&i.approvedAt.getTime()!==0}function Kt(i,e){return i.policyId===e.policyId&&i.version===e.version&&i.fingerprint===e.fingerprint}function ze(i){return Object.freeze({executionId:i.executionId,requestKey:i.requestKey,rootEntityType:i.rootEntityType,auditReason:i.auditReason,operations:Object.freeze(i.operations.map(e=>Object.freeze({kind:e.kind,entity:e.entity,entityId:M(e.entityId),originalVersion:e.originalVersion,changedValues:tt(e.changedValues)})))})}function M(i,e=new WeakSet){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||typeof i=="bigint")return i;if(i instanceof Date)return i.toISOString();if(typeof i=="object"){if(e.has(i))throw new k("mutation policy values must not contain cycles");e.add(i);try{if(Array.isArray(i))return Object.freeze(i.map(n=>M(n,e)));const t=i;return"id"in t&&Object.keys(t).some(n=>n!=="id")?M(t.id,e):Object.freeze(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,M(r,e)])))}finally{e.delete(i)}}return String(i)}function tt(i){return Object.freeze(Object.fromEntries(Object.entries(i).map(([e,t])=>[e,M(t)])))}function it(i){return ce({kind:i.kind,entity:i.entity,entityId:i.entityId,originalVersion:i.originalVersion,changedValues:i.changedValues})}function Qe(i,e){const t=i?.ledgerKey;return t&&typeof t=="object"&&String(t.entity??"").trim()&&t.id!==void 0&&t.id!==null?`ledger:${String(t.entity).trim()}:${ce(t.id)}`:`operation:${it(e)}`}function ce(i){return typeof i=="bigint"?JSON.stringify(`${i.toString()}n`):i===void 0?'""':i===null||typeof i!="object"?JSON.stringify(i):Array.isArray(i)?`[${i.map(ce).join(",")}]`:`{${Object.entries(i).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${ce(t)}`).join(",")}}`}const Ue=new WeakMap;let Wt=1;function Gt(i){if(!i||typeof i!="object"&&typeof i!="function")return String(i);const e=i;let t=Ue.get(e);return t||(t=Wt++,Ue.set(e,t)),String(t)}class Ve extends Error{constructor(e,t,n){super(`context root ${e}: expected ${t}`),this.reason=e,this.expectedType=t,this.activeRoot=n,this.name="ContextRootError"}}class Ht{constructor(){this.mutationPolicy=new zt,this.resources=new Map,this.continuousPageCursors=new Map,this.retainedIdSets=new Map,this.idSetBuilds=new Map,this.continuousPageRuntime={owner:"",get:(e,t)=>this.getContinuousPageCursor(e,t),put:(e,t,n)=>this.putContinuousPageCursor(e,t,n),observe:(e,t)=>{this.continuousPagePlan=e,this.continuousPageCursorId=t}},this.idSetPaginationRuntime={owner:"",scope:"",get:e=>this.idSetStore().get(e),put:(e,t)=>this.idSetStore().put(e,t),build:(e,t)=>this.singleFlightIdSetBuild(e,t),observe:(e,t)=>{this.idSetPaginationPlan=e,this.idSetPaginationCount=t,this.idSetPaginationCountAccuracy=e==="ID_SET_BUILD"||e==="ID_SET_HIT"?"EXACT":e==="ID_SET_FALLBACK_LIMIT_EXCEEDED"?"LOWER_BOUND":"UNKNOWN"}},this.userIdentifier="",this.continuousPagePlan="DISABLED",this.idSetPaginationPlan="ID_SET_DISABLED",this.idSetPaginationCountAccuracy="UNKNOWN",this.locale="en",this.i18nCatalog=we.builtin}withObjectStorage(e){return this.insertResource("objectStorageProvider",e)}withObjectStorageObserver(e){return this.insertResource("objectStorageObserver",e)}objectStorage(e){return new mt(this,e)}async withQueryRequest(e,t){const n=this.requireResource("dataService");return n.withQueryRequest?n.withQueryRequest(e,t):t()}setLocaleCode(e){const t=We(e);return this.locale=t,this}setLanguageCode(e){return this.setLocaleCode(e)}installI18nCatalog(e){if(!e)throw new Error("catalog is required");return this.i18nCatalog=e,this}installIdSetPaginationStore(e){if(!e)throw new Error("ID set pagination store is required");return this.insertResource("idSetPaginationStore",e)}translateCheckResults(e){return e.map(t=>this.i18nCatalog.translate(t,this.locale))}withMutationPolicyRegistry(e){if(!e||typeof e.resolve!="function")throw new TypeError("mutation policy registry must expose resolve(requestKey)");return this.mutationPolicy.setRegistry(e),this}withMutationPolicyApprovalProvider(e){if(!e||typeof e.findApproval!="function")throw new TypeError("mutation policy approval provider must expose findApproval(identity)");return this.mutationPolicy.setApprovalProvider(e),this}withMutationGovernanceSink(e){if(!e||typeof e.onWarning!="function")throw new TypeError("mutation governance sink must expose onWarning(context, warning)");return this.mutationPolicy.setWarningSink(e),this}reviewMutationPlan(e){return this.mutationPolicy.review(this,e)}beginMutationPolicyGraph(){this.mutationPolicy.beginGraph()}recordMutationPolicyPreflight(e){this.mutationPolicy.recordPreflight(e)}enterMutationPolicy(e){return this.mutationPolicy.enterMutation(this,e).snapshot}ensureMutationPolicyGraphComplete(){this.mutationPolicy.ensureGraphComplete()}endMutationPolicyGraph(){this.mutationPolicy.endGraph()}beginFixEvidence(){return this.insertResource("fixEvidenceCurrent",[])}recordFixEvidence(e){const t=String(e.sourceLabel||""),n=t.toLowerCase();if(!e.entityType||!e.modelPath||!t||n.includes("authorization")||n.includes("cookie")||n.includes("token="))throw new TypeError("Fix evidence must contain only safe framework provenance labels");const r=this.getResource("fixEvidenceCurrent")??[];return this.getResource("fixEvidenceCurrent")||this.insertResource("fixEvidenceCurrent",r),r.push(Object.freeze({...e})),this}finishFixEvidence(){const e=this.getResource("fixEvidenceCurrent")??[];return this.insertResource("fixEvidenceLast",Object.freeze([...e])),this.removeResource("fixEvidenceCurrent")}lastFixEvidence(){return this.getResource("fixEvidenceLast")??[]}insertResource(e,t){return this.resources.set(e,t),this}getResource(e){return this.resources.get(e)}removeResource(e){return this.resources.delete(e),this}requireResource(e){const t=this.getResource(e);if(t===void 0)throw new Error(`Required UserContext resource is missing: ${e}`);return t}ensureSchema(){const e=this.requireResource("dataService"),t=e[Ge];if(!t)throw new Error("Configured dataService is not a schema-aware TeaQL provider");return t.call(e,this)}withActiveRoot(e){if(!e||!e.entity||e.id===void 0||e.id===null)throw new TypeError("active root must be a typed entity reference");return this.insertResource("activeRoot",Object.freeze({...e}))}requireActiveRoot(e){const t=this.getResource("activeRoot");if(!t)throw new Ve("missing",e);if(t.entity!==e)throw new Ve("type_mismatch",e,t);return t}prepareQuery(e){this.continuousPageRuntime.owner=this.userIdentifier,this.idSetPaginationRuntime.owner=this.userIdentifier;const t=this.getResource("activeRoot");return this.idSetPaginationRuntime.scope=[this.userIdentifier,t?`${t.entity}:${String(t.id)}`:"-",Gt(this.getResource("dataService"))].join("|"),e.bindContinuousPageRuntime(this.continuousPageRuntime).bindIdSetPaginationRuntime(this.idSetPaginationRuntime)}getContinuousPageCursor(e,t){const n=`${e}:${t}`,r=this.continuousPageCursors.get(n);if(r&&r.expiresAt<=Date.now()){this.continuousPageCursors.delete(n);return}return r}putContinuousPageCursor(e,t,n){if(this.continuousPageCursors.size>=4096){const r=[...this.continuousPageCursors.entries()].sort((o,s)=>o[1].expiresAt-s[1].expiresAt)[0];r&&this.continuousPageCursors.delete(r[0])}this.continuousPageCursors.set(`${e}:${t}`,n)}getRetainedIdSet(e){const t=this.retainedIdSets.get(e);if(t&&t.expiresAt<=Date.now()){this.retainedIdSets.delete(e);return}return t}idSetStore(){return this.getResource("idSetPaginationStore")??{get:e=>this.getRetainedIdSet(e),put:(e,t)=>this.putRetainedIdSet(e,t),invalidate:e=>{this.retainedIdSets.delete(e)}}}putRetainedIdSet(e,t){if(t.ids.byteLength>268435456)throw new Error("ID set exceeds the process-local store memory ceiling");const r=()=>[...this.retainedIdSets.values()].reduce((o,s)=>o+s.ids.byteLength,0);for(;this.retainedIdSets.size>=64||r()+t.ids.byteLength>268435456;){const o=[...this.retainedIdSets.entries()].sort((s,a)=>s[1].expiresAt-a[1].expiresAt)[0];if(!o)break;this.retainedIdSets.delete(o[0])}this.retainedIdSets.set(e,t)}async singleFlightIdSetBuild(e,t){const n=this.idSetBuilds.get(e);if(n)return{value:await n,built:!1};const r=t();this.idSetBuilds.set(e,r);try{return{value:await r,built:!0}}finally{this.idSetBuilds.delete(e)}}}function nt(i,e){const t=i.defaultDomainRoot,n=e.defaultDomainRoot;if(t&&n&&(t.entity!==n.entity||t.id!==n.id))throw new Error("Cannot compose Runtime Modules with different Default Domain Roots");const r=new Map;for(const o of[...i.constants??[],...e.constants??[]])r.set(`${o.entity}:${o.id}`,o);return{defaultDomainRoot:n??t,constants:[...r.values()],ensure:i.ensure&&e.ensure?async o=>{await i.ensure(o),await e.ensure(o)}:e.ensure??i.ensure}}class rt{constructor(e={},t={},n={}){this.schemas=Object.freeze({...e}),this.checkers=Object.freeze({...t}),this.bootstrap=Object.freeze({defaultDomainRoot:n.defaultDomainRoot,constants:Object.freeze([...n.constants??[]]),ensure:n.ensure})}and(e){return new rt({...this.schemas,...e.schemas},{...this.checkers,...e.checkers},nt(this.bootstrap,e.bootstrap))}}class q{constructor(e,t,n){this.field=e,this.expr=t,this.direction=n}static new(e,t){return new q(e,null,t)}static expr(e,t){return new q("",e,t)}static asc(e){return q.new(e,"Asc")}static desc(e){return q.new(e,"Desc")}}class le{constructor(e,t,n,r){this.enabledValue=e,this.cacheExpiredMillis=t,this.propagateValue=n,this.propagateCacheExpiredMillis=r}static enabled(e){return new le(!0,e,!1,0)}propagate(e){return this.propagateValue=!0,this.propagateCacheExpiredMillis=e,this}}let Yt=class st{constructor(e){this.hardLimitValue=1e4,this.filterCondition=null,this.limitValue=0,this.offsetValue=0,this.orderItems=[],this.selectItems=[],this.properties=[],this.joins=[],this.groupByItems=[],this.aggregateItems=[],this.facets=[],this.relations=[],this.relationAggregates=[],this.entity=e,Object.defineProperty(this,"hardLimitValue",{enumerable:!1,writable:!0,value:1e4}),Object.defineProperty(this,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"topNProbeThreshold",{enumerable:!1,writable:!0,value:void 0})}comment(e){return this.commentText=e,this}purpose(e){return this.purposeText=e,this}facetBy(e,t,n,r=!0,o){return this.facets.push({facetName:e,relationName:t,query:n.toQuery(),includeAllFacets:r,operation:o}),this}clone(){const e=D(this);for(const t of["commentText","purposeText","_comment","_purpose"]){const n=Object.getOwnPropertyDescriptor(e,t);n&&"value"in n&&n.configurable&&Object.defineProperty(e,t,{...n,writable:!0})}return e}filter(e){return this.filterCondition=e,this}limit(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.limitValue=e,this}optimizeForContinuousPageFetch(){return this.optimizeForContinuousPageFetchWith("default",600)}optimizeForContinuousPageFetchWith(e,t){if(!e?.trim())throw new Error("continuous page namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("continuous page ttlSeconds must be a positive integer");return this.continuousPageFetchOptions={namespace:e,ttlSeconds:t},this}bindContinuousPageRuntime(e){return this.continuousPageRuntimeContext=e,this}localContinuousPageOptions(){return this.continuousPageFetchOptions}localContinuousPageRuntime(){return this.continuousPageRuntimeContext}clearContinuousPageRuntime(){return this.continuousPageRuntimeContext=void 0,this}optimizePaginationWithIdSet(){return this.optimizePaginationWithIdSetConfig("default",600,3e6)}optimizePaginationWithIdSetConfig(e,t,n){if(!e?.trim())throw new Error("ID set namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("ID set ttlSeconds must be a positive integer");if(!Number.isSafeInteger(n)||n<=0)throw new Error("ID set maxIds must be a positive integer");return this.idSetPaginationOptions={namespace:e,ttlSeconds:t,maxIds:n},this}bindIdSetPaginationRuntime(e){return this.idSetPaginationRuntimeContext=e,this}localIdSetPaginationOptions(){return this.idSetPaginationOptions}localIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext}clearIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext=void 0,this}topNProbeParentThreshold(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("topNProbeParentThreshold must be a non-negative safe integer");return this.topNProbeThreshold=e,this}localTopNProbeParentThreshold(){return this.topNProbeThreshold}prepareForList(){if(!Number.isSafeInteger(this.offsetValue)||this.offsetValue<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");if(this.limitValue&&(!Number.isSafeInteger(this.limitValue)||this.limitValue<1))throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.applyListLimit(this.hardLimitValue),this}forExactCount(e="__teaql_total"){const t=new st(this.entity);return t.filterCondition=D(this.filterCondition),t.commentText=this.commentText,t.purposeText=this.purposeText,t.aggregate("Count","id",e),Q(this,t),t}applyListLimit(e){if(this.limitValue||(this.limitValue=e),this.limitValue>e)throw new Error(`QUERY_HARD_LIMIT_EXCEEDED: requested limit ${this.limitValue} exceeds hard limit ${e}`);for(const t of this.relations)t.query?.applyListLimit(1e4)}offset(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");return this.offsetValue=e,this}relation(e){return this.relations.push({name:e}),this}relationQuery(e,t,n="id",r="id",o=!0,s){return this.relations.push({name:e,query:t,localKey:n,foreignKey:r,many:o,operation:s}),this}relationAggregate(e,t,n,r=!0,o){return this.relationAggregates.push({relationName:e,alias:t,query:n,singleResult:r,operation:o}),this}order(e){return this.orderItems.push(e),this}select(e){return this.selectItems.push(...e),this}enableAggregationCacheFor(e){return this.aggregationCache=le.enabled(e),this}propagateAggregationCache(e){return this.aggregationCache||(this.aggregationCache=le.enabled(0)),this.aggregationCache.propagate(e),this}aggregate(e,t,n){return this.aggregateItems.push({function:e,field:t,alias:n}),this}groupBy(e){return this.groupByItems.push(e),this}};function Xt(i,e){if(i.logMode!=="masked")throw new Error("Telemetry requires safe SQL projection");const t=(n=[])=>JSON.stringify(n.map(r=>({kind:r.kind,name:r.name,detail:r.detail??""})));return Object.freeze({body:"TeaQL SQL execution",correlation:e,attributes:Object.freeze({"teaql.trace_chain":t(i.traceChain),"teaql.trace_path":t(i.tracePath),"teaql.mutation_lineage":t(i.mutationLineage),"teaql.intent.comment":i.comment??i.auditReason??"","teaql.intent.purpose":i.purpose??"","teaql.sql.debug":i.debugSQL,"teaql.sql.log_mode":i.logMode,"teaql.sql.operation":i.operation,"teaql.sql.outcome":i.executionOutcome??"unknown","teaql.sql.elapsed_us":i.elapsedMicros,...i.resultCount===void 0?{}:{"teaql.sql.result_count":i.resultCount},...i.affectedRows===void 0?{}:{"teaql.sql.affected_rows":i.affectedRows}})})}function pe(i,e=!1){try{e?console.warn(i):console.info(i)}catch{}}class J extends Array{static get[Symbol.species](){return Array}constructor(e=[],t={}){typeof e=="number"?super(e):super(...e),Object.setPrototypeOf(this,J.prototype),this.totalCount=t.totalCount,this.aggregations=t.aggregations??{},this.summary=t.summary??{},this.facets=t.facets??{},this.isLoaded=t.isLoaded??!0}static empty(){return new J([],{isLoaded:!1})}get data(){return this}withTotalCount(e){return this.totalCount=e,this}withFacet(e,t){return this.facets[e]=t,this}facet(e){return this.facets[e]}totalCountOrLength(){return this.totalCount??this.length}}function Jt(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function $e(i){if(i&&typeof i=="object"){const e=i;return e.id??e.Id}return i}function Zt(i,e){const t=Jt(e);for(const n of[e,`${e}Id`,t,`${t}_id`]){const r=$e(i[n]);if(r!=null)return r}}function ei(i){const e=i.function.toLowerCase();return e==="count"||e==="sum"?0:null}function ti(i,e){return typeof i=="number"&&typeof e=="number"?i-e:i instanceof Date&&e instanceof Date?i.getTime()-e.getTime():String(i).localeCompare(String(e))}async function ii(i,e,t,n,r,o){const s=n.clone();s.facets=[],s.relations=[],s.relationAggregates=[],s.orderItems=[],s.aggregateItems=[],s.groupByItems=[],s.offsetValue=0,s.limitValue=0,s.selectItems=[...new Set([r,...o.map(u=>u.field)])],s.comment(`aggregate ${r}`),Q(n,s);const a=await i.executeQuery(t.deriveHelper(e(s),`aggregate ${r}`).query),c=new Map,l=new Map;for(const u of a){const f=Zt(u,r);if(f==null)continue;const g=String(f),h=c.get(g)??{},p=l.get(g)??{};for(const m of o){const y=m.function.toLowerCase(),d=u[m.field];if(y==="count")d!=null&&(h[m.alias]=Number(h[m.alias]??0)+1);else if(y==="sum"||y==="avg"){if(d!=null){const b=Number(d);if(!Number.isFinite(b))throw new Error(`Facet aggregate ${m.alias} requires numeric values`);h[m.alias]=Number(h[m.alias]??0)+b,y==="avg"&&(p[m.alias]=(p[m.alias]??0)+1)}}else if(y==="min"||y==="max"){if(d!=null){const b=h[m.alias],E=b==null?0:ti(d,b);(b==null||y==="min"&&E<0||y==="max"&&E>0)&&(h[m.alias]=d)}}else throw new Error(`Unsupported facet aggregate: ${m.function}`)}c.set(g,h),l.set(g,p)}for(const[u,f]of c){const g=l.get(u)??{};for(const h of o){if(h.function.toLowerCase()!=="avg")continue;const p=g[h.alias]??0;f[h.alias]=p?Number(f[h.alias]??0)/p:null}}return c}async function ot(i,e,t,n){const r=new L(t);t=r.query;const o={};for(const s of n){const a=r.deriveOperation(t,s.operation??{kind:"facet",relation:s.relationName,alias:s.facetName}),c=a.deriveChild(s.query.clone(),s.relationName),l=c.query,u=l.facets;l.facets=[];const f=l.aggregateItems.map(d=>({function:String(d.function),field:String(d.field),alias:String(d.alias)})),g=f.length?f:[{function:"Count",field:"id",alias:"__teaql_facet_membership_count"}];let h;if(i.executeFacetAggregates)h=await i.executeFacetAggregates(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName,g);else if(i.executeFacetMembership&&g.every(d=>d.function.toLowerCase()==="count")){const d=await i.executeFacetMembership(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName);h=new Map([...d].map(([b,E])=>[b,Object.fromEntries(g.map(S=>[S.alias,E]))]))}else h=await ii(i,e,a,t,s.relationName,g);l.aggregateItems=[],l.groupByItems=[];for(const d of l.relationAggregates){if(d.query.entity!==t.entity)continue;const b=t.clone();b.selectItems=["id"],b.properties=[],b.relations=[],b.relationAggregates=[],b.facets=[],b.aggregateItems=[],b.groupByItems=[],b.orderItems=[],b.offsetValue=0,b.limitValue=0;const E={id:{$inSubquery:{query:b,field:"id"}}};d.query.filterCondition=d.query.filterCondition?{$and:[d.query.filterCondition,E]}:E,Q(t,d.query)}if(!s.includeAllFacets){const d={id:{$in:[...h.keys()]}};l.filterCondition=l.filterCondition?{$and:[l.filterCondition,d]}:d}Q(t,l);const m=(await i.executeQuery(c.withQuery(e(l)).query)).map(d=>{const b=String($e(d.id??d.Id)),E=h.get(b),S={...d};for(const w of f)S[w.alias]=E?.[w.alias]??ei(w);return S}).filter(d=>s.includeAllFacets||h.has(String($e(d.id??d.Id)))),y=new J(m);u.length&&(y.facets=await ot(i,e,c.withQuery(l).query,u)),o[s.facetName]=y}return o}function ni(i){const e=new Map;for(const t of Object.values(i))for(const n of Object.values(t.relations||{})){if(!n.many)continue;const r=i[n.targetEntity],o=r?.columns[n.foreignKey]?.columnName,s=r?.columns.id?.columnName;if(!r||!o||!s)continue;const a=`idx_${r.table}_${o}_${s}`;let c=2166136261;for(let f=0;f>>0).toString(36),u=a.length<=30?a:`${a.slice(0,Math.max(1,29-l.length))}_${l}`;e.set(u,{name:u,table:r.table,foreignColumn:o,idColumn:s})}return[...e.values()]}async function ri(i,e,t,n){const r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ID space floor ${n} for ${t}`);for(let o=1;o<=100;o+=1){const s=await i.query(`SELECT current_level AS id FROM teaql_id_space WHERE type_name = ${e(1)}`,[t]);if(!s.rowCount){try{if((await i.query(`INSERT INTO teaql_id_space(type_name, current_level) VALUES (${e(1)}, ${e(2)})`,[t,r])).rowCount===1)return}catch(l){if(!(await i.query(`SELECT current_level FROM teaql_id_space WHERE type_name = ${e(1)}`,[t])).rowCount)throw l}continue}const a=Number(s.rows[0].id);if(a>=r)return;const c=await i.query(`UPDATE teaql_id_space SET current_level = ${e(1)} WHERE type_name = ${e(2)} AND current_level = ${e(3)}`,[r,t,a]);if(c.rowCount===1)return;if(c.rowCount!==0)throw new Error(`ID space floor update for ${t} changed ${c.rowCount} rows on attempt ${o}`)}throw new Error(`Unable to synchronize ID space floor for ${t} after 100 optimistic-lock attempts`)}function si(i,e){return i===e?!0:(i instanceof Date&&(i=i.getTime()),e instanceof Date&&(e=e.getTime()),i!=null&&e!==null&&e!==void 0&&String(i)===String(e))}function ie(i){return Object.freeze(i.map((e,t)=>Object.freeze({...e,level:t})))}function me(i,e,t,n,r,o){const s=i.traceFor({entity:String(e.entity),id:r}),a=be([...s,{kind:"entity",name:String(e.entity),entityId:r,detail:""}],t,n);return{auditReason:i.comment,tracePath:ie(a.tracePath),mutationLineage:s,targetID:r,inheritedBindings:R(o,i.graphSession?.logBindings)}}class oi{constructor(e=t=>console.debug(t)){this.writer=e}write(e){e=Je(e),this.writer(`[TeaQL SQL][${e.operation}][${e.elapsedMicros}us] ${e.resultSummary}${e.executionOutcome?` outcome=${e.executionOutcome}`:""} +comment=${e.comment??""} purpose=${e.purpose??""} auditReason=${e.auditReason??""} tracePath=${ye(e.tracePath)} traceChain=${ye(e.traceChain??[])} mutationLineage=${ye(e.mutationLineage??[])} +`+(e.omissionReason?`SQL omitted: ${e.omissionReason} +`:"")+`Debug SQL: ${e.debugSQL}`)}}function ye(i){return JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString():t)}class Si{constructor(){this.mode="all",this.entries=[]}record(e){const t=e.operation==="select";this.mode==="disabled"||this.mode==="select"&&!t||this.mode==="mutation"&&t||this.entries.push(Object.freeze({...e,...e.traceChain?{traceChain:_(e.traceChain)}:{},parameters:Object.freeze([...e.parameters])}))}setMode(e){return this.mode=e,this.entries=[],this}enableAll(){return this.setMode("all")}enableSelect(){return this.setMode("select")}enableMutation(){return this.setMode("mutation")}disable(){return this.setMode("disabled")}snapshot(){return[...this.entries]}}class ai{constructor(e,t){this.driver=e,this.bootstrapTail=Promise.resolve(),this.sqlTrace=[],this.internalQueryToken=Symbol("teaql-internal-query"),this.bindLogPolicies=new WeakMap,this.bindOperandSources=new WeakMap,this.derivedQueryBindings=new WeakMap,this.derivedRelationAssembly=new WeakMap,this.auditEvents=[],this.diagnosticSQLLogSink=new oi,this.queryLoggingEnabled=!0,this.mutationLoggingEnabled=!0,this.customTelemetry=!1,this.checkers={},this.userContext=new Ht,this.bootstrap={},this.graphAuditActions=[],this.graphCommitActions=[],this.graphRollbackActions=[],this.graphSaveTail=Promise.resolve(),this.schemas={...t}}fieldLogPolicy(e,t){const n=e.columns[t],r=n?.modelName??n?.columnName??t;return H(r)||H(t)?"credential":e.auditMaskFields?e.auditMaskFields?.includes(r)||e.auditMaskFields?.includes(t)?"masked":n?.logPolicy??"unknown":"unknown"}bindValue(e,t,n,r){const o=this.bindLogPolicies.get(e)??e.map(()=>"unknown");e.push(t),o.push(n),this.bindLogPolicies.set(e,o),r!==void 0&&this.bindOperandSources.set(e,R({parameterizedSQL:"",parameters:[r],parameterLogPolicies:[n],sqlOrigin:"generated"},this.bindOperandSources.get(e)))}queryLogBindings(e,t){return R({parameterizedSQL:e,parameters:t,parameterLogPolicies:this.bindLogPolicies.get(t),sqlOrigin:"generated"},this.bindOperandSources.get(t))}install(e){return Object.assign(this.schemas,e.schemas),Object.assign(this.checkers,e.checkers),this.bootstrap=nt(this.bootstrap,e.bootstrap),this}setUserContext(e){return this.userContext=e,this}schema(e){const t=this.schemas[e];if(!t)throw new Error(`Unknown TeaQL entity: ${e}`);return t}toRuntimeMutationRecord(e,t){const n={};for(const[r,o]of Object.entries(t)){const s=e.columns[r]?r:Object.keys(e.columns).find(a=>e.columns[a].modelName===r||e.columns[a].columnName===r);s&&(n[s]=o)}return n}encode(e,t){const n=e?.id??e;if(n!==void 0)return this.driver.encode(n,t)}decodeRow(e,t,n=[]){const r=this.schema(e),o={...t};for(const[s,a]of Object.entries(r.columns)){const c=o[s];c!=null&&(a.decode==="number"&&(o[s]=Number(c)),a.decode==="string"&&(o[s]=String(c)),a.decode==="date"&&c instanceof Date&&(o[s]=c.toISOString()),a.logicalType==="boolean"&&(o[s]=!!c))}for(const s of n)o[s]!==null&&o[s]!==void 0&&(o[s]=Number(o[s]));return o}get auditTrace(){return[...this.auditEvents]}setAuditSink(e){return this.auditSink=e,this}setRuntimeTelemetrySink(e){return this.telemetrySink=e,this}setDiagnosticSQLLogSink(e){return this.diagnosticSQLLogSink=e,this}setQueryLoggingEnabled(e){return this.queryLoggingEnabled=e,this}setMutationLoggingEnabled(e){return this.mutationLoggingEnabled=e,this}setRuntimeTelemetry(e){return this.customTelemetry=!0,this.runtimeTelemetry=e,this}attachStandardTelemetryStartup(e){this.telemetryStartup=e.then(async t=>{if(t){if(this.customTelemetry){await t.release();return}this.standardTelemetryHandle=t,this.runtimeTelemetry=t.telemetry}}).catch(()=>{pe("TeaQL telemetry: initialization failed; business continues without export.",!0)})}async flushTelemetry(){await this.telemetryStartup;try{await this.standardTelemetryHandle?.flush()}catch{pe("TeaQL telemetry: export flush failed; business outcome unchanged.",!0)}}async withQueryRequest(e,t){return new L(e),await this.telemetryStartup,F(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.request`,attributes:{"teaql.entity.type":String(e.entity)}},t)}recordSQL(e,t,n,r,o,s,a={},c="success",l,u){const g=e==="select"?this.queryLoggingEnabled:this.mutationLoggingEnabled,{targetID:h,inheritedBindings:p,...m}=a,y=Object.freeze({operation:e,...m,executionOutcome:c,traceChain:_(a.traceChain??[]),tracePath:ie(a.tracePath??[]),...a.traceChain?{traceChain:_(a.traceChain)}:{},...a.mutationLineage?{mutationLineage:_(a.mutationLineage)}:{},parameterizedSQL:t,parameters:Object.freeze([...n]),debugSQL:"",databaseKind:this.driver.databaseKind,sqlOrigin:"generated",parameterLogPolicies:Object.freeze([...this.bindLogPolicies.get(n)??n.map(()=>"unknown")]),elapsedMicros:Math.max(0,(Date.now()-r)*1e3),resultCount:o,affectedRows:s,resultSummary:o!==void 0?`${o} rows returned`:s!==void 0?`${s} rows affected`:`statement ${c}; row count unknown`}),d=p&&l?R(l,p):p??l,b=this.bindOperandSources.get(n),E=b?R(b,d):d;if(Ne(y,E,h===void 0?[]:[h]),this.runtimeTelemetry?.recordDiagnostic)try{this.runtimeTelemetry.recordsSQLDiagnostics?.()!==!1&&this.runtimeTelemetry.recordDiagnostic(Xt(Pt(y),u))}catch{pe("TeaQL telemetry: SQL diagnostic rejected; business outcome unchanged.",!0)}if(!this.telemetrySink&&!(g&&this.diagnosticSQLLogSink))return y;try{const S=Je(y);try{this.telemetrySink?.record(S)}catch{}if(g)try{this.diagnosticSQLLogSink?.write(S)}catch{}}catch{}return y}queryLogIntent(e){const t=new L(e),n=be(t.traceSource,this.driver.databaseKind,"select");return{comment:t.intent.comment,purpose:t.purpose,traceChain:t.traceChain,tracePath:ie(n.tracePath)}}async executeLoggedSQL(e,t,n,r,o,s,a){await this.telemetryStartup;const c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.${e}`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":e==="select"?"query":e}}),l=c.correlation?.(),u=Date.now();let f;try{f=await(c.run?c.run(o):o())}catch(h){try{const p=this.recordSQL(e,t,n,u,void 0,void 0,r,"failure",s,l);a?.push(p)}finally{throw c.failure(h),h}}const g=this.recordSQL(e,t,n,u,e==="select"?f.rowCount:void 0,e==="select"?void 0:f.rowCount,r,"success",s,l);return a?.push(g),c.success({attributes:{"teaql.result.cardinality":f.rowCount}}),f}async[Ge](e){await this.telemetryStartup,this.schemaReady||(this.schemaReady=this.driver.ensureSchema(this.schemas)),await this.schemaReady;const t=this.bootstrapTail;let n;this.bootstrapTail=new Promise(s=>{n=s}),await t,this.userContext=e;const r=e.getResource("bootstrapActor"),o=e.getResource("bootstrapCategory");e.insertResource("bootstrapActor","teaql-generated-bootstrap"),e.insertResource("bootstrapCategory","runtime-bootstrap");try{this.bootstrap.ensure?await this.bootstrap.ensure(e):await this.ensureBootstrapData()}finally{r===void 0?e.removeResource("bootstrapActor"):e.insertResource("bootstrapActor",r),o===void 0?e.removeResource("bootstrapCategory"):e.insertResource("bootstrapCategory",o),n()}}invalidateSchemaState(){this.schemaReady=void 0}async ensureBootstrapData(){const e=[...this.bootstrap.defaultDomainRoot?[this.bootstrap.defaultDomainRoot]:[],...this.bootstrap.constants??[]];e.length&&await this.executeGraphSave(new U("reconcile model bootstrap data"),async t=>{const n=this.graphMutationSession,r=[];for(const o of e){const s=await this.planBootstrapMutation(n,o);s&&r.push({record:o,request:t.request(s)})}for(const{request:o}of r)this.preflightMutation(o);for(const{request:o}of r)await this.executeMutation(o);for(const o of e)await this.driver.ensureIdFloor(n,o.entity,o.id)})}async planBootstrapMutation(e,t){const n=this.schema(t.entity),r=Object.entries(t.values??{}).map(([g,h])=>{const p=n.columns[g];if(!p)throw new Error(`Unknown bootstrap field ${t.entity}.${g}`);return{column:p.columnName,value:this.driver.encode(h,p)}}),o=new Yt(t.entity).filter({id:{$eq:t.id}}).limit(1).comment("inspect model bootstrap record").purpose("ensure model-defined root and constants");o.prepareForList();const s=new L(o),a=`SELECT * FROM ${this.driver.identifier(n.table)} WHERE ${this.driver.identifier(n.columns.id?.columnName??"id")} = ${this.driver.placeholder(1)}`,c=[t.id];this.bindLogPolicies.set(c,[this.fieldLogPolicy(n,"id")]);const l=await this.executeLoggedSQL("select",a,c,this.queryLogIntent(s.query),()=>e.query(a,c));if(!l.rowCount)return{entity:t.entity,action:"Create",id:t.id,version:0,payload:{...t.values}};const u=l.rows[0];if(r.filter(g=>!si(u[g.column],g.value)).length)return{entity:t.entity,action:"Update",id:t.id,version:Number(u[n.columns.version?.columnName??"version"]),payload:{...this.decodeRowForSchema(n,u),...t.values}}}async executeGraphSave(e,t){const n=new Mt(e);await this.telemetryStartup;const r=async()=>{const o=this.graphSaveTail;let s;this.graphSaveTail=new Promise(u=>{s=u}),await o;let a=!1,c=!1,l=!1;try{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],this.userContext.insertResource("fixTime",new Date),this.userContext.beginFixEvidence(),a=!0,this.userContext.beginMutationPolicyGraph(),c=!0;const u=await this.driver.transaction(async h=>{this.graphMutationSession=h,this.activeGraph=n;try{const p=await t(n);return this.userContext.ensureMutationPolicyGraphComplete(),p}finally{this.graphMutationSession=void 0,this.activeGraph=void 0}});l=!0;let f,g=!1;for(const h of[...this.graphCommitActions,...this.graphAuditActions])try{await h()}catch(p){g||(f=p),g=!0}if(g)throw new De(f);return u}catch(u){if(!l)for(const f of[...this.graphRollbackActions].reverse())try{f()}catch{}throw u}finally{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],c&&this.userContext.endMutationPolicyGraph(),this.userContext.removeResource("fixTime"),a&&this.userContext.finishFixEvidence(),s()}};return F(this.runtimeTelemetry,{family:"mutation",name:"graph.save",attributes:{"teaql.entity.type":"graph","teaql.mutation.kind":"graph"}},r)}afterGraphCommit(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphCommitActions.push(e)}afterGraphRollback(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphRollbackActions.push(e)}requireGraphOwnership(e){if(e.graphSession!==this.activeGraph||this.graphMutationSession!==void 0&&e.graphSession===void 0)throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability")}async withMutationSession(e,t){return this.requireGraphOwnership(e),e.graphSession?t(this.graphMutationSession):this.driver.transaction(t)}preflightMutation(e){const t=e instanceof j?e:new j(e);if(this.requireGraphOwnership(t),e=this.checkAndFixMutation(t),t.graphSession){const n=this.schema(e.entity);t.graphSession.captureLogBindings(this.mutationLogBindings(t,e,n))}return this.userContext.recordMutationPolicyPreflight(e),e}mutationLogBindings(e,t,n){const r=o=>{const s=this.toRuntimeMutationRecord(n,o),a=Object.keys(s);return{parameterizedSQL:"",sqlOrigin:"generated",parameters:a.map(c=>s[c]),parameterLogPolicies:a.map(c=>this.fieldLogPolicy(n,c))}};return R(r(t.payload||{}),r(e.loadedValues()))}checkAndFixMutation(e){const t=e instanceof j?e:new j(e);this.requireGraphOwnership(t),e=t.mutation,e={...e,payload:{...e?.payload??{}}},Object.defineProperty(e,"comment",{value:t.comment,enumerable:!0});const n=this.checkers[String(e.entity)];if(!n)return e;const r=[],o=this.userContext.getResource("fixTime")===void 0;o&&this.userContext.insertResource("fixTime",new Date).beginFixEvidence();try{if(n.checkAndFix(this.userContext,e,r),e.ledgerKey&&e.ledgerRoot)for(const[s,a]of Object.entries(e.payload||{}))e.ledgerRoot.set(e.ledgerKey,s,a);if(this.userContext.translateCheckResults(r),r.length)throw new dt(r);return e}finally{o&&this.userContext.removeResource("fixTime").finishFixEvidence()}}async executeMutation(e){await this.telemetryStartup;const t=e instanceof j?e:new j(e);this.requireGraphOwnership(t),e=t.mutation;const n=N(this.runtimeTelemetry,{family:"mutation",name:`${String(e?.entity||"unknown")}.${String(e?.action||"unknown").toLowerCase()}`,attributes:{"teaql.entity.type":String(e?.entity||"unknown"),"teaql.mutation.kind":String(e?.action||"unknown").toLowerCase()}}),r=async()=>{try{e=this.checkAndFixMutation(t);const o=this.userContext.enterMutationPolicy(e),s=this.schema(e.entity),a=this.toRuntimeMutationRecord(s,e.payload||{}),c=this.mutationLogBindings(t,e,s),l=this.driver.identifier(s.table),u=[],f=await F(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.mutation`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":String(e.action).toLowerCase()}},()=>this.withMutationSession(t,async y=>{if(e.action==="Create"){const d=e.id?String(e.id):await this.driver.nextId(y,e.entity);e.id&&await this.driver.ensureIdFloor(y,e.entity,d);const b=Number(e.version||0)+1,E={...a,id:d,version:b},S=Object.keys(s.columns).filter($=>E[$]!==void 0),w=S.map($=>this.driver.identifier(s.columns[$].columnName)).join(", "),v=S.map(($,T)=>this.driver.placeholder(T+1)).join(", "),I=S.map($=>this.encode(E[$],s.columns[$]));this.bindLogPolicies.set(I,S.map($=>this.fieldLogPolicy(s,$)));const O=`INSERT INTO ${l} (${w}) VALUES (${v})`,A=me(t,e,this.driver.databaseKind,"insert",d,c);return await this.executeLoggedSQL("insert",O,I,A,()=>y.query(O,I),void 0,u),{success:!0,id:d,version:b,persistedRecord:await this.readPersistedRecord(y,s,d,A,O,I,u)}}if(e.action==="Update"){const d=Object.keys(s.columns).filter($=>$!=="id"&&$!=="version"&&a[$]!==void 0),b=d.map($=>this.encode(a[$],s.columns[$]));this.bindLogPolicies.set(b,d.map($=>this.fieldLogPolicy(s,$)));const E=d.map(($,T)=>`${this.driver.identifier(s.columns[$].columnName)} = `+this.driver.placeholder(T+1)),S=this.driver.identifier("version");E.push(`${S} = ${S} + 1`),this.bindValue(b,String(e.id),this.fieldLogPolicy(s,"id"));const w=[`${this.driver.identifier("id")} = ${this.driver.placeholder(b.length)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),w.push(`${S} = ${this.driver.placeholder(b.length)}`));const v=`UPDATE ${l} SET ${E.join(", ")} WHERE ${w.join(" AND ")}`,I=me(t,e,this.driver.databaseKind,"update",String(e.id),c);if((await this.executeLoggedSQL("update",v,b,I,()=>y.query(v,b),void 0,u)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const A=await this.readPersistedRecord(y,s,String(e.id),I,v,b,u);return{success:!0,id:String(e.id),version:Number(A.version),persistedRecord:A}}if(e.action==="Delete"){const d=this.driver.identifier("version"),b=[String(e.id)];this.bindLogPolicies.set(b,[this.fieldLogPolicy(s,"id")]);const E=[`${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`];e.version!==void 0&&e.version!==null&&(this.bindValue(b,Number(e.version),this.fieldLogPolicy(s,"version")),E.push(`${this.driver.identifier("version")} = `+this.driver.placeholder(b.length)));const S=`UPDATE ${l} SET ${d} = -(${d} + 1) WHERE ${E.join(" AND ")}`,w=me(t,e,this.driver.databaseKind,"delete",String(e.id),c);if((await this.executeLoggedSQL("delete",S,b,w,()=>y.query(S,b),void 0,u)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const I=await this.readPersistedRecord(y,s,String(e.id),w,S,b,u);return{success:!0,id:String(e.id),version:Number(I.version),deleted:!0,persistedRecord:I}}throw new Error(`Unsupported mutation action: ${e.action}`)})),g=t.auditProjection({entity:String(e.entity),id:f.id},e.payload,c),h=Object.freeze({entity:e.entity,action:e.action,id:String(f.id),...g,recordedAt:new Date().toISOString(),actor:this.userContext.getResource("bootstrapActor"),category:this.userContext.getResource("bootstrapCategory"),changedFields:Object.freeze(Object.keys(e.payload||{}).sort()),version:f.version,mutationGovernance:o}),p=async()=>{this.auditEvents.push(h),this.auditSink&&await F(this.runtimeTelemetry,{family:"audit",name:`${e.entity}.audit`,attributes:{"teaql.entity.type":String(e.entity),"teaql.mutation.kind":String(e.action).toLowerCase(),"teaql.audit.changed_field_count":Object.keys(e.payload||{}).length}},async()=>this.auditSink(h))};if(t.graphSession)this.graphAuditActions.push(p);else try{await p()}catch(y){throw new De(y)}n.success();const m=Object.freeze({...u[0],statements:Object.freeze([...u])});return Ne(m,R(c,t.graphSession?.logBindings),[f.id]),{...f,metadata:m}}catch(o){throw n.failure(o),o}};return n.run?n.run(r):r()}async readPersistedRecord(e,t,n,r,o,s,a){const l=`SELECT ${Object.entries(t.columns).map(([S,w])=>`${this.driver.identifier(w.columnName)} AS ${this.driver.identifier(S)}`).join(", ")} FROM ${this.driver.identifier(t.table)} WHERE ${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`,u=[n];this.bindLogPolicies.set(u,[this.fieldLogPolicy(t,"id")]);const f=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.readback`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}}),g=Date.now();let h;const p={parameterizedSQL:o,parameters:s,parameterLogPolicies:this.bindLogPolicies.get(s),sqlOrigin:"generated"},m=r.tracePath?.find(S=>S.kind==="operation")?.name??"unknown",y=be([...He(m,r.auditReason,"verify persisted mutation result"),...(r.tracePath??[]).filter(S=>S.kind==="relation")],this.driver.databaseKind,"select"),d={...r,tracePath:ie(y.tracePath),comment:r.auditReason,purpose:"verify persisted mutation result"},b=S=>a.push(this.recordSQL("select",l,u,g,h?.rowCount,void 0,d,S,p,f.correlation?.()));let E;try{if(h=await(f.run?f.run(()=>e.query(l,u)):e.query(l,u)),f.success({attributes:{"teaql.result.cardinality":h.rowCount}}),h.rowCount!==1)throw new Error(`Persisted ${t.table}(${n}) could not be read back`);E=this.decodeRowForSchema(t,h.rows[0])}catch(S){h||f.failure(S);const w=h?"success":S instanceof Error&&(S.name==="AbortError"||S.name==="TimeoutError")?"cancelled":"failure";try{b(w)}finally{throw S}}return b("success"),E}decodeRowForSchema(e,t){const n={...t};for(const[r,o]of Object.entries(e.columns)){const s=n[r];s!=null&&(o.decode==="number"&&(n[r]=Number(s)),o.decode==="string"&&(n[r]=String(s)),o.decode==="date"&&s instanceof Date&&(n[r]=s.toISOString()),o.logicalType==="boolean"&&(n[r]=!!s))}return n}compileExpression(e,t,n){if(Array.isArray(e?.$and))return`(${e.$and.map(s=>this.compileExpression(s,t,n)).join(" AND ")})`;const r=Object.entries(e||{}).map(([o,s])=>{const a=t.columns[o];if(!a)throw new Error(`Unknown field ${o} for SQL query`);const c=this.driver.identifier(a.columnName),l=this.fieldLogPolicy(t,o);if(s?.$eq!==void 0){const u=s.$eq?.id??s.$eq;return u===null?`${c} IS NULL`:(this.bindValue(n,this.encode(u,a),l),`${c} = ${this.driver.placeholder(n.length)}`)}if(s?.$ne!==void 0){const u=s.$ne?.id??s.$ne;return u===null?`${c} IS NOT NULL`:(this.bindValue(n,this.encode(u,a),l),`${c} <> ${this.driver.placeholder(n.length)}`)}if(s?.$soundLike!==void 0)return this.bindValue(n,String(s.$soundLike),l),`SOUNDEX(${c}) = SOUNDEX(${this.driver.placeholder(n.length)})`;if(s?.$contains!==void 0)return this.bindValue(n,String(s.$contains),l),this.driver.contains(c,this.driver.placeholder(n.length));if(s?.$notContains!==void 0)return this.bindValue(n,String(s.$notContains),l),`NOT (${this.driver.contains(c,this.driver.placeholder(n.length))})`;for(const[u,f,g,h]of[["$startsWith","","%",!1],["$notStartsWith","","%",!0],["$endsWith","%","",!1],["$notEndsWith","%","",!0]])if(s?.[u]!==void 0){const p=String(s[u]);this.bindValue(n,`${f}${p}${g}`,l,p);const m=`${c} LIKE ${this.driver.placeholder(n.length)}`;return h?`NOT (${m})`:m}if(Array.isArray(s?.$in)){if(!s.$in.length)return"FALSE";const u=s.$in.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),l),this.driver.placeholder(n.length)));return`${c} IN (${u.join(", ")})`}if(Array.isArray(s?.$notIn)){if(!s.$notIn.length)return"TRUE";const u=s.$notIn.map(f=>(this.bindValue(n,this.encode(f?.id??f,a),l),this.driver.placeholder(n.length)));return`${c} NOT IN (${u.join(", ")})`}for(const[u,f]of[["$inSubquery",!1],["$notInSubquery",!0]]){const g=s?.[u];if(g!==void 0){const h=g.query,p=this.schema(h?.entity),m=String(g.field),y=p.columns[m];if(!y)throw new Error(`Unknown subquery projection ${m} for ${h?.entity}`);const d=this.filters(h).map(S=>this.compileExpression(S,p,n));p.columns.version&&d.push(`${this.driver.identifier(p.columns.version.columnName)} > 0`),f&&d.push(`${this.driver.identifier(y.columnName)} IS NOT NULL`);const b=d.length?` WHERE ${d.join(" AND ")}`:"",E=`SELECT ${this.driver.identifier(y.columnName)} FROM ${this.driver.identifier(p.table)}${b}`;return`${c} ${f?"NOT IN":"IN"} (${E})`}}if(Array.isArray(s?.$between)&&s.$between.length===2){this.bindValue(n,this.encode(s.$between[0],a),l);const u=this.driver.placeholder(n.length);this.bindValue(n,this.encode(s.$between[1],a),l);const f=this.driver.placeholder(n.length);return`${c} BETWEEN ${u} AND ${f}`}if(s?.$isNull===!0)return`${c} IS NULL`;if(s?.$isNull===!1)return`${c} IS NOT NULL`;if(s?.$gte!==void 0)return this.bindValue(n,this.encode(s.$gte,a),l),`${c} >= ${this.driver.placeholder(n.length)}`;if(s?.$lte!==void 0)return this.bindValue(n,this.encode(s.$lte,a),l),`${c} <= ${this.driver.placeholder(n.length)}`;if(s?.$gt!==void 0)return this.bindValue(n,this.encode(s.$gt,a),l),`${c} > ${this.driver.placeholder(n.length)}`;if(s?.$lt!==void 0)return this.bindValue(n,this.encode(s.$lt,a),l),`${c} < ${this.driver.placeholder(n.length)}`;throw new Error(`Unsupported query predicate for ${o}: ${JSON.stringify(s)}`)});return r.length?`(${r.join(" AND ")})`:"TRUE"}filters(e){return Array.isArray(e._filters)&&e._filters.length?e._filters:e.filterCondition?[e.filterCondition]:[]}groupBy(e){return e._groupBy||e.groupByItems||[]}aggregates(e){return Array.isArray(e._aggregates)?e._aggregates:(e.aggregateItems||[]).map(t=>({func:t.function,field:t.field,retName:t.alias}))}orders(e){return Array.isArray(e._orderBy)?e._orderBy.map(t=>({field:t.f,direction:t.d})):(e.orderItems||[]).map(t=>({field:t.field,direction:t.direction}))}async compileQuery(e,t=!0,n=[]){new ae(e?.commentText??e?._comment,e?.purposeText??e?._purpose);const r=this.schema(e.entity),o=[],s=this.groupBy(e),a=s.map(w=>{if(!r.columns[w])throw new Error(`Unknown group field: ${w}`);return this.driver.identifier(r.columns[w].columnName)}),c=s.map(w=>`${this.driver.identifier(r.columns[w].columnName)} AS `+this.driver.identifier(w)),l=[],u=Array.isArray(e.selectItems)&&e.selectItems.length?[...new Set(["id","version",...e.selectItems])]:Object.keys(r.columns);if(!s.length&&!this.aggregates(e).length){for(const v of n)u.includes(v)||u.push(v);const w=[...(e.relations??[]).map(v=>v.name),...(e.relationAggregates??[]).map(v=>v.relationName)];for(const v of w){const I=r.relations?.[v];if(!I)throw new Error(`Missing relation ${e.entity}.${v}`);u.includes(I.localKey)||u.push(I.localKey)}}for(const w of u)if(!r.columns[w])throw new Error(`Unknown selected field: ${w}`);let f=u.map(w=>{const v=r.columns[w];return`${this.driver.identifier(v.columnName)} AS ${this.driver.identifier(w)}`}).join(", ");const g=this.aggregates(e);if(g.length){const w=g.map(v=>{if(!r.columns[v.field])throw new Error(`Unknown aggregate field: ${v.field}`);return l.push(v.retName),`${this.driver.aggregateFunction(v.func)}(${this.driver.identifier(r.columns[v.field].columnName)}) AS `+this.driver.identifier(v.retName)});f=[...c,...w].join(", ")}const h=e.__teaqlPartitionBy,p=this.orders(e),m=p.map(w=>{if(!r.columns[w.field])throw new Error(`Unknown order field: ${w.field}`);const v=String(w.direction).toLowerCase()==="desc"?"DESC":"ASC";return`${this.driver.identifier(r.columns[w.field].columnName)} ${v}`});if(h){const w=r.columns[h];if(!w)throw new Error(`Unknown partition field: ${h}`);const v=m.length?` ORDER BY ${m.join(", ")}`:"";f+=`, ROW_NUMBER() OVER (PARTITION BY ${this.driver.identifier(w.columnName)}${v}) AS `+this.driver.identifier("__teaql_partition_rank")}let y=`SELECT ${f} FROM ${this.driver.identifier(r.table)}`;const b=this.filters(e).map(w=>this.compileExpression(w,r,o));r.columns.version&&b.push(`${this.driver.identifier(r.columns.version.columnName)} > 0`),b.length&&(y+=` WHERE ${b.join(" AND ")}`),a.length&&(y+=` GROUP BY ${a.join(", ")}`);const E=e._limit!==void 0?Number(e._limit):Number(e.limitValue||0),S=e._offset!==void 0?Number(e._offset):Number(e.offsetValue||0);if(h){const w=this.driver.identifier("__teaql_partition_rank"),v=[];this.bindValue(o,S,"plain"),v.push(`${w} > ${this.driver.placeholder(o.length)}`),E>0&&(this.bindValue(o,S+E,"plain"),v.push(`${w} <= ${this.driver.placeholder(o.length)}`)),y=`SELECT * FROM (${y}) AS ${this.driver.identifier("__teaql_partitioned")} WHERE ${v.join(" AND ")} ORDER BY ${w}`}else p.length&&(y+=` ORDER BY ${m.join(", ")}`);return!h&&E>0&&(this.bindValue(o,E,"plain"),y+=` LIMIT ${this.driver.placeholder(o.length)}`),!h&&S>0&&(this.bindValue(o,S,"plain"),y+=` OFFSET ${this.driver.placeholder(o.length)}`),t&&this.sqlTrace.push(y),{sql:y,values:o,aggregateNames:l}}async executeQuery(e){const t=e instanceof L?e:new L(e);return!(e instanceof L)&&e?.[this.internalQueryToken]!==!0&&typeof e?.prepareForList=="function"&&e.prepareForList(),this.executeQueryWithIntent(t.query,this.derivedQueryBindings.get(e),this.derivedRelationAssembly.get(e))}async executeDerivedQuery(e,t,n,r){const o=new L(e,n).query;t&&this.derivedQueryBindings.set(o,t),r&&this.derivedRelationAssembly.set(o,r);try{return await this.executeQuery(o)}finally{this.derivedQueryBindings.delete(o),this.derivedRelationAssembly.delete(o)}}descendantBindings(e,t,n,r){if(!(!e.relations?.length&&!e.relationAggregates?.length))return R(this.queryLogBindings(t,n),r)}async queryTreeBindings(e,t,n,r){let o=R(this.queryLogBindings(t,n),r);const s=new L(e).intent,a=[e],c=new Set;for(;a.length;){const l=a.pop();if(!l||c.has(l))continue;if(c.add(l),l!==e){const f=await this.compileQuery(new L(l,s).query,!1);o=R(this.queryLogBindings(f.sql,f.values),o)}const u=Nt(l);u&&a.push(u);for(const f of[...l.relations??[],...l.relationAggregates??[]])f.query&&a.push(f.query);for(const f of l.facets??[]){if(!f.query)continue;const g=f.query.clone();g.aggregateItems=[],g.groupByItems=[],a.push(g)}}return o}async executeQueryWithIntent(e,t,n){await this.telemetryStartup;const r=N(this.runtimeTelemetry,{family:"query",name:`${String(e?.entity||"unknown")}.list`,attributes:{"teaql.entity.type":String(e?.entity||"unknown")}}),o=async()=>{try{const s=e?.[this.internalQueryToken]===!0;if(!s){if(typeof e?.prepareForList!="function")throw new Error("TeaQL list execution requires the formal runtime SelectQuery");e.prepareForList()}const a=s?{query:e,execution:void 0}:await this.prepareIdSetPage(e,t),c=s?a:await this.prepareContinuousPage(a.query);e=new L(e).withQuery(c.query).query;const{sql:l,values:u,aggregateNames:f}=await this.compileQuery(e,!0,n?[n.field]:[]);t=await this.queryTreeBindings(e,l,u,t);const h=(await this.executeLoggedSQL("select",l,u,this.queryLogIntent(e),()=>this.driver.query(l,u),t)).rows.map(m=>this.decodeRow(e.entity,m,f));if(a.execution?.pageIds){const m=new Map(a.execution.pageIds.map((y,d)=>[String(y),d]));h.sort((y,d)=>(m.get(String(y.id))??Number.MAX_SAFE_INTEGER)-(m.get(String(d.id))??Number.MAX_SAFE_INTEGER))}const p=this.descendantBindings(e,l,u,t);if(n)for(const m of h)n.keys.set(m,m[n.field]);if(await this.enhanceQueryRows(h,e,p),n&&Array.isArray(e.selectItems)&&e.selectItems.length&&!["id","version",...e.selectItems,...this.groupBy(e)].includes(n.field)){const m=this.schema(e.entity);if(![...(e.relations??[]).map(d=>d.name),...(e.relationAggregates??[]).map(d=>d.relationName)].some(d=>m.relations?.[d]?.localKey===n.field))for(const d of h)delete d[n.field]}return s||await this.registerContinuousPage(e,c.execution,h),r.success({attributes:{"teaql.result.cardinality":h.length}}),h}catch(s){throw r.failure(s),s}};return r.run?r.run(o):o()}async prepareIdSetPage(e,t){const n=e.localIdSetPaginationOptions?.(),r=e.localIdSetPaginationRuntime?.();if(!n||!r)return r?.observe("ID_SET_DISABLED"),{query:e};const o=this.queryLimit(e);if(!o||e.localContinuousPageOptions?.()||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return r.observe("ID_SET_FALLBACK_UNSUPPORTED_SHAPE"),{query:e};if((e.orderItems||[]).some(m=>m.expr!=null))return r.observe("ID_SET_FALLBACK_NON_DETERMINISTIC_ORDER"),{query:e};this.orders(e).some(m=>m.field==="id")||(e=e.clone().order(q.asc("id")));const s=e.clone();s.offsetValue=0,s.limitValue=0,s.selectItems=[],s.relations=[],s.commentText=void 0,s.purposeText=void 0,s.clearIdSetPaginationRuntime(),s.clearContinuousPageRuntime();const a=`${n.namespace}|${r.scope}|${JSON.stringify(s)}`;let c=2166136261;for(let m=0;m>>0).toString(16)}`;let u,f=!1;try{u=r.get(l)}catch{return r.observe("ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(u)f=!0,r.observe("ID_SET_HIT",u.ids.length);else{let m;try{m=await r.build(l,async()=>{const y=r.get(l);if(y)return y;const d=e.clone();d.selectItems=["id"],d.relations=[],d.relationAggregates=[],d.facets=[],d.offsetValue=0,d.limitValue=n.maxIds+1,d.clearIdSetPaginationRuntime(),d.clearContinuousPageRuntime(),d[this.internalQueryToken]=!0;const b=new L(e).deriveHelper(d,`collect ${e.entity} IDs for pagination`),E=await this.compileQuery(e,!1),S=await this.queryTreeBindings(e,E.sql,E.values,t),w=await this.executeDerivedQuery(b.query,S,b.intent);if(w.length>n.maxIds)return;let v;try{v=BigUint64Array.from(w.map(O=>BigInt(O.id)))}catch{throw new Error("ID_SET_UNSUPPORTED_ID")}const I={ids:v,expiresAt:Date.now()+n.ttlSeconds*1e3};return r.put(l,I),I})}catch(y){return r.observe(y instanceof Error&&y.message==="ID_SET_UNSUPPORTED_ID"?"ID_SET_FALLBACK_UNSUPPORTED_SHAPE":"ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(u=m.value,!u)return r.observe("ID_SET_FALLBACK_LIMIT_EXCEEDED",n.maxIds+1),{query:e};f=!m.built,r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",u.ids.length)}const g=Number(e.offsetValue||e._offset||0),h=Array.from(u.ids.slice(g,g+o)),p=e.clone();return p.offsetValue=0,p.limitValue=Math.max(h.length,1),p.filterCondition=p.filterCondition?{$and:[p.filterCondition,{id:{$in:h}}]}:{id:{$in:h}},p.clearIdSetPaginationRuntime(),r.observe(f?"ID_SET_HIT":"ID_SET_BUILD",u.ids.length),{query:p,execution:{pageIds:h,totalCount:u.ids.length}}}async executeFacetMembership(e,t,n=[]){const r=await this.executeFacetAggregates(e,t,[{function:"Count",field:"id",alias:"__teaql_facet_count"}]);return new Map([...r].map(([o,s])=>[o,Number(s.__teaql_facet_count??0)]))}async executeFacetAggregates(e,t,n){const r=new L(e);e=r.query;const o=r.withQuery(e.clone()).query;Q(e,o),o.facets=[],o.relations=[],o.relationAggregates=[],o.orderItems=[],o.offsetValue=0,o.limitValue=0,o.selectItems=[],o.groupByItems=[t],o.aggregateItems=n.map(a=>({...a})),o[this.internalQueryToken]=!0;const s=await this.executeQuery(o);return new Map(s.flatMap(a=>{const c=a[t];if(c==null)return[];const l={};for(const u of n)l[u.alias]=a[u.alias];return[[String(c),l]]}))}async executeCount(e,t,n){const r=e instanceof L?e:new L(e);if(e=r.query,typeof e?.forExactCount!="function")throw new Error("TeaQL exact count requires the formal runtime SelectQuery");const o=t??"__teaql_total",s=r.deriveOperation(e.forExactCount(o),n??{kind:"named-count",...t!==void 0?{alias:t}:{}}),c=(await this.executeQuery(s.query))[0]?.[o];if(typeof c!="number"||!Number.isFinite(c))throw new Error(`TeaQL provider did not return exact count alias ${o}`);return c}async prepareContinuousPage(e){const t=e.localContinuousPageOptions?.(),n=e.localContinuousPageRuntime?.();if(!t||!n)return n?.observe("DISABLED"),{query:e};const r=this.orders(e),o=this.queryLimit(e);if(!o||r.length!==1||r[0].field!=="id"||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return n.observe("OFFSET_FALLBACK:UNSUPPORTED_QUERY_SHAPE"),{query:e};const s=Object.assign(Object.create(Object.getPrototypeOf(e)),e);s.orderItems=[...e.orderItems||[]],s.relations=[...e.relations||[]],Object.defineProperty(s,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:t}),Object.defineProperty(s,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:n});const a=Number(e.offsetValue||e._offset||0),c={...JSON.parse(JSON.stringify(s)),offsetValue:0,_offset:0,commentText:void 0,purposeText:void 0},l=`${t.namespace}|${n.owner}|${JSON.stringify(c)}`;let u=2166136261;for(let m=0;m>>0).toString(16)}`,g={queryKey:f,offset:a,limit:o,direction:String(r[0].direction).toLowerCase(),ttlSeconds:t.ttlSeconds,runtime:n,optimized:!1};if(a===0)return n.observe("OFFSET_FALLBACK:FIRST_PAGE"),{query:s,execution:g};let h;try{h=await F(this.runtimeTelemetry,{family:"cache",name:"continuous_page.get",attributes:{"teaql.cache.operation":"get"}},()=>n.get(f,a))}catch{return n.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE"),{query:s,execution:g}}if(!h)return n.observe("OFFSET_FALLBACK:CACHE_MISS"),{query:s,execution:g};const p={id:{[g.direction==="desc"?"$lt":"$gt"]:h.boundary}};return s.filterCondition=s.filterCondition?{$and:[s.filterCondition,p]}:p,s.offsetValue=0,s._offset!==void 0&&(s._offset=0),g.optimized=!0,g.cursorId=h.cursorId,n.observe("CURSOR_SEEK",h.cursorId),{query:s,execution:g}}async registerContinuousPage(e,t,n){if(!(!t||n.length!==t.limit||!n.length||n[n.length-1].id===void 0)){try{await F(this.runtimeTelemetry,{family:"cache",name:"continuous_page.put",attributes:{"teaql.cache.operation":"put"}},()=>t.runtime.put(t.queryKey,t.offset+n.length,{cursorId:`cpg_${Date.now().toString(16)}_${Math.random().toString(16).slice(2)}`,boundary:n[n.length-1].id,expiresAt:Date.now()+t.ttlSeconds*1e3}))}catch{t.runtime.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE");return}t.optimized&&t.runtime.observe("CURSOR_SEEK",t.cursorId)}}executeForStream(e,t=1e3){try{const n=e instanceof L?new L(e.query,e.intent):new L(e);return this.executeCapturedStream(n.query,t)}catch(n){return(async function*(){throw n})()}}async*executeCapturedStream(e,t){if(await this.telemetryStartup,!Number.isInteger(t)||t<=0)throw new Error("stream chunk size must be a positive integer");if(Array.isArray(e.facets)&&e.facets.length>0)throw new Error("QRY-F01_STREAM_UNSUPPORTED: execute facets with executeForList");const{sql:n,values:r,aggregateNames:o}=await this.compileQuery(e),s=await this.queryTreeBindings(e,n,r),a=N(this.runtimeTelemetry,{family:"query",name:`${String(e.entity)}.stream`,attributes:{"teaql.entity.type":String(e.entity)}});let c;const l=async()=>{c=N(this.runtimeTelemetry,{family:"provider",name:`${this.driver.databaseKind}.stream`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}})};await(a.run?a.run(l):l());const u=c.correlation?.(),f=this.driver.stream(n,r)[Symbol.asyncIterator](),g=Date.now();let h="cancelled",p=0,m=[];const y=this.descendantBindings(e,n,r,s);try{for(;;){const d=await(c.run?c.run(()=>f.next()):f.next());if(d.done)break;m.push(this.decodeRow(e.entity,d.value,o)),m.length===t&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m,m=[])}m.length&&(await this.enhanceQueryRows(m,e,y),p+=m.length,yield m),h="success"}catch(d){throw h="failure",c.failure(d),a.failure(d),d}finally{try{await f.return?.()}catch(d){if(h!=="failure")throw h="failure",c.failure(d),a.failure(d),d}finally{if(h==="failure")try{this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,u)}catch{}else this.recordSQL("select",n,r,g,p,void 0,this.queryLogIntent(e),h,s,u),c.success({attributes:{"teaql.result.cardinality":p}}),a.success({attributes:{"teaql.result.cardinality":p}})}}}async enhanceQueryRows(e,t,n){if(!e.length)return;const r=[...(t.relations??[]).map(a=>a.name),...(t.relationAggregates??[]).map(a=>a.relationName)];if(!r.length)return;const o=this.schema(t.entity),s=new Map;for(const a of r){const c=o.relations?.[a];if(!c)throw new Error(`Missing relation ${t.entity}.${a}`);s.has(c.localKey)||s.set(c.localKey,e.map(l=>l[c.localKey]))}await this.enhanceRelationAggregates(e,t,s,n),await this.enhanceRelations(e,t,s,n)}async enhanceRelations(e,t,n,r){if(!e.length||!Array.isArray(t.relations)||!t.relations.length)return;const o=this.schema(t.entity),s=new L(t).intent;for(const a of t.relations){const c=o.relations?.[a.name];if(!c)throw new Error(`Missing relation ${t.entity}.${a.name}`);const l=n.get(c.localKey),u=l.filter(S=>S!=null),f=a.query?this.queryLimit(a.query):void 0,g=a.query?.localTopNProbeParentThreshold?.(),h=c.many&&f!==void 0,p=Array.isArray(a.query?.selectItems)?a.query.selectItems:[],m=p.length>0&&!p.includes(c.foreignKey),y=this.driver.topNRelationPlanPolicy==="alwaysProbe",d=h&&(g===void 0?y:g>0&&u.length<=g),b=d?"bounded_probes":"window",E=N(this.runtimeTelemetry,{family:"relation_load",name:`${t.entity}.${String(a.name)}`,attributes:{"teaql.entity.type":String(t.entity),"teaql.relation.name":String(a.name),"teaql.relation.parent_count":u.length,"teaql.relation.per_parent_limit":f??0,"teaql.relation.configured_probe_threshold":g??"provider-default","teaql.relation.selected_plan":b,"teaql.relation.probe_count":d?u.length:0}});try{if(!u.length&&!(c.many&&a.query?.facets?.length)){for(const O of e)O[a.name]=c.many?[]:null;E.success({attributes:{"teaql.result.cardinality":0}});continue}const S={...a.query||{},entity:c.targetEntity,selectItems:m?[...p,c.foreignKey]:p,_filters:[...this.filters(a.query||{})],relations:[...a.query?.relations||[]],orderItems:[...a.query?.orderItems||[]],__teaqlPartitionBy:h&&!d?c.foreignKey:void 0};if(h){const O=this.groupBy(S),A=O.length||this.aggregates(S).length?O:["id"];for(const $ of A)S.orderItems.some(T=>T.field===$)||S.orderItems.push(q.asc($))}typeof S.clearContinuousPageRuntime=="function"&&S.clearContinuousPageRuntime(),S[this.internalQueryToken]=!0;const w=[],v={field:c.foreignKey,keys:new WeakMap};if(d)for(const O of u){const A={...S,_filters:[...S._filters,{[c.foreignKey]:{$eq:O}}],__teaqlPartitionBy:void 0};w.push(...await this.executeDerivedQuery(new L(t).derive(A,a.name,a.operation).query,r,s,v))}else S._filters.push({[c.foreignKey]:{$in:u}}),w.push(...await this.executeDerivedQuery(new L(t).derive(S,a.name,a.operation).query,r,s,v));for(const O of w)delete O.__teaql_partition_rank;const I=new Map;for(const O of w){if(!v.keys.has(O))throw new Error("Relation assembly lost its captured row identity");const A=v.keys.get(O),$=I.get(A)||[];$.push(O),I.set(A,$)}if(m)for(const O of w)delete O[c.foreignKey];for(const[O,A]of e.entries()){const $=I.get(l[O])||[];if(c.many&&a.query?.facets?.length){const T=a.query.clone();T.entity=c.targetEntity;const he=l[O],Ae={[c.foreignKey]:he==null?{$in:[]}:{$eq:he}};T.filterCondition=T.filterCondition?{$and:[T.filterCondition,Ae]}:Ae,Q(t,T);const ct=new L(t).derive(T,a.name,a.operation).query;A[a.name]=new J($,{facets:await ot(this,lt=>lt,ct,T.facets)})}else{const T=l[O];A[a.name]=c.many?$:$[0]??(T==null?null:{[c.foreignKey]:T})}}E.success({attributes:{"teaql.result.cardinality":w.length}})}catch(S){throw E.failure(S),S}}}async enhanceRelationAggregates(e,t,n,r){const o=t.relationAggregates;if(!e.length||!Array.isArray(o)||!o.length)return;const s=this.schema(t.entity),a=new L(t).intent;for(const c of o){const l=s.relations?.[c.relationName];if(!l)throw new Error(`Missing relation ${t.entity}.${c.relationName}`);const u=n.get(l.localKey),f=u.filter(y=>y!=null);if(!f.length){for(const y of e)y[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{};continue}const g=c.query.clone();g.entity=l.targetEntity,g.selectItems=[],g.properties=[],g.orderItems=[],g.limitValue=0,g.offsetValue=0,g.relations=[],g.relationAggregates=[],g.aggregateItems.length||g.aggregate("Count","id",c.alias),g.groupByItems.includes(l.foreignKey)||g.groupBy(l.foreignKey);const h={[l.foreignKey]:{$in:f}};g.filterCondition=g.filterCondition?{$and:[g.filterCondition,h]}:h,g[this.internalQueryToken]=!0;const p=await this.executeDerivedQuery(new L(t).deriveAggregate(g,c.relationName,c.operation??{kind:"relation-count",relation:c.relationName,alias:c.alias}).query,r,a),m=new Map;for(const y of p)m.set(y[l.foreignKey],y);for(const[y,d]of e.entries()){const b=m.get(u[y]);b?c.singleResult?d[c.alias]=b[g.aggregateItems[0].alias]??null:d[c.alias]=Object.fromEntries(Object.entries(b).filter(([E])=>E!==l.foreignKey)):d[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{}}}}emptyAggregateValue(e){const t=e.aggregateItems[0];return!t||String(t.function).toLowerCase()==="count"?0:null}queryLimit(e){if(e._limit!==void 0)return Number(e._limit);if(e.limitValue!==void 0&&Number(e.limitValue)>0)return Number(e.limitValue)}async close(){try{await this.driver.close()}finally{await this.telemetryStartup,await this.standardTelemetryHandle?.release(),this.standardTelemetryHandle=void 0}}}function ci(i){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))throw new Error(`Unsafe SQL identifier: ${i}`);return i}function li(i){const t={count:"COUNT",sum:"SUM",avg:"AVG",min:"MIN",max:"MAX"}[String(i).toLowerCase()];if(!t)throw new Error(`Unsupported aggregate: ${i}`);return t}class ui{constructor(e){this.worker=e,this.nextRequestId=1,this.pending=new Map,this.closed=!1,this.onMessage=t=>{const n=t.data;if(!n||n.type!=="teaql-browser-sqlite-response")return;const r=this.pending.get(n.requestId);if(r)if(this.pending.delete(n.requestId),n.error){const o=new Error(n.error.message);o.name=n.error.name,n.error.code&&(o.code=n.error.code),r.reject(o)}else r.resolve(n.result)},this.onError=t=>{const n=new Error(t.message||"Browser SQLite worker failed");n.name="BrowserSQLiteWorkerError";for(const r of this.pending.values())r.reject(n);this.pending.clear()},e.addEventListener("message",this.onMessage),e.addEventListener("error",this.onError)}request(e,t){if(this.closed)return Promise.reject(new Error("Browser SQLite worker is closed"));const n=this.nextRequestId++;return new Promise((r,o)=>{this.pending.set(n,{resolve:s=>r(s),reject:o}),this.worker.postMessage({type:"teaql-browser-sqlite-request",requestId:n,operation:e,payload:t})})}async close(e){if(!this.closed)try{await this.request("close")}finally{this.closed=!0,this.worker.removeEventListener("message",this.onMessage),this.worker.removeEventListener("error",this.onError),e&&this.worker.terminate?.();const t=new Error("Browser SQLite worker is closed");for(const n of this.pending.values())n.reject(t);this.pending.clear()}}}class hi{constructor(e){this.transport=e}query(e,t=[]){return this.transport.request("query",{sql:e,values:t})}}class Te{constructor(e,t){this.transport=e,this.options=t,this.databaseKind="sqlite",this.accessTail=Promise.resolve()}static async open(e,t={}){const n={storage:t.storage??"memory",databaseName:fi(t.databaseName??"teaql-browser.sqlite3"),terminateWorkerOnClose:t.terminateWorkerOnClose??!0},r=new ui(e);return await r.request("open",n),new Te(r,n)}identifier(e){return`"${ci(e)}"`}placeholder(e){return"?"}contains(e,t){return`CAST(${e} AS TEXT) LIKE '%' || ${t} || '%'`}aggregateFunction(e){return li(e)}encode(e,t){return e==null?e:t?.logicalType==="json"&&typeof e!="string"?JSON.stringify(e):t?.logicalType==="boolean"?e?1:0:e instanceof Date?e.toISOString():e}async exclusive(e){const t=this.accessTail;let n;this.accessTail=new Promise(r=>{n=r}),await t;try{return await e()}finally{n()}}query(e,t=[]){return this.exclusive(()=>this.transport.request("query",{sql:e,values:t}))}async*stream(e,t=[]){const n=await this.query(e,t);for(const r of n.rows)yield r}transaction(e){return this.exclusive(async()=>{const t=new hi(this.transport);await t.query("BEGIN IMMEDIATE");try{const n=await e(t);return await t.query("COMMIT"),n}catch(n){try{await t.query("ROLLBACK")}catch{}throw n}})}async ensureSchema(e){for(const t of Object.values(e)){const n=this.identifier(t.table);await this.query(`CREATE TABLE IF NOT EXISTS ${n} ("id" INTEGER PRIMARY KEY, "version" INTEGER NOT NULL)`);const r=await this.query(`PRAGMA table_info(${n})`),o=new Set(r.rows.map(s=>String(s.name)));for(const[s,a]of Object.entries(t.columns))s==="id"||s==="version"||o.has(a.columnName)||await this.query(`ALTER TABLE ${n} ADD COLUMN ${this.identifier(a.columnName)} ${di(a.logicalType)}${a.nullable===!1?" NOT NULL":""}`)}for(const t of ni(e))await this.query(`CREATE INDEX IF NOT EXISTS ${this.identifier(t.name)} ON ${this.identifier(t.table)} (${this.identifier(t.foreignColumn)}, ${this.identifier(t.idColumn)} DESC)`);await this.query("CREATE TABLE IF NOT EXISTS teaql_id_space (type_name TEXT PRIMARY KEY, current_level INTEGER NOT NULL)")}async nextId(e,t){for(let n=1;n<=100;n+=1){const r=await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t]);if(!r.rowCount){try{if((await e.query("INSERT INTO teaql_id_space(type_name, current_level) VALUES (?, 1)",[t])).rowCount===1)return"1"}catch(c){if(!(await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t])).rowCount)throw c}continue}const o=Number(r.rows[0].id),s=o+1,a=await e.query("UPDATE teaql_id_space SET current_level = ? WHERE type_name = ? AND current_level = ?",[s,t,o]);if(a.rowCount===1)return String(s);if(a.rowCount!==0)throw new Error(`ID space update for ${t} changed ${a.rowCount} rows`)}throw new Error(`Unable to allocate ID for ${t} after 100 optimistic-lock attempts`)}ensureIdFloor(e,t,n){return ri(e,r=>this.placeholder(r),t,n)}reset(){return this.exclusive(()=>this.transport.request("reset",this.options))}close(){return this.exclusive(()=>this.transport.close(this.options.terminateWorkerOnClose))}}class at extends ai{constructor(e,t){super(e,t),this.browserDriver=e}static async open(e,t,n={}){return new at(await Te.open(e,n),t)}get storage(){return this.browserDriver.options.storage}async reset(e){await this.browserDriver.reset(),this.invalidateSchemaState(),await e.ensureSchema()}}function di(i){return{boolean:"INTEGER",double:"REAL",decimal:"NUMERIC",date:"TEXT",datetime:"TEXT",json:"TEXT",integer:"INTEGER",text:"TEXT"}[i]}function fi(i){const e=i.trim();if(!e||e.includes("/")||e.includes("\\")||e==="."||e==="..")throw new TypeError("Browser SQLite databaseName must be a simple file name");return e}function vi(i,e,t,n){const r=o=>{if(o.includes("."))throw new Error("Dynamic search requires a trusted relation binding");const s=t[i.entity]?.queryFields;if(!s||!Object.prototype.hasOwnProperty.call(s,o))throw new Error("Missing generated scalar search binding");return s[o]};return gi(i,e,t,{filter:(o,s)=>{const[a,c]=Object.entries(s)[0];if(c===null&&a!=="$eq"&&a!=="$ne")throw new Error("Null supports only equality predicates");return{[r(o)]:s}},order:(o,s)=>s==="asc"?q.asc(r(o)):q.desc(r(o))},n)}function gi(i,e,t,n,r=o=>console.warn({...o,fieldPath:""})){const o=yi(e,i.entity,t,()=>{}),s=Object.entries(o.search.filter??{}).map(([f,g])=>n.filter(f,g)),a=(o.search.orderBy??[]).map(f=>n.order(f.field,f.direction));if(s.some(f=>!V(f)))throw new Error("Invalid trusted search filter binding");if(a.some(f=>!(f instanceof q)))throw new Error("Invalid trusted search order binding");const c=i.clone(),l=i._filters??[],u=[...l,...i.filterCondition?[i.filterCondition]:[]];return(s.length||l.length)&&c.filter({$and:[...u,...s]}),c.orderItems.push(...a),o.warnings.forEach(f=>r({...f})),{query:c,warnings:o.warnings}}const te=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),V=i=>typeof i=="object"&&i!==null&&!Array.isArray(i),pi=new Set(["__proto__","prototype","constructor"]),mi=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$notIn","$contains"]);function yi(i,e,t,n=o=>console.warn({...o,fieldPath:""}),r=100){if(!Number.isSafeInteger(r)||r<1)throw new Error("Invalid search limit");if(!te(t,e))throw new Error("Unknown search entity");let o;try{o=typeof i=="string"?JSON.parse(i):i}catch{throw new Error("Dynamic search requires valid JSON")}if(!V(o)||Object.keys(o).some(h=>!["filter","orderBy"].includes(h)))throw new Error("Unsupported dynamic search input or control");if(o.filter!==void 0&&!V(o.filter))throw new Error("Invalid search filter");if(o.orderBy!==void 0&&!Array.isArray(o.orderBy))throw new Error("Invalid search ordering");const s=Object.entries(o.filter??{}),a=o.orderBy??[];if(s.length+a.length>r)throw new Error("Dynamic search exceeds clause limit");const c=[],l={filter:Object.create(null),orderBy:[]};function u(h){const p=h.split(".");if(p.length>16||p.some(d=>!d||d.startsWith("$")||pi.has(d)))throw new Error("Invalid dynamic search field path");let m=t[e];for(const d of p.slice(0,-1)){if(!te(m.relations,d))return;const b=m.relations[d];if(!te(t,b))throw new Error("Invalid trusted search relation metadata");m=t[b]}const y=p[p.length-1];return te(m.fields,y)?m.fields[y]:void 0}function f(h,p){c.push({code:"DYNAMIC_SEARCH_UNKNOWN_FIELD",entity:e,clause:p,fieldPath:h})}function g(h,p){if(h===null)return;if(!(p==="date"?typeof h=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(h)&&!h.startsWith("0000-")&&Number.isFinite(Date.parse(h+"T00:00:00Z"))&&new Date(h+"T00:00:00Z").toISOString().slice(0,10)===h:p==="decimal"?typeof h=="string"&&/^[+-]?\d+(?:\.\d+)?$/.test(h)||typeof h=="number"&&Number.isFinite(h):p==="integer"||p==="timestamp"?typeof h=="number"&&Number.isSafeInteger(h):p==="number"?typeof h=="number"&&Number.isFinite(h):typeof h===p))throw new Error("Invalid value for known search field")}for(const[h,p]of s){const m=V(p)?Object.entries(p):[["$eq",p]];if(m.length!==1||!mi.has(m[0][0]))throw new Error("Unsupported or malformed dynamic search operator");const[y,d]=m[0];if((y==="$in"||y==="$notIn")&&(!Array.isArray(d)||d.length>1e3))throw new Error("Invalid or oversized search value list");const b=u(h);if(b===void 0){f(h,"FILTER");continue}if(b==="unsupported")throw new Error("Known search field has no supported scalar binding");if(y==="$contains"&&b!=="string")throw new Error("String operator requires a string field");if(Array.isArray(d)){if(y!=="$in"&&y!=="$notIn")throw new Error("Unexpected search value list");d.forEach(E=>g(E,b))}else g(d,b);l.filter[h]={[y]:Array.isArray(d)?[...d]:d}}for(const h of a){if(!V(h)||Object.keys(h).some(m=>!["field","direction"].includes(m))||typeof h.field!="string"||!["asc","desc"].includes(h.direction))throw new Error("Invalid dynamic search ordering");const p=u(h.field);if(p===void 0){f(h.field,"ORDER_BY");continue}if(p==="unsupported")throw new Error("Known search field has no supported scalar binding");l.orderBy.push({field:h.field,direction:h.direction})}return c.forEach(h=>n({...h})),{search:l,warnings:c}}export{at as B,dt as C,wi as D,Oe as L,U as M,q as O,ae as Q,rt as R,Yt as S,Ht as U,J as a,Si as b,bi as c,vi as d,ot as e,_ as f,gi as m}; diff --git a/dist/assets/main-Cg0XY2hs.js b/dist/assets/main-Cg0XY2hs.js new file mode 100644 index 0000000000000000000000000000000000000000..8d0e51880261e77283ffad873144639d1587aed0 --- /dev/null +++ b/dist/assets/main-Cg0XY2hs.js @@ -0,0 +1,104 @@ +import{S as x,m as Te,a as qe,e as xe,O as $,B as Qe,b as Re,R as $e,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-Ch_QcWVU.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ie={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(` +`,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const i=f[String(a)];return i===void 0?a:Number(i)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class P{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(` +`)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this.pageTotalAlias)));const i=await n.executeQuery(e.prepareQuery(a)),c=new qe(i,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,l=>e.prepareQuery(l),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?$.asc(e):$.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends P{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends P{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends P{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends P{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends P{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends P{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends P{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?$.asc(s):$.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),b=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),R=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),V=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let d=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[d]??t}function O(t){return d==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let w="tree",v,fe=0,ee;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ae==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset) + .limit(pageSize) + .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:te(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() + .selectPlatformWith(Q.platforms().selectName()) + .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .orderByOrderDateDescending() + .orderByIdDescending() + .limit(8) + .comment('what: list recent commerce orders') + .purpose('why: provide the default order overview') + .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() + .withOrderNumberIs('TQL-2026-1003') + .selectPlatformWith(Q.platforms()) + .selectCustomerWith(Q.customers()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectItemListWith(Q.orderItems().orderByIdAscending()) + .selectPaymentListWith(Q.payments().orderByIdAscending()) + .selectShipmentListWith(Q.shipments().orderByIdAscending()) + .limit(1) + .comment('what: load one complete order graph') + .purpose('why: inspect items, payment and fulfillment together') + .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() + .selectPlatformWith(Q.platforms().selectName()) + .countOrderListAs('orderCount') + .orderByNameAscending() + .comment('what: list customers with related order counts') + .purpose('why: compare customer activity at a glance') + .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() + .groupByCurrency().groupByStatus() + .countAs('orderCount') + .sumTotalAmountAs('grossAmount') + .averageTotalAmountAs('averageOrderValue') + .comment('what: aggregate orders by currency and status') + .purpose('why: show the current order funnel') + .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() + .groupByProductName() + .sumQuantityAs('units') + .sumLineAmountAs('revenue') + .comment('what: aggregate sold units and line revenue') + .purpose('why: identify the strongest products in the demo data') + .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() + .groupByCurrency().groupByProvider().groupByStatus() + .countAs('paymentCount').sumAmountAs('paymentAmount') + .orderByCurrencyAscending().orderByProviderAscending() + .comment('what: reconcile payment totals by provider') + .purpose('why: compare captured, pending and refunded money') + .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、范围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() + .withStatusIsPendingPayment() + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectCustomerWith(Q.customers().selectName()) + .selectPaymentListWith(Q.payments()) + .comment('what: find orders awaiting payment') + .purpose('why: support payment follow-up') + .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() + .withPlatformIdIs('1') + .withTotalAmountGreaterThanOrEqualTo(500) + .selectCustomerWith(Q.customers().selectName().selectCity()) + .orderByTotalAmountDescending() + .comment('what: find high-value domestic orders') + .purpose('why: prioritize valuable fulfillment work') + .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() + .withStatusIn('READY', 'IN_TRANSIT') + .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) + .orderByStatusAscending().orderByIdAscending() + .comment('what: find shipments that are not delivered') + .purpose('why: monitor active fulfillment') + .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { + "filter": { + "currency": "CNY", + "totalAmount": { "$gte": 250 }, + "status": { "$in": ["PAID", "SHIPPED"] } + }, + "orderBy": [{ "field": "totalAmount", "direction": "desc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>G(t,{filter:{currency:"CNY",totalAmount:{$gte:250},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { + "filter": { "orderDate": { "$gte": "2026-09-15" } }, + "orderBy": [{ "field": "orderDate", "direction": "asc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>G(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { + "filter": { + "status": "DELIVERED", + "internalNote": { "$contains": "not queryable" } + } +}; +const request = Q.customerOrders().filterByJson(input); +const data = await request + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx); +const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ie},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new Re().enableSelect();r.install(new $e(ie,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),o=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:o.payload}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){F.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const i=document.createElement("a");i.href=`#${a.id}`,i.dataset.queryId=a.id,i.textContent=O(a.title),i.addEventListener("click",c=>{c.preventDefault(),W=a.id,history.replaceState(null,"",`#${a.id}`),H(),E&&D(a,E).catch(N)}),o.append(i)}e.append(r,o),F.append(e)}H()}function H(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function D(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),b.classList.add("loading"),b.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),b.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),R.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",J.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),v={data:s,query:t,active:e},w=t.view==="dashboard"||Z(s)?"table":"tree",z();const o=Math.max(1,Math.round(performance.now()-r));fe=o,ee=n;const a=e.evidence.snapshot();we(a,n),Le(s,t,o)}finally{b.classList.remove("loading"),b.removeAttribute("aria-busy")}}function we(t,e=ee){ue.replaceChildren(),et.textContent=d==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(m=>m.kind==="relation"||m.kind==="request"||m.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const i=document.createElement("td");i.textContent=`${v?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const m=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${m?.detail||m?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(m=>m.detail||m.name).join(" → ");const l=document.createElement("td");l.className="evidence-sql";const h=r.parameters.length?r.parameters.map(m=>String(m)).join(", "):"none";l.textContent=`${r.parameterizedSQL} · bindings: ${h}`,s.append(a,i,c,l),ue.append(s)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!v)return;const{data:t,query:e,active:r}=v,n=e.view==="dashboard"||Z(t);if(n||(w="tree"),Q.disabled=!n,Q.classList.toggle("active",w==="table"),V.classList.toggle("active",w==="tree"),Q.setAttribute("aria-pressed",String(w==="table")),V.setAttribute("aria-pressed",String(w==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",w!=="tree"),w==="table"&&e.view==="dashboard"){R.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(w==="table"&&Z(t)){R.textContent=d==="en"?"Result table":"结果表格",ut(t);return}R.textContent=d==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const i=document.createElement("p");i.className="result-table-empty",i.textContent=d==="en"?"The query returned no records.":"查询没有返回记录。",e.append(i),b.replaceChildren(e);return}const r=[...new Set(t.flatMap(i=>Object.keys(i)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const i of r){const c=document.createElement("th");c.scope="col",c.textContent=i,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const i of t){const c=document.createElement("tr");for(const l of r){const h=document.createElement("td");h.textContent=lt(i[l]),c.append(h)}a.append(c)}n.append(s,a),e.append(n),b.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return d==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return be(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?d==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=d==="en"?"Order Management Center":"订单管理中心";const i=document.createElement("p");i.textContent=d==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,i);const c=document.createElement("form");c.className="order-search";const l=document.createElement("input");l.type="search",l.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",l.value=t.search,l.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),h.title=d==="en"?"Search":"查询";const m=document.createElement("span");m.className="search-icon",m.setAttribute("aria-hidden","true"),h.append(m),c.append(l,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=l.value.trim(),A.page=0,D(r,e).catch(N)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(d==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,D(r,e).catch(N)}));for(const p of t.statusFacets)S.append(me(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,D(r,e).catch(N)},`${d==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const ve=d==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of ve){const q=document.createElement("span");q.textContent=p,M.append(q)}if(g.append(M),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const _=document.createElement("div");_.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=d==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const T=document.createElement("div");T.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));T.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p=ae-1,e,r)),_.append(ne,T),n.append(s,S,g,_),b.replaceChildren(n)}function me(t,e,r,n,s,o,a){const i=document.createElement("button");i.type="button",i.className=`metric-card metric-${r}`,n&&i.style.setProperty("--metric-color",n),i.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const l=document.createElement("strong");if(l.textContent=String(e),i.append(c,l),a){const h=document.createElement("small");h.textContent=a,i.append(h)}return i.addEventListener("click",o),i}function pt(t){return new Intl.NumberFormat(d==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(m=>{const S=document.createElement("span");S.className="order-primary",S.textContent=m,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=te(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=be(i)||String(r.name??i);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const l=document.createElement("span");l.className="product-preview",n.forEach((m,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(m.productName??"?").slice(0,1),g.title=`${String(m.productName??"")} × ${String(m.quantity??1)}`,l.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const m=document.createElement("small");m.textContent=`+${h}`,l.append(m)}return e.append(l),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,D(s,n).catch(N)}),o}function be(t){return(d==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){b.replaceChildren(Ne(t,"result",0))}function Ne(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),i=document.createElement("details");i.className="tree-branch",i.open=r===0;const c=document.createElement("summary"),l=document.createElement("span");l.className="tree-key",l.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,a.length),c.append(l,h),i.append(c);const m=document.createElement("div");m.className="tree-children";for(const[S,g]of a)m.append(Ne(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(m),i}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return d==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):d==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Le(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=d==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;k.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function De(){document.documentElement.lang=d==="en"?"en":"zh-CN",document.title=d==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=d==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===d;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",d==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",d==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",d==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",d==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",d==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",d==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",d==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",d==="en"?"Result tree actions":"结果树操作"),dt(),v){const{data:e,query:r,active:n}=v;ye.textContent=O(r.title),he.textContent=O(r.description),z(),we(n.evidence.snapshot(),ee),Le(e,r,fe),Oe(B.checked?"opfs":"memory")}else k.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return le.find(t=>t.id===W)??le[0]}async function Pe(t){k.textContent=d==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await D(re(),r),Oe(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Pe(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await D(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{b.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(w="table",z())});V.addEventListener("click",()=>{w="tree",z()});tt.addEventListener("click",()=>{b.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{d=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",d),De()})});function N(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}De();W=re().id;H();Pe(Ae).catch(N); diff --git a/dist/assets/main-gHLGx1pH.js b/dist/assets/main-gHLGx1pH.js deleted file mode 100644 index 5de35f55d321681eb889d38d979c8068d7a7b040..0000000000000000000000000000000000000000 --- a/dist/assets/main-gHLGx1pH.js +++ /dev/null @@ -1,102 +0,0 @@ -import{S as T,m as Te,a as ie,e as de,O as R,B as Qe,b as $e,R as Re,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-BBmdgl4H.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),_e=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ce={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},he=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(` -`,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),Me={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,o=n.status,s=d=>{const a=f[String(d)];return a===void 0?d:Number(a)};return o&&typeof o=="object"&&!Array.isArray(o)&&"$in"in o?n.status={$in:Array.isArray(o.$in)?o.$in.map(s):o.$in}:n.status=s(o),e}class D{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new T(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(` -`)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){this.ensureIntent();const r=this.service(e),n=this.toQuery(),o=await r.executeQuery(e.prepareQuery(n)),s=new ie(o);return n.facets.length&&(s.facets=await de(r,d=>e.prepareQuery(d),n,n.facets)),s}async executeForRows(e){return this.executeForList(e)}async executeForPage(e,r,n){this.ensureIntent();const o=this.service(e),s=this.toQuery(),d=await o.executeCount(s,this.pageTotalAlias,this.pageTotalAlias?{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}:void 0),a=this.toQuery().offset(r).limit(n),c=new ie(await o.executeQuery(e.prepareQuery(a)),{totalCount:d});return this.pageTotalAlias&&(c.aggregations[this.pageTotalAlias]=d),s.facets.length&&(c.facets=await de(o,m=>e.prepareQuery(m),s,s.facets)),{data:c,totalCount:d,offset:r,limit:n}}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends D{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends D{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new T("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends D{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends D{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class He extends D{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class Ve extends D{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class ue extends D{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),Me,{filter:(o,s)=>o==="status.code"?{status:{$inSubquery:{query:new T("OrderStatus").filter({code:s}),field:"id"}}}:o==="itemList.productName"?{id:{$inSubquery:{query:new T("OrderItem").filter({productName:s}),field:"orderId"}}}:{[o]:s},order:(o,s)=>s==="asc"?R.asc(o):R.desc(o)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new T("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const o=r.toQuery();return o.commentText||o.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>o},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.applyRowCount(),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForList(e)}executeForPage(e,r,n){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForPage(e,r,n)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new ue}static customerOrdersWithMinimalFields(){return new ue(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new He}static shipments(){return new Ve}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),b=document.querySelector("#result"),ge=document.querySelector("#result-title"),fe=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),le=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),$=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),me=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=document.querySelector("#view-tree"),Ae=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let i=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[i]??t}function O(t){return i==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let w="tree",v,Se=0,ee;const A={search:"",page:0,pageSize:4},Ce=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ce==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Ie(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(o=>o.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Ie(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=await r.executeForPage(t.context,A.page*A.pageSize,A.pageSize),o=n.data.facet("statusCounts")??[];return{orders:n.data,totalOrders:Number(n.data.aggregations.totalOrders??n.totalCount),filteredOrders:n.totalCount,statusFacets:o.map(s=>({code:te(s),name:String(s.name??""),color:String(s.color??""),orderCount:Number(s.orderCount??0),orderTotalAmount:Number(s.orderTotalAmount??0)})).filter(s=>s.code&&s.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:r.toQExpression("executeForPage(ctx, pageOffset, pageSize);")}}const we=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() - .selectPlatformWith(Q.platforms().selectName()) - .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) - .selectStatusWith(Q.orderStatuses().selectName().selectColor()) - .orderByOrderDateDescending() - .orderByIdDescending() - .limit(8) - .comment('what: list recent commerce orders') - .purpose('why: provide the default order overview') - .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() - .withOrderNumberIs('TQL-2026-1003') - .selectPlatformWith(Q.platforms()) - .selectCustomerWith(Q.customers()) - .selectStatusWith(Q.orderStatuses().selectName().selectColor()) - .selectItemListWith(Q.orderItems().orderByIdAscending()) - .selectPaymentListWith(Q.payments().orderByIdAscending()) - .selectShipmentListWith(Q.shipments().orderByIdAscending()) - .limit(1) - .comment('what: load one complete order graph') - .purpose('why: inspect items, payment and fulfillment together') - .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() - .selectPlatformWith(Q.platforms().selectName()) - .countOrderListAs('orderCount') - .orderByNameAscending() - .comment('what: list customers with related order counts') - .purpose('why: compare customer activity at a glance') - .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() - .groupByCurrency().groupByStatus() - .countAs('orderCount') - .sumTotalAmountAs('grossAmount') - .averageTotalAmountAs('averageOrderValue') - .comment('what: aggregate orders by currency and status') - .purpose('why: show the current order funnel') - .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() - .groupByProductName() - .sumQuantityAs('units') - .sumLineAmountAs('revenue') - .comment('what: aggregate sold units and line revenue') - .purpose('why: identify the strongest products in the demo data') - .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() - .groupByCurrency().groupByProvider().groupByStatus() - .countAs('paymentCount').sumAmountAs('paymentAmount') - .orderByCurrencyAscending().orderByProviderAscending() - .comment('what: reconcile payment totals by provider') - .purpose('why: compare captured, pending and refunded money') - .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、范围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() - .withStatusIsPendingPayment() - .selectStatusWith(Q.orderStatuses().selectName().selectColor()) - .selectCustomerWith(Q.customers().selectName()) - .selectPaymentListWith(Q.payments()) - .comment('what: find orders awaiting payment') - .purpose('why: support payment follow-up') - .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() - .withPlatformIdIs('1') - .withTotalAmountGreaterThanOrEqualTo(500) - .selectCustomerWith(Q.customers().selectName().selectCity()) - .orderByTotalAmountDescending() - .comment('what: find high-value domestic orders') - .purpose('why: prioritize valuable fulfillment work') - .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() - .withStatusIn('READY', 'IN_TRANSIT') - .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) - .orderByStatusAscending().orderByIdAscending() - .comment('what: find shipments that are not delivered') - .purpose('why: monitor active fulfillment') - .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { - "filter": { - "currency": "CNY", - "totalAmount": { "$gte": 250 }, - "status": { "$in": ["PAID", "SHIPPED"] } - }, - "orderBy": [{ "field": "totalAmount", "direction": "desc" }] -}; -const data = await Q.customerOrders() - .filterByJson(input) - .limit(20) - .comment('what: execute a validated browser search') - .purpose('why: demonstrate safe dynamic order discovery') - .executeForList(ctx);`,run:t=>G(t,{filter:{currency:"CNY",totalAmount:{$gte:250},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { - "filter": { "orderDate": { "$gte": "2026-09-15" } }, - "orderBy": [{ "field": "orderDate", "direction": "asc" }] -}; -const data = await Q.customerOrders() - .filterByJson(input) - .limit(20) - .comment('what: execute a validated browser search') - .purpose('why: demonstrate safe dynamic order discovery') - .executeForList(ctx);`,run:t=>G(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { - "filter": { - "status": "DELIVERED", - "internalNote": { "$contains": "not queryable" } - } -}; -const request = Q.customerOrders().filterByJson(input); -const data = await request - .limit(20) - .comment('what: execute a validated browser search') - .purpose('why: demonstrate safe dynamic order discovery') - .executeForList(ctx); -const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],pe=we.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ce},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new $e().enableSelect();r.install(new Re(ce,{},{constants:_e})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const o=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),s=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:o,review:(d,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(d=>({policy:d,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(s),await s.ensureSchema(),{client:r,context:s,evidence:n}}async function be(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const o=he.map(s=>n.request({entity:s.entity,action:"Create",id:s.id,payload:s.payload}));for(const s of o)t.client.preflightMutation(s);for(const s of o)await t.client.executeMutation(s)})}function dt(){F.replaceChildren();for(const t of we){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const o=document.createElement("p");o.textContent=O(t.description),r.append(n,o);const s=document.createElement("div");s.className="query-links";for(const d of t.queries){const a=document.createElement("a");a.href=`#${d.id}`,a.dataset.queryId=d.id,a.textContent=O(d.title),a.addEventListener("click",c=>{c.preventDefault(),W=d.id,history.replaceState(null,"",`#${d.id}`),V(),E&&P(d,E).catch(N)}),s.append(a)}e.append(r,s),F.append(e)}V()}function V(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function P(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),b.classList.add("loading"),b.setAttribute("aria-busy","true"),ge.textContent=O(t.title),fe.textContent=O(t.description),le.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Ie(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),b.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),$.textContent=t.view==="dashboard"?i==="en"?"Order management center":"订单管理中心":i==="en"?"Result tree":"结果树",J.textContent=i==="en"?"Running query…":"查询中…";try{const o=await t.run(e);t.view==="dashboard"&&(le.textContent=o.queryExpression),v={data:o,query:t,active:e},w=t.view==="dashboard"||Z(o)?"table":"tree",z();const s=Math.max(1,Math.round(performance.now()-r));Se=s,ee=n;const d=e.evidence.snapshot();Ee(d,n),Pe(o,t,s)}finally{b.classList.remove("loading"),b.removeAttribute("aria-busy")}}function Ee(t,e=ee){me.replaceChildren(),et.textContent=i==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const o=document.createElement("tr");o.className="evidence-row";const s=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),d=document.createElement("td");d.className="evidence-time",d.dataset.executedAt=e?.toISOString()??"",d.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const a=document.createElement("td");a.textContent=`${v?.query.id??"query"} · #${n+1} · ${s?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const h=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${h}`,o.append(d,a,c,m),me.append(o)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!v)return;const{data:t,query:e,active:r}=v,n=e.view==="dashboard"||Z(t);if(n||(w="tree"),Q.disabled=!n,Q.classList.toggle("active",w==="table"),H.classList.toggle("active",w==="tree"),Q.setAttribute("aria-pressed",String(w==="table")),H.setAttribute("aria-pressed",String(w==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",w!=="tree"),w==="table"&&e.view==="dashboard"){$.textContent=i==="en"?"Result table":"结果表格",mt(t,r,e);return}if(w==="table"&&Z(t)){$.textContent=i==="en"?"Result table":"结果表格",ut(t);return}$.textContent=i==="en"?"Result tree":"结果树",Le(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const a=document.createElement("p");a.className="result-table-empty",a.textContent=i==="en"?"The query returned no records.":"查询没有返回记录。",e.append(a),b.replaceChildren(e);return}const r=[...new Set(t.flatMap(a=>Object.keys(a)))],n=document.createElement("table");n.className="result-table";const o=document.createElement("thead"),s=document.createElement("tr");for(const a of r){const c=document.createElement("th");c.scope="col",c.textContent=a,s.append(c)}o.append(s);const d=document.createElement("tbody");for(const a of t){const c=document.createElement("tr");for(const m of r){const h=document.createElement("td");h.textContent=lt(a[m]),c.append(h)}d.append(c)}n.append(o,d),e.append(n),b.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return i==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return Ne(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?i==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const o=document.createElement("div");o.className="order-center-toolbar";const s=document.createElement("div"),d=document.createElement("h3");d.textContent=i==="en"?"Order Management Center":"订单管理中心";const a=document.createElement("p");a.textContent=i==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",s.append(d,a);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=i==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",i==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",i==="en"?"Run order query":"执行订单查询"),h.title=i==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),h.append(l),c.append(m,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=m.value.trim(),A.page=0,P(r,e).catch(N)}),o.append(s,c);const S=document.createElement("div");S.className="order-metrics",S.append(ye(i==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,P(r,e).catch(N)}));for(const p of t.statusFacets)S.append(ye(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,P(r,e).catch(N)},`${i==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const _=document.createElement("div");_.className="order-row order-row-head";const xe=i==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of xe){const x=document.createElement("span");x.textContent=p,_.append(x)}if(g.append(_),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=i==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const M=document.createElement("div");M.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=i==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const q=document.createElement("div");q.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));q.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p=ae-1,e,r)),M.append(ne,q),n.append(o,S,g,M),b.replaceChildren(n)}function ye(t,e,r,n,o,s,d){const a=document.createElement("button");a.type="button",a.className=`metric-card metric-${r}`,n&&a.style.setProperty("--metric-color",n),a.classList.toggle("active",o);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),a.append(c,m),d){const h=document.createElement("small");h.textContent=d,a.append(h)}return a.addEventListener("click",s),a}function pt(t){return new Intl.NumberFormat(i==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const s=document.createElement("span"),d=document.createElement("span"),a=te(r);d.className=`status-badge status-${a.toLowerCase()}`,d.textContent=Ne(a)||String(r.name??a);const c=String(r.color??"");c&&(d.style.color=c,d.style.backgroundColor=`${c}18`),s.append(d),e.append(s);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const l=document.createElement("small");l.textContent=`+${h}`,m.append(l)}return e.append(m),e}function j(t,e,r,n,o){const s=document.createElement("button");return s.type="button",s.textContent=t,s.disabled=r,s.addEventListener("click",()=>{A.page=e,P(o,n).catch(N)}),s}function Ne(t){return(i==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Le(t){b.replaceChildren(Oe(t,"result",0))}function Oe(t,e,r){if(t!==null&&typeof t=="object"){const d=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),a=document.createElement("details");a.className="tree-branch",a.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,d.length),c.append(m,h),a.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of d)l.append(Oe(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return a.append(l),a}const n=document.createElement("div");n.className="tree-leaf";const o=document.createElement("span");o.className="tree-key",o.textContent=e;const s=document.createElement("span");return s.className=`tree-value tree-${t===null?"null":typeof t}`,s.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(o,s),n}function ht(t,e){if(Array.isArray(t))return i==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):i==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Pe(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),o=i==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${o} · ${r} ms · ${i==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function De(t){const e=he.filter(r=>r.entity==="CustomerOrder").length;k.textContent=i==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=i==="en"?"en":"zh-CN",document.title=i==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=i==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),Ae.forEach(e=>{const r=e.dataset.locale===i;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",i==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",i==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",i==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",i==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",i==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",i==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",i==="en"?"Result tree actions":"结果树操作"),dt(),v){const{data:e,query:r,active:n}=v;ge.textContent=O(r.title),fe.textContent=O(r.description),z(),Ee(n.evidence.snapshot(),ee),Pe(e,r,Se),De(B.checked?"opfs":"memory")}else k.textContent=i==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return pe.find(t=>t.id===W)??pe[0]}async function qe(t){k.textContent=i==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await be(r),await P(re(),r),De(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),qe(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await be(E),await P(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{b.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(w="table",z())});H.addEventListener("click",()=>{w="tree",z()});tt.addEventListener("click",()=>{b.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});Ae.forEach(t=>{t.addEventListener("click",()=>{i=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",i),ve()})});function N(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=i==="en"?"Query failed":"查询失败",Le({error:e.name,message:e.message})}ve();W=re().id;V();qe(Ce).catch(N); diff --git a/assets/object-location-xgYMemK6.js b/dist/assets/object-location-CJfVWqJC.js similarity index 98% rename from assets/object-location-xgYMemK6.js rename to dist/assets/object-location-CJfVWqJC.js index 8c8bc4aa545522c7f661771b17aa4cfc4635714b..c939dc87b827c5badde2203ea5ea8a76769aea66 100644 --- a/assets/object-location-xgYMemK6.js +++ b/dist/assets/object-location-CJfVWqJC.js @@ -1 +1 @@ -import{f as u}from"./dynamic-search-BBmdgl4H.js";const i=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class V{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(s,e){this.traces.set(i(s),{key:Object.freeze({...s}),nodes:u(e)})}traceChain(s){return this.traces.get(i(s))?.nodes}set(s,e,t){if(!e.trim())throw new TypeError("field is required");const r=i(s),a=this.changes.get(r)??{key:Object.freeze({...s}),values:{}};a.values[e]=t,this.changes.set(r,a)}snapshot(){return[...this.changes.values()].map(s=>({key:Object.freeze({...s.key}),values:Object.freeze({...s.values})}))}change(s){return Object.freeze({...this.changes.get(i(s))?.values??{}})}mergeFrom(s){if(s!==this){for(const e of s.snapshotVersions())this.requireMatchingVersion(e.key,e.version);for(const e of s.snapshot())for(const[t,r]of Object.entries(e.values))this.set(e.key,t,r);for(const e of s.newKeys.values())this.markAsNew(e);for(const e of s.deletedKeys.values())this.markAsDeleted(e);for(const e of s.snapshotVersions())this.setOriginalVersion(e.key,e.version);for(const e of s.traces.values())this.setTraceChain(e.key,e.nodes)}}mergeEntityFrom(s,e){if(s===this)return;const t=s.originalVersion(e);t!==void 0&&this.requireMatchingVersion(e,t);for(const[a,c]of Object.entries(s.change(e)))this.set(e,a,c);s.isNew(e)&&this.markAsNew(e),s.isDeleted(e)&&this.markAsDeleted(e),t!==void 0&&this.setOriginalVersion(e,t);const r=s.traceChain(e);r&&this.setTraceChain(e,r)}hasPending(s){const e=i(s);return this.newKeys.has(e)||this.deletedKeys.has(e)||Object.keys(this.changes.get(e)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(s,e){const t=i(s),r=i(e);if(t===r)return;const a=this.originalVersion(s);a!==void 0&&this.requireMatchingVersion(e,a);const c=this.changes.get(t);if(c){this.changes.delete(t);for(const[f,g]of Object.entries(c.values))this.set(e,f,g)}const h=this.originalVersions.get(t);h!==void 0&&(this.originalVersions.delete(t),this.originalVersions.set(r,{key:Object.freeze({...e}),version:h.version})),this.newKeys.delete(t)&&this.newKeys.set(r,Object.freeze({...e})),this.deletedKeys.delete(t)&&this.deletedKeys.set(r,Object.freeze({...e}));const l=this.traces.get(t);l&&(this.traces.delete(t),this.setTraceChain(e,l.nodes))}clearEntity(s){const e=i(s);this.changes.delete(e),this.newKeys.delete(e),this.deletedKeys.delete(e),this.traces.delete(e)}requireMatchingVersion(s,e){const t=this.originalVersion(s);if(t!==void 0&&t!==e)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(s,e){this.requireMatchingVersion(s,e),this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}acceptCommittedVersion(s,e){if(this.hasPending(s))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}originalVersion(s){return this.originalVersions.get(i(s))?.version}markAsNew(s){this.newKeys.set(i(s),Object.freeze({...s}))}isNew(s){return this.newKeys.has(i(s))}markAsDeleted(s){const e=i(s);this.changes.delete(e),this.deletedKeys.set(e,Object.freeze({...s}))}isDeleted(s){return this.deletedKeys.has(i(s))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}function d(n){const s=n.split("_");return s[0]+s.slice(1).map(e=>e?e[0].toUpperCase()+e.slice(1):"").join("")}function p(n,s){if(s==="snake_case")return n;const e=d(n);return s==="camelCase"||!e?e:e[0].toUpperCase()+e.slice(1)}function m(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class o{constructor(s){this.segments=s}static root(){return new o([])}static property(s){return o.root().property(s)}property(s){return new o([...this.segments,{kind:"property",name:s}])}index(s){return new o([...this.segments,{kind:"index",index:s}])}prefixedBy(s){return new o([...s.segments,...this.segments])}modelPath(){return this.render(s=>s)}nativePath(){return this.render(d)}instancePath(s="camelCase"){return this.segments.map(e=>e.kind==="index"?String(e.index):m(p(e.name,s))).map(e=>`/${e}`).join("")}toString(){return this.nativePath()}render(s){let e="";for(const t of this.segments)t.kind==="index"?e+=`[${t.index}]`:e+=`${e?".":""}${s(t.name)}`;return e}}export{V as E,o as O}; +import{f as u}from"./dynamic-search-Ch_QcWVU.js";const i=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class V{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(s,e){this.traces.set(i(s),{key:Object.freeze({...s}),nodes:u(e)})}traceChain(s){return this.traces.get(i(s))?.nodes}set(s,e,t){if(!e.trim())throw new TypeError("field is required");const r=i(s),a=this.changes.get(r)??{key:Object.freeze({...s}),values:{}};a.values[e]=t,this.changes.set(r,a)}snapshot(){return[...this.changes.values()].map(s=>({key:Object.freeze({...s.key}),values:Object.freeze({...s.values})}))}change(s){return Object.freeze({...this.changes.get(i(s))?.values??{}})}mergeFrom(s){if(s!==this){for(const e of s.snapshotVersions())this.requireMatchingVersion(e.key,e.version);for(const e of s.snapshot())for(const[t,r]of Object.entries(e.values))this.set(e.key,t,r);for(const e of s.newKeys.values())this.markAsNew(e);for(const e of s.deletedKeys.values())this.markAsDeleted(e);for(const e of s.snapshotVersions())this.setOriginalVersion(e.key,e.version);for(const e of s.traces.values())this.setTraceChain(e.key,e.nodes)}}mergeEntityFrom(s,e){if(s===this)return;const t=s.originalVersion(e);t!==void 0&&this.requireMatchingVersion(e,t);for(const[a,c]of Object.entries(s.change(e)))this.set(e,a,c);s.isNew(e)&&this.markAsNew(e),s.isDeleted(e)&&this.markAsDeleted(e),t!==void 0&&this.setOriginalVersion(e,t);const r=s.traceChain(e);r&&this.setTraceChain(e,r)}hasPending(s){const e=i(s);return this.newKeys.has(e)||this.deletedKeys.has(e)||Object.keys(this.changes.get(e)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(s,e){const t=i(s),r=i(e);if(t===r)return;const a=this.originalVersion(s);a!==void 0&&this.requireMatchingVersion(e,a);const c=this.changes.get(t);if(c){this.changes.delete(t);for(const[f,g]of Object.entries(c.values))this.set(e,f,g)}const h=this.originalVersions.get(t);h!==void 0&&(this.originalVersions.delete(t),this.originalVersions.set(r,{key:Object.freeze({...e}),version:h.version})),this.newKeys.delete(t)&&this.newKeys.set(r,Object.freeze({...e})),this.deletedKeys.delete(t)&&this.deletedKeys.set(r,Object.freeze({...e}));const l=this.traces.get(t);l&&(this.traces.delete(t),this.setTraceChain(e,l.nodes))}clearEntity(s){const e=i(s);this.changes.delete(e),this.newKeys.delete(e),this.deletedKeys.delete(e),this.traces.delete(e)}requireMatchingVersion(s,e){const t=this.originalVersion(s);if(t!==void 0&&t!==e)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(s,e){this.requireMatchingVersion(s,e),this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}acceptCommittedVersion(s,e){if(this.hasPending(s))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}originalVersion(s){return this.originalVersions.get(i(s))?.version}markAsNew(s){this.newKeys.set(i(s),Object.freeze({...s}))}isNew(s){return this.newKeys.has(i(s))}markAsDeleted(s){const e=i(s);this.changes.delete(e),this.deletedKeys.set(e,Object.freeze({...s}))}isDeleted(s){return this.deletedKeys.has(i(s))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}function d(n){const s=n.split("_");return s[0]+s.slice(1).map(e=>e?e[0].toUpperCase()+e.slice(1):"").join("")}function p(n,s){if(s==="snake_case")return n;const e=d(n);return s==="camelCase"||!e?e:e[0].toUpperCase()+e.slice(1)}function m(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class o{constructor(s){this.segments=s}static root(){return new o([])}static property(s){return o.root().property(s)}property(s){return new o([...this.segments,{kind:"property",name:s}])}index(s){return new o([...this.segments,{kind:"index",index:s}])}prefixedBy(s){return new o([...s.segments,...this.segments])}modelPath(){return this.render(s=>s)}nativePath(){return this.render(d)}instancePath(s="camelCase"){return this.segments.map(e=>e.kind==="index"?String(e.index):m(p(e.name,s))).map(e=>`/${e}`).join("")}toString(){return this.nativePath()}render(s){let e="";for(const t of this.segments)t.kind==="index"?e+=`[${t.index}]`:e+=`${e?".":""}${s(t.name)}`;return e}}export{V as E,o as O}; diff --git a/assets/orders-CQOGX0kN.js b/dist/assets/orders-BIvSfQqM.js similarity index 99% rename from assets/orders-CQOGX0kN.js rename to dist/assets/orders-BIvSfQqM.js index 7d712fbdeea59f2a682869956b591f9018f3c8d5..aab4e2a829e978be0cb9595d8597ed94fb5e0dcf 100644 --- a/assets/orders-CQOGX0kN.js +++ b/dist/assets/orders-BIvSfQqM.js @@ -1,2 +1,2 @@ -import{S as yt,a as A,L as v,M as b,C as L,d as G,e as F,Q as z,R as pt,B as ft,U as gt,D as Ot,c as wt,b as qt}from"./dynamic-search-BBmdgl4H.js";import{E as T,O as w}from"./object-location-xgYMemK6.js";/* empty css */class c extends yt{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,r="id",i="id",s=!0,h){return super.relationQuery(t,e,r,i,s,h)}}class Q{static teaqlTemporaryId=0;id;platform;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--Q.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Customer",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new Q(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new Q({id:String(t)})}static teaqlBootstrapNew(t){return new Q().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Customer",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.customer;(this.id===void 0||!a.isLoaded("customer")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomer(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Customer",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.customer;(this.id===void 0||!y.isLoaded("customer")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomer(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.customer;(this.id===void 0||!g.isLoaded("customer")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomer(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,platform:this.platform,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class B{static teaqlTemporaryId=0;id;customerOrder;productName;quantity;unitPrice;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--B.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const r={...t};Object.assign(this,r),t.customerOrder&&typeof t.customerOrder=="object"&&(this.customerOrder=t.customerOrder instanceof $?t.customerOrder:$.fromRecord(t.customerOrder),this.markLoaded("customerOrder"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const r=new B(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new B({id:String(t)})}static teaqlBootstrapNew(t){return new B().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const p=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(l=>!this.isLoaded(l.member));if(p)throw new L([{ruleId:"invalid_type",location:w.property(p.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o),o.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderItem",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return p.scopeFor(this.teaqlEntityKey()),this;const l=await e.executeMutation(p);for(const[C,f]of Object.entries(o.payload))C!=="id"&&C!=="version"&&this._root.set(this.teaqlEntityKey(),C,f);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();return this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update"),p.scopeFor(m),e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer_order:this.customerOrder,product_name:this.productName,quantity:this.quantity,unit_price:this.unitPrice,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateProductName(t){return this.productName=t,this.markLoaded("productName"),this._root.set(this.teaqlEntityKey(),"product_name",t),this}updateQuantity(t){return this.quantity=t,this.markLoaded("quantity"),this._root.set(this.teaqlEntityKey(),"quantity",t),this}updateUnitPrice(t){return this.unitPrice=t,this.markLoaded("unitPrice"),this._root.set(this.teaqlEntityKey(),"unit_price",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomerOrder(t){return this.customerOrder=t?.id??t,this.markLoaded("customerOrder"),this._root.set(this.teaqlEntityKey(),"customer_order",this.customerOrder),this}}class ${static teaqlTemporaryId=0;id;customer;status;orderNumber;orderDate;totalAmount;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--$.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderItemList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderItemList,Object.assign(this,r),t.customer&&typeof t.customer=="object"&&(this.customer=t.customer instanceof Q?t.customer:Q.fromRecord(t.customer),this.markLoaded("customer")),t.status&&typeof t.status=="object"&&(this.status=t.status instanceof S?t.status:S.fromRecord(t.status),this.markLoaded("status")),Array.isArray(t.orderItemList)){const i=t.orderItemList;this._orderItemList=new A(i.map(s=>s instanceof B?s:B.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"CustomerOrder",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new $(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new $({id:String(t)})}static teaqlBootstrapNew(t){return new $().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"CustomerOrder",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderItemList.entries()){a.teaqlAttachRoot(this._root);const u=a.customerOrder;(this.id===void 0||!a.isLoaded("customerOrder")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomerOrder(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_item_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"CustomerOrder",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderItemList.entries()){y.teaqlAttachRoot(this._root);const O=y.customerOrder;(this.id===void 0||!y.isLoaded("customerOrder")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomerOrder(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_item_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderItemList.entries()){g.teaqlAttachRoot(this._root);const y=g.customerOrder;(this.id===void 0||!g.isLoaded("customerOrder")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomerOrder(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_item_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer:this.customer,status:this.status,order_number:this.orderNumber,order_date:this.orderDate,total_amount:this.totalAmount,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateOrderNumber(t){return this.orderNumber=t,this.markLoaded("orderNumber"),this._root.set(this.teaqlEntityKey(),"order_number",t),this}updateOrderDate(t){return this.orderDate=t,this.markLoaded("orderDate"),this._root.set(this.teaqlEntityKey(),"order_date",t),this}updateTotalAmount(t){return this.totalAmount=t,this.markLoaded("totalAmount"),this._root.set(this.teaqlEntityKey(),"total_amount",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomer(t){return this.customer=t?.id??t,this.markLoaded("customer"),this._root.set(this.teaqlEntityKey(),"customer",this.customer),this}updateStatus(t){return this.status=t?.id??t,this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToNew(){return this.status="1001",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToPaid(){return this.status="1002",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToCancelled(){return this.status="1003",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}orderItemList(){return this._orderItemList}}class S{static teaqlTemporaryId=0;platform;id;name;code;color;displayOrder;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--S.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderStatus",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new S(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new S({id:String(t)})}static teaqlBootstrapNew(t){return new S().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderStatus",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.status;(this.id===void 0||!a.isLoaded("status")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateStatus(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderStatus",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.status;(this.id===void 0||!y.isLoaded("status")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateStatus(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.status;(this.id===void 0||!g.isLoaded("status")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateStatus(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{platform:this.platform,id:this.id,name:this.name,code:this.code,color:this.color,display_order:this.displayOrder,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateCode(t){return this.code=t,this.markLoaded("code"),this._root.set(this.teaqlEntityKey(),"code",t),this}updateColor(t){return this.color=t,this.markLoaded("color"),this._root.set(this.teaqlEntityKey(),"color",t),this}updateDisplayOrder(t){return this.displayOrder=t,this.markLoaded("displayOrder"),this._root.set(this.teaqlEntityKey(),"display_order",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class N{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--N.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderStatusList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderStatusList,delete r.customerList,Object.assign(this,r),Array.isArray(t.orderStatusList)){const i=t.orderStatusList;this._orderStatusList=new A(i.map(s=>s instanceof S?s:S.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderStatusList")}if(Array.isArray(t.customerList)){const i=t.customerList;this._customerList=new A(i.map(s=>s instanceof Q?s:Q.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderStatusList)e.teaqlAttachRoot(t);for(const e of this._customerList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new N(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new N({id:String(t)})}static teaqlBootstrapNew(t){return new N().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderStatusList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_status_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}for(const[l,a]of this._customerList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Platform",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderStatusList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_status_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}for(const[g,y]of this._customerList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderStatusList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_status_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}for(const[f,g]of this._customerList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}orderStatusList(){return this._orderStatusList}customerList(){return this._customerList}}const J=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({orderStatusList:"OrderStatus",customerList:"Customer"})}),OrderStatus:Object.freeze({fields:Object.freeze({platform:"integer",id:"integer",name:"string",code:"string",color:"string",display_order:"integer",displayOrder:"integer",version:"integer"}),queryFields:Object.freeze({platform:"platform",id:"id",name:"name",code:"code",color:"color",display_order:"displayOrder",displayOrder:"displayOrder",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),Customer:Object.freeze({fields:Object.freeze({id:"integer",platform:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",platform:"platform",name:"name",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),CustomerOrder:Object.freeze({fields:Object.freeze({id:"integer",customer:"integer",status:"integer",order_number:"string",orderNumber:"string",order_date:"date",orderDate:"date",total_amount:"decimal",totalAmount:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer:"customer",status:"status",order_number:"orderNumber",orderNumber:"orderNumber",order_date:"orderDate",orderDate:"orderDate",total_amount:"totalAmount",totalAmount:"totalAmount",version:"version"}),relations:Object.freeze({customer:"Customer",status:"OrderStatus",orderItemList:"OrderItem"})}),OrderItem:Object.freeze({fields:Object.freeze({id:"integer",customer_order:"integer",customerOrder:"integer",product_name:"string",productName:"string",quantity:"integer",unit_price:"decimal",unitPrice:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer_order:"customerOrder",customerOrder:"customerOrder",product_name:"productName",productName:"productName",quantity:"quantity",unit_price:"unitPrice",unitPrice:"unitPrice",version:"version"}),relations:Object.freeze({customer_order:"CustomerOrder",customerOrder:"CustomerOrder"})})});class st{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new vt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectOrderStatusListWith(t){return this.query.relationQuery("orderStatusList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectOrderStatusListWith",relation:"orderStatusList"}),this}selectCustomerListWith(t){return this.query.relationQuery("customerList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectCustomerListWith",relation:"customerList"}),this}haveOrderStatuses(){return this.withOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}haveNoOrderStatuses(){return this.withoutOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}withOrderStatusListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutOrderStatusListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}haveCustomers(){return this.withCustomerListMatching({toQuery:()=>new c("Customer")})}haveNoCustomers(){return this.withoutCustomerListMatching({toQuery:()=>new c("Customer")})}withCustomerListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutCustomerListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countOrderStatuses(){return this.countOrderStatusesAs("countOrderStatuses")}countOrderStatusesAs(t){const e=new c("OrderStatus").filter({version:{$gte:1}});return this.countOrderStatusesWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderStatusesAs",relation:"orderStatusList",alias:t},this}countOrderStatusesWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"relation-count",method:"countOrderStatusesWith",relation:"orderStatusList",alias:t}),this}minDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.minDisplayOrderOfOrderStatusesAs("minOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}minDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"minDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}maxDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.maxDisplayOrderOfOrderStatusesAs("maxOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}maxDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"maxDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sumDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sumDisplayOrderOfOrderStatusesAs("sumOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sumDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sumDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}avgDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.avgDisplayOrderOfOrderStatusesAs("avgOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}avgDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"avgDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}standardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.standardDeviationDisplayOrderOfOrderStatusesAs("standardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}standardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"standardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs("squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sampleVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sampleVarianceDisplayOrderOfOrderStatusesAs("sampleVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sampleVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sampleVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}samplePopulationVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs("samplePopulationVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}samplePopulationVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}countCustomers(){return this.countCustomersAs("countCustomers")}countCustomersAs(t){const e=new c("Customer").filter({version:{$gte:1}});return this.countCustomersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomersAs",relation:"customerList",alias:t},this}countCustomersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerList",t,r,!0,{kind:"relation-count",method:"countCustomersWith",relation:"customerList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof N?o:N.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof N?u:N.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof N?o:N.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class vt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new N}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ot{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderStatus"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new It(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["platform","id","name","code","color","displayOrder","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectCode(){return this.query.select(["code"]),this}selectColor(){return this.query.select(["color"]),this}selectDisplayOrder(){return this.query.select(["displayOrder"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","status",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"status"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"status"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withCodeContaining(t){return this.filters.push({code:{$contains:t}}),this}withCodeIs(t){return this.filters.push({code:{$eq:t}}),this}withCodeIsNot(t){return this.filters.push({code:{$ne:t}}),this}withCodeIn(...t){return this.filters.push({code:{$in:t}}),this}withCodeNotIn(...t){return this.filters.push({code:{$notIn:t}}),this}withCodeGreaterThan(t){return this.filters.push({code:{$gt:t}}),this}withCodeGreaterThanOrEqualTo(t){return this.filters.push({code:{$gte:t}}),this}withCodeLessThan(t){return this.filters.push({code:{$lt:t}}),this}withCodeLessThanOrEqualTo(t){return this.filters.push({code:{$lte:t}}),this}withCodeBetween(t,e){return this.filters.push({code:{$between:[t,e]}}),this}withCodeIsKnown(){return this.filters.push({code:{$isNull:!1}}),this}withCodeIsUnknown(){return this.filters.push({code:{$isNull:!0}}),this}withCodeNotContaining(t){return this.filters.push({code:{$notContains:t}}),this}withCodeStartingWith(t){return this.filters.push({code:{$startsWith:t}}),this}withCodeNotStartingWith(t){return this.filters.push({code:{$notStartsWith:t}}),this}withCodeEndingWith(t){return this.filters.push({code:{$endsWith:t}}),this}withCodeNotEndingWith(t){return this.filters.push({code:{$notEndsWith:t}}),this}withCodeSoundingLike(t){return this.filters.push({code:{$soundLike:t}}),this}withColorContaining(t){return this.filters.push({color:{$contains:t}}),this}withColorIs(t){return this.filters.push({color:{$eq:t}}),this}withColorIsNot(t){return this.filters.push({color:{$ne:t}}),this}withColorIn(...t){return this.filters.push({color:{$in:t}}),this}withColorNotIn(...t){return this.filters.push({color:{$notIn:t}}),this}withColorGreaterThan(t){return this.filters.push({color:{$gt:t}}),this}withColorGreaterThanOrEqualTo(t){return this.filters.push({color:{$gte:t}}),this}withColorLessThan(t){return this.filters.push({color:{$lt:t}}),this}withColorLessThanOrEqualTo(t){return this.filters.push({color:{$lte:t}}),this}withColorBetween(t,e){return this.filters.push({color:{$between:[t,e]}}),this}withColorIsKnown(){return this.filters.push({color:{$isNull:!1}}),this}withColorIsUnknown(){return this.filters.push({color:{$isNull:!0}}),this}withColorNotContaining(t){return this.filters.push({color:{$notContains:t}}),this}withColorStartingWith(t){return this.filters.push({color:{$startsWith:t}}),this}withColorNotStartingWith(t){return this.filters.push({color:{$notStartsWith:t}}),this}withColorEndingWith(t){return this.filters.push({color:{$endsWith:t}}),this}withColorNotEndingWith(t){return this.filters.push({color:{$notEndsWith:t}}),this}withColorSoundingLike(t){return this.filters.push({color:{$soundLike:t}}),this}withDisplayOrderIs(t){return this.filters.push({displayOrder:{$eq:t}}),this}withDisplayOrderIsNot(t){return this.filters.push({displayOrder:{$ne:t}}),this}withDisplayOrderIn(...t){return this.filters.push({displayOrder:{$in:t}}),this}withDisplayOrderNotIn(...t){return this.filters.push({displayOrder:{$notIn:t}}),this}withDisplayOrderGreaterThan(t){return this.filters.push({displayOrder:{$gt:t}}),this}withDisplayOrderGreaterThanOrEqualTo(t){return this.filters.push({displayOrder:{$gte:t}}),this}withDisplayOrderLessThan(t){return this.filters.push({displayOrder:{$lt:t}}),this}withDisplayOrderLessThanOrEqualTo(t){return this.filters.push({displayOrder:{$lte:t}}),this}withDisplayOrderBetween(t,e){return this.filters.push({displayOrder:{$between:[t,e]}}),this}withDisplayOrderIsKnown(){return this.filters.push({displayOrder:{$isNull:!1}}),this}withDisplayOrderIsUnknown(){return this.filters.push({displayOrder:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByCodeAscending(){return this.query.orderBy("code","asc"),this}orderByCodeDescending(){return this.query.orderBy("code","desc"),this}orderByColorAscending(){return this.query.orderBy("color","asc"),this}orderByColorDescending(){return this.query.orderBy("color","desc"),this}orderByDisplayOrderAscending(){return this.query.orderBy("displayOrder","asc"),this}orderByDisplayOrderDescending(){return this.query.orderBy("displayOrder","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minDisplayOrder(){return this.minDisplayOrderAs("minOfDisplayOrder")}minDisplayOrderAs(t){return this.query.aggregate("min","displayOrder",t),this}maxDisplayOrder(){return this.maxDisplayOrderAs("maxOfDisplayOrder")}maxDisplayOrderAs(t){return this.query.aggregate("max","displayOrder",t),this}sumDisplayOrder(){return this.sumDisplayOrderAs("sumOfDisplayOrder")}sumDisplayOrderAs(t){return this.query.aggregate("sum","displayOrder",t),this}avgDisplayOrder(){return this.avgDisplayOrderAs("avgOfDisplayOrder")}avgDisplayOrderAs(t){return this.query.aggregate("avg","displayOrder",t),this}standardDeviationDisplayOrder(){return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder")}standardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev","displayOrder",t),this}squareRootOfPopulationStandardDeviationDisplayOrder(){return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder")}squareRootOfPopulationStandardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev_pop","displayOrder",t),this}sampleVarianceDisplayOrder(){return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder")}sampleVarianceDisplayOrderAs(t){return this.query.aggregate("var_samp","displayOrder",t),this}samplePopulationVarianceDisplayOrder(){return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder")}samplePopulationVarianceDisplayOrderAs(t){return this.query.aggregate("var_pop","displayOrder",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByCode(){return this.query.groupBy("code"),this}groupByCodeAs(t){return this.query.groupBy("code"),this}groupByColor(){return this.query.groupBy("color"),this}groupByColorAs(t){return this.query.groupBy("color"),this}groupByDisplayOrder(){return this.query.groupBy("displayOrder"),this}groupByDisplayOrderAs(t){return this.query.groupBy("displayOrder"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof S?o:S.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof S?u:S.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof S?o:S.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class It{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new S}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class nt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Customer"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Lt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","platform","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","customer",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customer"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customer"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof Q?o:Q.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof Q?u:Q.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof Q?o:Q.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class Lt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new Q}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class at{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("CustomerOrder"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new At(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customer","status","orderNumber","orderDate","totalAmount","version"]),this}selectId(){return this.query.select(["id"]),this}selectOrderNumber(){return this.query.select(["orderNumber"]),this}selectOrderDate(){return this.query.select(["orderDate"]),this}selectTotalAmount(){return this.query.select(["totalAmount"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerWith(t){return this.query.select(["customer"]),this.query.relationQuery("customer",t.toQuery(),"customer","id",!1,{kind:"relation-select",method:"selectCustomerWith",relation:"customer"}),this}selectStatusWith(t){return this.query.select(["status"]),this.query.relationQuery("status",t.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this}withCustomerMatching(t){return this.filters.push({customer:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerMatching(t){return this.filters.push({customer:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withStatusMatching(t){return this.filters.push({status:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutStatusMatching(t){return this.filters.push({status:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectOrderItemListWith(t){return this.query.relationQuery("orderItemList",t.toQuery(),"id","customerOrder",!0,{kind:"relation-select",method:"selectOrderItemListWith",relation:"orderItemList"}),this}haveOrderItems(){return this.withOrderItemListMatching({toQuery:()=>new c("OrderItem")})}haveNoOrderItems(){return this.withoutOrderItemListMatching({toQuery:()=>new c("OrderItem")})}withOrderItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}withoutOrderItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}countOrderItems(){return this.countOrderItemsAs("countOrderItems")}countOrderItemsAs(t){const e=new c("OrderItem").filter({version:{$gte:1}});return this.countOrderItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderItemsAs",relation:"orderItemList",alias:t},this}countOrderItemsWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"relation-count",method:"countOrderItemsWith",relation:"orderItemList",alias:t}),this}minQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minQuantityOfOrderItemsAs("minOfQuantityOfOrderItems",{toQuery:()=>t})}minQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxQuantityOfOrderItemsAs("maxOfQuantityOfOrderItems",{toQuery:()=>t})}maxQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumQuantityOfOrderItemsAs("sumOfQuantityOfOrderItems",{toQuery:()=>t})}sumQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgQuantityOfOrderItemsAs("avgOfQuantityOfOrderItems",{toQuery:()=>t})}avgQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationQuantityOfOrderItemsAs("standardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}standardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceQuantityOfOrderItemsAs("sampleVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}sampleVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceQuantityOfOrderItemsAs("samplePopulationVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}minUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minUnitPriceOfOrderItemsAs("minOfUnitPriceOfOrderItems",{toQuery:()=>t})}minUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxUnitPriceOfOrderItemsAs("maxOfUnitPriceOfOrderItems",{toQuery:()=>t})}maxUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumUnitPriceOfOrderItemsAs("sumOfUnitPriceOfOrderItems",{toQuery:()=>t})}sumUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgUnitPriceOfOrderItemsAs("avgOfUnitPriceOfOrderItems",{toQuery:()=>t})}avgUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationUnitPriceOfOrderItemsAs("standardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}standardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceUnitPriceOfOrderItemsAs("sampleVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}sampleVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceUnitPriceOfOrderItemsAs("samplePopulationVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomer(t){return this.filters.push({customer:{$eq:t}}),this}filterByCustomerIn(...t){return this.filters.push({customer:{$in:t}}),this}withCustomerIsKnown(){return this.filters.push({customer:{$isNull:!1}}),this}withCustomerIsUnknown(){return this.filters.push({customer:{$isNull:!0}}),this}filterByStatus(t){return this.filters.push({status:{$eq:t}}),this}filterByStatusIn(...t){return this.filters.push({status:{$in:t}}),this}withStatusIsKnown(){return this.filters.push({status:{$isNull:!1}}),this}withStatusIsUnknown(){return this.filters.push({status:{$isNull:!0}}),this}withStatusIsNew(){return this.filters.push({status:{$eq:"1001"}}),this}withStatusIsPaid(){return this.filters.push({status:{$eq:"1002"}}),this}withStatusIsCancelled(){return this.filters.push({status:{$eq:"1003"}}),this}withOrderNumberContaining(t){return this.filters.push({orderNumber:{$contains:t}}),this}withOrderNumberIs(t){return this.filters.push({orderNumber:{$eq:t}}),this}withOrderNumberIsNot(t){return this.filters.push({orderNumber:{$ne:t}}),this}withOrderNumberIn(...t){return this.filters.push({orderNumber:{$in:t}}),this}withOrderNumberNotIn(...t){return this.filters.push({orderNumber:{$notIn:t}}),this}withOrderNumberGreaterThan(t){return this.filters.push({orderNumber:{$gt:t}}),this}withOrderNumberGreaterThanOrEqualTo(t){return this.filters.push({orderNumber:{$gte:t}}),this}withOrderNumberLessThan(t){return this.filters.push({orderNumber:{$lt:t}}),this}withOrderNumberLessThanOrEqualTo(t){return this.filters.push({orderNumber:{$lte:t}}),this}withOrderNumberBetween(t,e){return this.filters.push({orderNumber:{$between:[t,e]}}),this}withOrderNumberIsKnown(){return this.filters.push({orderNumber:{$isNull:!1}}),this}withOrderNumberIsUnknown(){return this.filters.push({orderNumber:{$isNull:!0}}),this}withOrderNumberNotContaining(t){return this.filters.push({orderNumber:{$notContains:t}}),this}withOrderNumberStartingWith(t){return this.filters.push({orderNumber:{$startsWith:t}}),this}withOrderNumberNotStartingWith(t){return this.filters.push({orderNumber:{$notStartsWith:t}}),this}withOrderNumberEndingWith(t){return this.filters.push({orderNumber:{$endsWith:t}}),this}withOrderNumberNotEndingWith(t){return this.filters.push({orderNumber:{$notEndsWith:t}}),this}withOrderNumberSoundingLike(t){return this.filters.push({orderNumber:{$soundLike:t}}),this}withOrderDateIs(t){return this.filters.push({orderDate:{$eq:t}}),this}withOrderDateIsNot(t){return this.filters.push({orderDate:{$ne:t}}),this}withOrderDateIn(...t){return this.filters.push({orderDate:{$in:t}}),this}withOrderDateNotIn(...t){return this.filters.push({orderDate:{$notIn:t}}),this}withOrderDateGreaterThan(t){return this.filters.push({orderDate:{$gt:t}}),this}withOrderDateGreaterThanOrEqualTo(t){return this.filters.push({orderDate:{$gte:t}}),this}withOrderDateLessThan(t){return this.filters.push({orderDate:{$lt:t}}),this}withOrderDateLessThanOrEqualTo(t){return this.filters.push({orderDate:{$lte:t}}),this}withOrderDateBetween(t,e){return this.filters.push({orderDate:{$between:[t,e]}}),this}withOrderDateIsKnown(){return this.filters.push({orderDate:{$isNull:!1}}),this}withOrderDateIsUnknown(){return this.filters.push({orderDate:{$isNull:!0}}),this}withTotalAmountIs(t){return this.filters.push({totalAmount:{$eq:t}}),this}withTotalAmountIsNot(t){return this.filters.push({totalAmount:{$ne:t}}),this}withTotalAmountIn(...t){return this.filters.push({totalAmount:{$in:t}}),this}withTotalAmountNotIn(...t){return this.filters.push({totalAmount:{$notIn:t}}),this}withTotalAmountGreaterThan(t){return this.filters.push({totalAmount:{$gt:t}}),this}withTotalAmountGreaterThanOrEqualTo(t){return this.filters.push({totalAmount:{$gte:t}}),this}withTotalAmountLessThan(t){return this.filters.push({totalAmount:{$lt:t}}),this}withTotalAmountLessThanOrEqualTo(t){return this.filters.push({totalAmount:{$lte:t}}),this}withTotalAmountBetween(t,e){return this.filters.push({totalAmount:{$between:[t,e]}}),this}withTotalAmountIsKnown(){return this.filters.push({totalAmount:{$isNull:!1}}),this}withTotalAmountIsUnknown(){return this.filters.push({totalAmount:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByOrderNumberAscending(){return this.query.orderBy("orderNumber","asc"),this}orderByOrderNumberDescending(){return this.query.orderBy("orderNumber","desc"),this}orderByOrderDateAscending(){return this.query.orderBy("orderDate","asc"),this}orderByOrderDateDescending(){return this.query.orderBy("orderDate","desc"),this}orderByTotalAmountAscending(){return this.query.orderBy("totalAmount","asc"),this}orderByTotalAmountDescending(){return this.query.orderBy("totalAmount","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minTotalAmount(){return this.minTotalAmountAs("minOfTotalAmount")}minTotalAmountAs(t){return this.query.aggregate("min","totalAmount",t),this}maxTotalAmount(){return this.maxTotalAmountAs("maxOfTotalAmount")}maxTotalAmountAs(t){return this.query.aggregate("max","totalAmount",t),this}sumTotalAmount(){return this.sumTotalAmountAs("sumOfTotalAmount")}sumTotalAmountAs(t){return this.query.aggregate("sum","totalAmount",t),this}avgTotalAmount(){return this.avgTotalAmountAs("avgOfTotalAmount")}avgTotalAmountAs(t){return this.query.aggregate("avg","totalAmount",t),this}standardDeviationTotalAmount(){return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount")}standardDeviationTotalAmountAs(t){return this.query.aggregate("stddev","totalAmount",t),this}squareRootOfPopulationStandardDeviationTotalAmount(){return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount")}squareRootOfPopulationStandardDeviationTotalAmountAs(t){return this.query.aggregate("stddev_pop","totalAmount",t),this}sampleVarianceTotalAmount(){return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount")}sampleVarianceTotalAmountAs(t){return this.query.aggregate("var_samp","totalAmount",t),this}samplePopulationVarianceTotalAmount(){return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount")}samplePopulationVarianceTotalAmountAs(t){return this.query.aggregate("var_pop","totalAmount",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomer(){return this.query.groupBy("customer"),this}groupByCustomerAs(t){return this.query.groupBy("customer"),this}groupByStatus(){return this.query.groupBy("status"),this}groupByStatusAs(t){return this.query.groupBy("status"),this}groupByOrderNumber(){return this.query.groupBy("orderNumber"),this}groupByOrderNumberAs(t){return this.query.groupBy("orderNumber"),this}groupByOrderDate(){return this.query.groupBy("orderDate"),this}groupByOrderDateAs(t){return this.query.groupBy("orderDate"),this}groupByTotalAmount(){return this.query.groupBy("totalAmount"),this}groupByTotalAmountAs(t){return this.query.groupBy("totalAmount"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerAs(t,e,r=!0){return this.query.facetBy(t,"customer",e,r,{kind:"facet",method:"facetByCustomerAs",relation:"customer",alias:t}),this}facetByStatusAs(t,e,r=!0){return this.query.facetBy(t,"status",e,r,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof $?o:$.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof $?u:$.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof $?o:$.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class At{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new $}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ut{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new _t(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customerOrder","productName","quantity","unitPrice","version"]),this}selectId(){return this.query.select(["id"]),this}selectProductName(){return this.query.select(["productName"]),this}selectQuantity(){return this.query.select(["quantity"]),this}selectUnitPrice(){return this.query.select(["unitPrice"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerOrderWith(t){return this.query.select(["customerOrder"]),this.query.relationQuery("customerOrder",t.toQuery(),"customerOrder","id",!1,{kind:"relation-select",method:"selectCustomerOrderWith",relation:"customerOrder"}),this}withCustomerOrderMatching(t){return this.filters.push({customerOrder:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerOrderMatching(t){return this.filters.push({customerOrder:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomerOrder(t){return this.filters.push({customerOrder:{$eq:t}}),this}filterByCustomerOrderIn(...t){return this.filters.push({customerOrder:{$in:t}}),this}withCustomerOrderIsKnown(){return this.filters.push({customerOrder:{$isNull:!1}}),this}withCustomerOrderIsUnknown(){return this.filters.push({customerOrder:{$isNull:!0}}),this}withProductNameContaining(t){return this.filters.push({productName:{$contains:t}}),this}withProductNameIs(t){return this.filters.push({productName:{$eq:t}}),this}withProductNameIsNot(t){return this.filters.push({productName:{$ne:t}}),this}withProductNameIn(...t){return this.filters.push({productName:{$in:t}}),this}withProductNameNotIn(...t){return this.filters.push({productName:{$notIn:t}}),this}withProductNameGreaterThan(t){return this.filters.push({productName:{$gt:t}}),this}withProductNameGreaterThanOrEqualTo(t){return this.filters.push({productName:{$gte:t}}),this}withProductNameLessThan(t){return this.filters.push({productName:{$lt:t}}),this}withProductNameLessThanOrEqualTo(t){return this.filters.push({productName:{$lte:t}}),this}withProductNameBetween(t,e){return this.filters.push({productName:{$between:[t,e]}}),this}withProductNameIsKnown(){return this.filters.push({productName:{$isNull:!1}}),this}withProductNameIsUnknown(){return this.filters.push({productName:{$isNull:!0}}),this}withProductNameNotContaining(t){return this.filters.push({productName:{$notContains:t}}),this}withProductNameStartingWith(t){return this.filters.push({productName:{$startsWith:t}}),this}withProductNameNotStartingWith(t){return this.filters.push({productName:{$notStartsWith:t}}),this}withProductNameEndingWith(t){return this.filters.push({productName:{$endsWith:t}}),this}withProductNameNotEndingWith(t){return this.filters.push({productName:{$notEndsWith:t}}),this}withProductNameSoundingLike(t){return this.filters.push({productName:{$soundLike:t}}),this}withQuantityIs(t){return this.filters.push({quantity:{$eq:t}}),this}withQuantityIsNot(t){return this.filters.push({quantity:{$ne:t}}),this}withQuantityIn(...t){return this.filters.push({quantity:{$in:t}}),this}withQuantityNotIn(...t){return this.filters.push({quantity:{$notIn:t}}),this}withQuantityGreaterThan(t){return this.filters.push({quantity:{$gt:t}}),this}withQuantityGreaterThanOrEqualTo(t){return this.filters.push({quantity:{$gte:t}}),this}withQuantityLessThan(t){return this.filters.push({quantity:{$lt:t}}),this}withQuantityLessThanOrEqualTo(t){return this.filters.push({quantity:{$lte:t}}),this}withQuantityBetween(t,e){return this.filters.push({quantity:{$between:[t,e]}}),this}withQuantityIsKnown(){return this.filters.push({quantity:{$isNull:!1}}),this}withQuantityIsUnknown(){return this.filters.push({quantity:{$isNull:!0}}),this}withUnitPriceIs(t){return this.filters.push({unitPrice:{$eq:t}}),this}withUnitPriceIsNot(t){return this.filters.push({unitPrice:{$ne:t}}),this}withUnitPriceIn(...t){return this.filters.push({unitPrice:{$in:t}}),this}withUnitPriceNotIn(...t){return this.filters.push({unitPrice:{$notIn:t}}),this}withUnitPriceGreaterThan(t){return this.filters.push({unitPrice:{$gt:t}}),this}withUnitPriceGreaterThanOrEqualTo(t){return this.filters.push({unitPrice:{$gte:t}}),this}withUnitPriceLessThan(t){return this.filters.push({unitPrice:{$lt:t}}),this}withUnitPriceLessThanOrEqualTo(t){return this.filters.push({unitPrice:{$lte:t}}),this}withUnitPriceBetween(t,e){return this.filters.push({unitPrice:{$between:[t,e]}}),this}withUnitPriceIsKnown(){return this.filters.push({unitPrice:{$isNull:!1}}),this}withUnitPriceIsUnknown(){return this.filters.push({unitPrice:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByProductNameAscending(){return this.query.orderBy("productName","asc"),this}orderByProductNameDescending(){return this.query.orderBy("productName","desc"),this}orderByQuantityAscending(){return this.query.orderBy("quantity","asc"),this}orderByQuantityDescending(){return this.query.orderBy("quantity","desc"),this}orderByUnitPriceAscending(){return this.query.orderBy("unitPrice","asc"),this}orderByUnitPriceDescending(){return this.query.orderBy("unitPrice","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minQuantity(){return this.minQuantityAs("minOfQuantity")}minQuantityAs(t){return this.query.aggregate("min","quantity",t),this}maxQuantity(){return this.maxQuantityAs("maxOfQuantity")}maxQuantityAs(t){return this.query.aggregate("max","quantity",t),this}sumQuantity(){return this.sumQuantityAs("sumOfQuantity")}sumQuantityAs(t){return this.query.aggregate("sum","quantity",t),this}avgQuantity(){return this.avgQuantityAs("avgOfQuantity")}avgQuantityAs(t){return this.query.aggregate("avg","quantity",t),this}standardDeviationQuantity(){return this.standardDeviationQuantityAs("standardDeviationOfQuantity")}standardDeviationQuantityAs(t){return this.query.aggregate("stddev","quantity",t),this}squareRootOfPopulationStandardDeviationQuantity(){return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity")}squareRootOfPopulationStandardDeviationQuantityAs(t){return this.query.aggregate("stddev_pop","quantity",t),this}sampleVarianceQuantity(){return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity")}sampleVarianceQuantityAs(t){return this.query.aggregate("var_samp","quantity",t),this}samplePopulationVarianceQuantity(){return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity")}samplePopulationVarianceQuantityAs(t){return this.query.aggregate("var_pop","quantity",t),this}minUnitPrice(){return this.minUnitPriceAs("minOfUnitPrice")}minUnitPriceAs(t){return this.query.aggregate("min","unitPrice",t),this}maxUnitPrice(){return this.maxUnitPriceAs("maxOfUnitPrice")}maxUnitPriceAs(t){return this.query.aggregate("max","unitPrice",t),this}sumUnitPrice(){return this.sumUnitPriceAs("sumOfUnitPrice")}sumUnitPriceAs(t){return this.query.aggregate("sum","unitPrice",t),this}avgUnitPrice(){return this.avgUnitPriceAs("avgOfUnitPrice")}avgUnitPriceAs(t){return this.query.aggregate("avg","unitPrice",t),this}standardDeviationUnitPrice(){return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice")}standardDeviationUnitPriceAs(t){return this.query.aggregate("stddev","unitPrice",t),this}squareRootOfPopulationStandardDeviationUnitPrice(){return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice")}squareRootOfPopulationStandardDeviationUnitPriceAs(t){return this.query.aggregate("stddev_pop","unitPrice",t),this}sampleVarianceUnitPrice(){return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice")}sampleVarianceUnitPriceAs(t){return this.query.aggregate("var_samp","unitPrice",t),this}samplePopulationVarianceUnitPrice(){return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice")}samplePopulationVarianceUnitPriceAs(t){return this.query.aggregate("var_pop","unitPrice",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomerOrder(){return this.query.groupBy("customerOrder"),this}groupByCustomerOrderAs(t){return this.query.groupBy("customerOrder"),this}groupByProductName(){return this.query.groupBy("productName"),this}groupByProductNameAs(t){return this.query.groupBy("productName"),this}groupByQuantity(){return this.query.groupBy("quantity"),this}groupByQuantityAs(t){return this.query.groupBy("quantity"),this}groupByUnitPrice(){return this.query.groupBy("unitPrice"),this}groupByUnitPriceAs(t){return this.query.groupBy("unitPrice"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerOrderAs(t,e,r=!0){return this.query.facetBy(t,"customerOrder",e,r,{kind:"facet",method:"facetByCustomerOrderAs",relation:"customerOrder",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof B?o:B.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof B?u:B.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof B?o:B.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class _t{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new B}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class E{static platforms(){return new st(!1)}static platformsWithMinimalFields(){return new st(!0)}static orderStatuses(){return new ot(!1)}static orderStatusesWithMinimalFields(){return new ot(!0)}static customers(){return new nt(!1)}static customersWithMinimalFields(){return new nt(!0)}static customerOrders(){return new at(!1)}static customerOrdersWithMinimalFields(){return new at(!0)}static orderItems(){return new ut(!1)}static orderItemsWithMinimalFields(){return new ut(!0)}}class I extends Error{constructor(t,e,r){const i=`select${r.charAt(0).toUpperCase()}${r.slice(1)}(...)`,s={error:"TeaQLNotLoadedError",root:t,accessPath:e.split("."),breakPoint:r,missingPreload:[r],suggestedFix:i,severity:"error",humanMessage:`访问 ${t}.${e} 时缺少预加载。请在查询中加入 ${i}`};super(JSON.stringify(s)),this.root=t,this.accessPath=e,this.breakPoint=r,this.name="TeaQLNotLoadedError",this.details=s}root;accessPath;breakPoint;details}function q(d,t){return d?`${d}.${t}`:t}class n{constructor(t,e=!0,r){this.value=t,this.present=e,this.notLoaded=r}value;present;notLoaded;static missing(){return new n(void 0,!1)}static notLoaded(t){return new n(void 0,!1,t)}eval(){if(this.notLoaded)throw this.notLoaded;return this.present?this.value:void 0}isPresent(){if(this.notLoaded)throw this.notLoaded;return this.present}orElse(t){const e=this.eval();return this.present&&e!=null?e:t}}class x{constructor(t,e="Platform(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}orderStatusList(){const t=q(this.path,"orderStatusList");return this.notLoaded?new U([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderStatusList")?new U(this.value.orderStatusList(),this.root,t):new U([],this.root,t,!1,new I(this.root,t,"orderStatusList")):U.missing(this.root,t)}customerList(){const t=q(this.path,"customerList");return this.notLoaded?new M([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerList")?new M(this.value.customerList(),this.root,t):new M([],this.root,t,!1,new I(this.root,t,"customerList")):M.missing(this.root,t)}}class V{constructor(t,e="OrderStatus(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}code(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"code");return this.value.isLoaded("code")?new n(this.value.code):n.notLoaded(new I(this.root,t,"code"))}color(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"color");return this.value.isLoaded("color")?new n(this.value.color):n.notLoaded(new I(this.root,t,"color"))}displayOrder(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"displayOrder");return this.value.isLoaded("displayOrder")?new n(this.value.displayOrder):n.notLoaded(new I(this.root,t,"displayOrder"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class W{constructor(t,e="Customer(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class K{constructor(t,e="CustomerOrder(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}orderNumber(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderNumber");return this.value.isLoaded("orderNumber")?new n(this.value.orderNumber):n.notLoaded(new I(this.root,t,"orderNumber"))}orderDate(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderDate");return this.value.isLoaded("orderDate")?new n(this.value.orderDate):n.notLoaded(new I(this.root,t,"orderDate"))}totalAmount(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"totalAmount");return this.value.isLoaded("totalAmount")?new n(this.value.totalAmount):n.notLoaded(new I(this.root,t,"totalAmount"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customer");if(!this.value.isLoaded("customer"))return n.notLoaded(new I(this.root,t,"customer"));const e=this.value.customer;return new n(e instanceof Q?e.id:e)}statusId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"status");if(!this.value.isLoaded("status"))return n.notLoaded(new I(this.root,t,"status"));const e=this.value.status;return new n(e instanceof S?e.id:e)}customer(){const t=q(this.path,"customer");if(this.notLoaded)return new W(void 0,this.root,t,this.notLoaded);if(!this.value)return new W(void 0,this.root,t);if(!this.value.isLoaded("customer"))return new W(void 0,this.root,t,new I(this.root,t,"customer"));const e=this.value.customer,r=e==null?void 0:e instanceof Q?e:Q.fromRecord({id:e});return new W(r,this.root,t)}status(){const t=q(this.path,"status");if(this.notLoaded)return new V(void 0,this.root,t,this.notLoaded);if(!this.value)return new V(void 0,this.root,t);if(!this.value.isLoaded("status"))return new V(void 0,this.root,t,new I(this.root,t,"status"));const e=this.value.status,r=e==null?void 0:e instanceof S?e:S.fromRecord({id:e});return new V(r,this.root,t)}orderItemList(){const t=q(this.path,"orderItemList");return this.notLoaded?new j([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderItemList")?new j(this.value.orderItemList(),this.root,t):new j([],this.root,t,!1,new I(this.root,t,"orderItemList")):j.missing(this.root,t)}}class H{constructor(t,e="OrderItem(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}productName(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"productName");return this.value.isLoaded("productName")?new n(this.value.productName):n.notLoaded(new I(this.root,t,"productName"))}quantity(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"quantity");return this.value.isLoaded("quantity")?new n(this.value.quantity):n.notLoaded(new I(this.root,t,"quantity"))}unitPrice(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"unitPrice");return this.value.isLoaded("unitPrice")?new n(this.value.unitPrice):n.notLoaded(new I(this.root,t,"unitPrice"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerOrderId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customerOrder");if(!this.value.isLoaded("customerOrder"))return n.notLoaded(new I(this.root,t,"customerOrder"));const e=this.value.customerOrder;return new n(e instanceof $?e.id:e)}customerOrder(){const t=q(this.path,"customerOrder");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded);if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("customerOrder"))return new K(void 0,this.root,t,new I(this.root,t,"customerOrder"));const e=this.value.customerOrder,r=e==null?void 0:e instanceof $?e:$.fromRecord({id:e});return new K(r,this.root,t)}}class U{constructor(t,e="OrderStatus(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new U([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new V(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new V(void 0,this.root,e):new V(this.items[t],this.root,e)}}class M{constructor(t,e="Customer(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new M([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new W(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new W(void 0,this.root,e):new W(this.items[t],this.root,e)}}class k{constructor(t,e="CustomerOrder(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new k([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new K(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new K(void 0,this.root,e):new K(this.items[t],this.root,e)}}class j{constructor(t,e="OrderItem(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new j([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new H(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new H(void 0,this.root,e):new H(this.items[t],this.root,e)}}class et{static platform(t){return new x(t,`Platform(id=${t?.id??"null"})`)}static orderStatus(t){return new V(t,`OrderStatus(id=${t?.id??"null"})`)}static customer(t){return new W(t,`Customer(id=${t?.id??"null"})`)}static customerOrder(t){return new K(t,`CustomerOrder(id=${t?.id??"null"})`)}static orderItem(t){return new H(t,`OrderItem(id=${t?.id??"null"})`)}}const ht={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{orderStatusList:{targetEntity:"OrderStatus",localKey:"id",foreignKey:"platform",many:!0},customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platform",many:!0}}},OrderStatus:{table:"order_status_data",auditMaskFields:[],columns:{platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},code:{columnName:"code",modelName:"code",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},color:{columnName:"color",modelName:"color",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},displayOrder:{columnName:"display_order",modelName:"display_order",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},Customer:{table:"customer_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customer",many:!0}}},CustomerOrder:{table:"customer_order_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customer:{columnName:"customer",modelName:"customer",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},status:{columnName:"status",modelName:"status",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},orderNumber:{columnName:"order_number",modelName:"order_number",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},orderDate:{columnName:"order_date",modelName:"order_date",logPolicy:"plain",logicalType:"date",decode:"date",nullable:!1},totalAmount:{columnName:"total_amount",modelName:"total_amount",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customer:{targetEntity:"Customer",localKey:"customer",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},orderItemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"customerOrder",many:!0}}},OrderItem:{table:"order_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customerOrder:{columnName:"customer_order",modelName:"customer_order",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},productName:{columnName:"product_name",modelName:"product_name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},quantity:{columnName:"quantity",modelName:"quantity",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},unitPrice:{columnName:"unit_price",modelName:"unit_price",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customerOrder:{targetEntity:"CustomerOrder",localKey:"customerOrder",foreignKey:"id",many:!1}}}};async function Ct(d){let t=(await E.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];t||(t=N.teaqlBootstrapNew("1"),t.updateName("Commerce Test Platform"),await t.auditAs("create generated Domain Root Platform").save(d)),d.withActiveRoot({entity:"Platform",id:t.id});let e=(await E.orderStatuses().withIdIs("1001").comment("what: locate generated constant OrderStatus(1001)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!e)e=S.teaqlBootstrapNew("1001"),e.updatePlatform(t),e.updateName("New"),e.updateCode("NEW"),e.updateColor("#94A3B8"),e.updateDisplayOrder(1),await e.auditAs("create model constant OrderStatus(1001)").save(d);else{let s=!1;String(e.platform?.id??e.platform)!==String(t.id)&&(e.updatePlatform(t),s=!0),e.name!=="New"&&(e.updateName("New"),s=!0),e.code!=="NEW"&&(e.updateCode("NEW"),s=!0),e.color!=="#94A3B8"&&(e.updateColor("#94A3B8"),s=!0),e.displayOrder!==1&&(e.updateDisplayOrder(1),s=!0),s&&await e.auditAs("reconcile model constant OrderStatus(1001)").save(d)}let r=(await E.orderStatuses().withIdIs("1002").comment("what: locate generated constant OrderStatus(1002)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!r)r=S.teaqlBootstrapNew("1002"),r.updatePlatform(t),r.updateName("Paid"),r.updateCode("PAID"),r.updateColor("#22C55E"),r.updateDisplayOrder(2),await r.auditAs("create model constant OrderStatus(1002)").save(d);else{let s=!1;String(r.platform?.id??r.platform)!==String(t.id)&&(r.updatePlatform(t),s=!0),r.name!=="Paid"&&(r.updateName("Paid"),s=!0),r.code!=="PAID"&&(r.updateCode("PAID"),s=!0),r.color!=="#22C55E"&&(r.updateColor("#22C55E"),s=!0),r.displayOrder!==2&&(r.updateDisplayOrder(2),s=!0),s&&await r.auditAs("reconcile model constant OrderStatus(1002)").save(d)}let i=(await E.orderStatuses().withIdIs("1003").comment("what: locate generated constant OrderStatus(1003)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!i)i=S.teaqlBootstrapNew("1003"),i.updatePlatform(t),i.updateName("Cancelled"),i.updateCode("CANCELLED"),i.updateColor("#EF4444"),i.updateDisplayOrder(3),await i.auditAs("create model constant OrderStatus(1003)").save(d);else{let s=!1;String(i.platform?.id??i.platform)!==String(t.id)&&(i.updatePlatform(t),s=!0),i.name!=="Cancelled"&&(i.updateName("Cancelled"),s=!0),i.code!=="CANCELLED"&&(i.updateCode("CANCELLED"),s=!0),i.color!=="#EF4444"&&(i.updateColor("#EF4444"),s=!0),i.displayOrder!==3&&(i.updateDisplayOrder(3),s=!0),s&&await i.auditAs("reconcile model constant OrderStatus(1003)").save(d)}}const Pt=new pt(ht,{Platform:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},OrderStatus:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100}),(t.action==="Create"&&t.payload.code===void 0||t.payload.code===null)&&e.push({ruleId:"required",location:w.property("code")}),t.payload.code!=null&&[...String(t.payload.code)].length>100&&e.push({ruleId:"max_length",location:w.property("code"),inputValue:t.payload.code,systemValue:100}),(t.action==="Create"&&t.payload.color===void 0||t.payload.color===null)&&e.push({ruleId:"required",location:w.property("color")}),t.payload.color!=null&&[...String(t.payload.color)].length>100&&e.push({ruleId:"max_length",location:w.property("color"),inputValue:t.payload.color,systemValue:100}),(t.action==="Create"&&t.payload.display_order===void 0||t.payload.display_order===null)&&e.push({ruleId:"required",location:w.property("display_order")})}},Customer:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},CustomerOrder:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer===void 0||t.payload.customer===null)&&e.push({ruleId:"required",location:w.property("customer")}),(t.action==="Create"&&t.payload.status===void 0||t.payload.status===null)&&e.push({ruleId:"required",location:w.property("status")}),(t.action==="Create"&&t.payload.order_number===void 0||t.payload.order_number===null)&&e.push({ruleId:"required",location:w.property("order_number")}),t.payload.order_number!=null&&[...String(t.payload.order_number)].length>100&&e.push({ruleId:"max_length",location:w.property("order_number"),inputValue:t.payload.order_number,systemValue:100}),(t.action==="Create"&&t.payload.order_date===void 0||t.payload.order_date===null)&&e.push({ruleId:"required",location:w.property("order_date")}),(t.action==="Create"&&t.payload.total_amount===void 0||t.payload.total_amount===null)&&e.push({ruleId:"required",location:w.property("total_amount")})}},OrderItem:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer_order===void 0||t.payload.customer_order===null)&&e.push({ruleId:"required",location:w.property("customer_order")}),(t.action==="Create"&&t.payload.product_name===void 0||t.payload.product_name===null)&&e.push({ruleId:"required",location:w.property("product_name")}),t.payload.product_name!=null&&[...String(t.payload.product_name)].length>100&&e.push({ruleId:"max_length",location:w.property("product_name"),inputValue:t.payload.product_name,systemValue:100}),(t.action==="Create"&&t.payload.quantity===void 0||t.payload.quantity===null)&&e.push({ruleId:"required",location:w.property("quantity")}),(t.action==="Create"&&t.payload.unit_price===void 0||t.payload.unit_price===null)&&e.push({ruleId:"required",location:w.property("unit_price")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Commerce Test Platform"}},constants:[{entity:"OrderStatus",id:"1001",values:{platform:"1",name:"New",code:"NEW",color:"#94A3B8",displayOrder:1}},{entity:"OrderStatus",id:"1002",values:{platform:"1",name:"Paid",code:"PAID",color:"#22C55E",displayOrder:2}},{entity:"OrderStatus",id:"1003",values:{platform:"1",name:"Cancelled",code:"CANCELLED",color:"#EF4444",displayOrder:3}}],ensure:Ct}),it=document.querySelector("#status"),St=document.querySelector("#result"),Nt=document.querySelector("#trace"),$t=document.querySelector("#sql"),bt=document.querySelector("#evidence-rows"),Z=document.querySelector("#persist"),dt=document.querySelector("#logging"),rt=document.querySelector("#reset"),Y=document.querySelector("#query"),lt=document.querySelector("#search"),Tt={filter:{orderNumber:{$contains:"KEEP"}}};let R;Z.checked=localStorage.getItem("teaql-browser-order-storage")==="opfs";async function Qt(d){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await ft.open(t,{...ht},{storage:d,databaseName:"teaql-browser-orders.sqlite3"});e.install(Pt),e.setDiagnosticSQLLogSink(void 0).setMutationLoggingEnabled(!1);const r=Object.freeze({policyId:"browser-order-seed",version:"1",fingerprint:"sha256:browser-order-seed-v1"}),i=new gt().insertResource("dataService",e).withMutationPolicyRegistry(new Ot(()=>({identity:r,review:(s,h)=>h.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new wt(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(i),await i.ensureSchema(),await i.ensureSchema(),{client:e,context:i,evidence:new qt,diagnostics:[]}}async function ct({context:d}){if((await E.customerOrdersWithMinimalFields().limit(1).comment("detect existing order demo").purpose("keep mutation seeding idempotent").executeForList(d)).length)return;const e=(await E.platforms().limit(2).comment("load bootstrap platform").purpose("prepare order demo").executeForList(d))[0],r=E.customers().comment("initialize demo customer").purpose("prepare order demo").newEntity(d);r.updateName("North Star Retail").updatePlatform(e.id),await r.auditAs("seed browser order customer").save(d);for(let i=1;i<=4;i++){const s=E.customerOrders().comment("initialize demo order").purpose("prepare order demo").newEntity(d);s.updateCustomer(r.id).updateOrderNumber(i<4?`KEEP-00${i}`:"DROP-004").updateOrderDate(`2026-10-0${i}`).updateTotalAmount(i<4?i*100:900),i===1?s.updateStatusToNew():s.updateStatusToPaid(),await s.auditAs("seed browser order").save(d);for(let h=1;h<=5;h++){const o=E.orderItems().comment("initialize demo item").purpose("prepare item previews").newEntity(d);o.updateCustomerOrder(s.id).updateProductName(`Box ${h}`).updateQuantity(h).updateUnitPrice(20),await o.auditAs("seed browser order item").save(d)}}}async function tt(d){const t=JSON.parse(lt.value),e=E.customerOrdersWithMinimalFields().filterByJson(t);d.evidence.enableAll(),d.diagnostics.length=0,d.client.setRuntimeTelemetrySink(d.evidence).setQueryLoggingEnabled(dt.checked).setDiagnosticSQLLogSink({write:o=>d.diagnostics.push(o)});const r=await e.countAs("totalOrders").facetByStatusAs("statusCounts",E.orderStatusesWithMinimalFields().selectName().selectColor().countAs("orderCount").sumTotalAmountOfCustomerOrdersAs("orderTotalAmount",E.customerOrdersWithMinimalFields()).orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(E.orderStatusesWithMinimalFields().selectName().selectColor().comment("load status")).selectOrderItemListWith(E.orderItemsWithMinimalFields().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countOrderItemsAs("itemCount").orderByOrderDateDescending().orderByIdDescending().offset(1).limit(1).comment("load order list").purpose("render order list page").executeForList(d.context),i={data:r.data.map(o=>{const p=et.customerOrder(o),l=p.orderItemList().size().eval();if(l==null)throw new Error("Selected item list unexpectedly has a null size");return{id:o.id,version:o.version,orderNumber:p.orderNumber().eval(),orderDate:p.orderDate().eval(),status:{name:p.status().name().eval(),color:p.status().color().eval()},items:Array.from({length:l},(a,u)=>({productName:p.orderItemList().get(u).productName().eval(),quantity:p.orderItemList().get(u).quantity().eval()})),itemCount:o.itemCount}}),metadata:{totalCount:r.totalCount,pageOffset:1,pageSize:1,aggregations:r.data.aggregations,searchWarnings:e.dynamicSearchWarnings},facets:{statusCounts:r.data.facets.statusCounts.map(o=>({id:o.id,name:et.orderStatus(S.fromRecord(o)).name().eval(),color:et.orderStatus(S.fromRecord(o)).color().eval(),orderCount:o.orderCount,orderTotalAmount:o.orderTotalAmount}))}};St.textContent=JSON.stringify(i,null,2);const s=d.evidence.snapshot(),h=s.map(o=>{const p=o.traceChain??[],l=p.filter(m=>m.kind==="purpose"),a=l.length===1?`${l[0].detail}: ${p.filter(m=>m.kind==="comment").map(m=>m.detail).join(" → ")}`:"TraceChain unavailable",u=document.createElement("tr");for(const m of[`${o.elapsedMicros} µs`,o.tracePath.find(C=>C.kind==="request")?.name??"—",a,o.debugSQL]){const C=document.createElement("td");C.textContent=m,u.append(C)}return{row:u,businessTrace:a}});bt.replaceChildren(...h.map(o=>o.row)),Nt.textContent=h.map(o=>o.businessTrace).join(` +import{S as yt,a as A,L as v,M as b,C as L,d as G,e as F,Q as z,R as pt,B as ft,U as gt,D as Ot,c as wt,b as qt}from"./dynamic-search-Ch_QcWVU.js";import{E as T,O as w}from"./object-location-CJfVWqJC.js";/* empty css */class c extends yt{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,r="id",i="id",s=!0,h){return super.relationQuery(t,e,r,i,s,h)}}class Q{static teaqlTemporaryId=0;id;platform;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--Q.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Customer",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new Q(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new Q({id:String(t)})}static teaqlBootstrapNew(t){return new Q().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Customer",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.customer;(this.id===void 0||!a.isLoaded("customer")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomer(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Customer",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.customer;(this.id===void 0||!y.isLoaded("customer")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomer(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.customer;(this.id===void 0||!g.isLoaded("customer")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomer(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,platform:this.platform,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class B{static teaqlTemporaryId=0;id;customerOrder;productName;quantity;unitPrice;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--B.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const r={...t};Object.assign(this,r),t.customerOrder&&typeof t.customerOrder=="object"&&(this.customerOrder=t.customerOrder instanceof $?t.customerOrder:$.fromRecord(t.customerOrder),this.markLoaded("customerOrder"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const r=new B(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new B({id:String(t)})}static teaqlBootstrapNew(t){return new B().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const p=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(l=>!this.isLoaded(l.member));if(p)throw new L([{ruleId:"invalid_type",location:w.property(p.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o),o.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderItem",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return p.scopeFor(this.teaqlEntityKey()),this;const l=await e.executeMutation(p);for(const[C,f]of Object.entries(o.payload))C!=="id"&&C!=="version"&&this._root.set(this.teaqlEntityKey(),C,f);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();return this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update"),p.scopeFor(m),e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer_order:this.customerOrder,product_name:this.productName,quantity:this.quantity,unit_price:this.unitPrice,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateProductName(t){return this.productName=t,this.markLoaded("productName"),this._root.set(this.teaqlEntityKey(),"product_name",t),this}updateQuantity(t){return this.quantity=t,this.markLoaded("quantity"),this._root.set(this.teaqlEntityKey(),"quantity",t),this}updateUnitPrice(t){return this.unitPrice=t,this.markLoaded("unitPrice"),this._root.set(this.teaqlEntityKey(),"unit_price",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomerOrder(t){return this.customerOrder=t?.id??t,this.markLoaded("customerOrder"),this._root.set(this.teaqlEntityKey(),"customer_order",this.customerOrder),this}}class ${static teaqlTemporaryId=0;id;customer;status;orderNumber;orderDate;totalAmount;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--$.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderItemList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderItemList,Object.assign(this,r),t.customer&&typeof t.customer=="object"&&(this.customer=t.customer instanceof Q?t.customer:Q.fromRecord(t.customer),this.markLoaded("customer")),t.status&&typeof t.status=="object"&&(this.status=t.status instanceof S?t.status:S.fromRecord(t.status),this.markLoaded("status")),Array.isArray(t.orderItemList)){const i=t.orderItemList;this._orderItemList=new A(i.map(s=>s instanceof B?s:B.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"CustomerOrder",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new $(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new $({id:String(t)})}static teaqlBootstrapNew(t){return new $().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"CustomerOrder",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderItemList.entries()){a.teaqlAttachRoot(this._root);const u=a.customerOrder;(this.id===void 0||!a.isLoaded("customerOrder")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateCustomerOrder(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_item_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"CustomerOrder",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderItemList.entries()){y.teaqlAttachRoot(this._root);const O=y.customerOrder;(this.id===void 0||!y.isLoaded("customerOrder")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateCustomerOrder(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_item_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderItemList.entries()){g.teaqlAttachRoot(this._root);const y=g.customerOrder;(this.id===void 0||!g.isLoaded("customerOrder")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateCustomerOrder(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_item_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,customer:this.customer,status:this.status,order_number:this.orderNumber,order_date:this.orderDate,total_amount:this.totalAmount,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateOrderNumber(t){return this.orderNumber=t,this.markLoaded("orderNumber"),this._root.set(this.teaqlEntityKey(),"order_number",t),this}updateOrderDate(t){return this.orderDate=t,this.markLoaded("orderDate"),this._root.set(this.teaqlEntityKey(),"order_date",t),this}updateTotalAmount(t){return this.totalAmount=t,this.markLoaded("totalAmount"),this._root.set(this.teaqlEntityKey(),"total_amount",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomer(t){return this.customer=t?.id??t,this.markLoaded("customer"),this._root.set(this.teaqlEntityKey(),"customer",this.customer),this}updateStatus(t){return this.status=t?.id??t,this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToNew(){return this.status="1001",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToPaid(){return this.status="1002",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToCancelled(){return this.status="1003",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}orderItemList(){return this._orderItemList}}class S{static teaqlTemporaryId=0;platform;id;name;code;color;displayOrder;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--S.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.customerOrderList,Object.assign(this,r),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof N?t.platform:N.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const i=t.customerOrderList;this._customerOrderList=new A(i.map(s=>s instanceof $?s:$.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerOrderList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"OrderStatus",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._customerOrderList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new S(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new S({id:String(t)})}static teaqlBootstrapNew(t){return new S().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"OrderStatus",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const u=a.status;(this.id===void 0||!a.isLoaded("status")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updateStatus(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_order_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"OrderStatus",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const O=y.status;(this.id===void 0||!y.isLoaded("status")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updateStatus(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_order_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._customerOrderList.entries()){g.teaqlAttachRoot(this._root);const y=g.status;(this.id===void 0||!g.isLoaded("status")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updateStatus(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_order_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{platform:this.platform,id:this.id,name:this.name,code:this.code,color:this.color,display_order:this.displayOrder,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateCode(t){return this.code=t,this.markLoaded("code"),this._root.set(this.teaqlEntityKey(),"code",t),this}updateColor(t){return this.color=t,this.markLoaded("color"),this._root.set(this.teaqlEntityKey(),"color",t),this}updateDisplayOrder(t){return this.displayOrder=t,this.markLoaded("displayOrder"),this._root.set(this.teaqlEntityKey(),"display_order",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}class N{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new T,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--N.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderStatusList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerList",{value:t?.id?A.empty():new A,writable:!0,enumerable:!1}),t){const r={...t};if(delete r.orderStatusList,delete r.customerList,Object.assign(this,r),Array.isArray(t.orderStatusList)){const i=t.orderStatusList;this._orderStatusList=new A(i.map(s=>s instanceof S?s:S.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("orderStatusList")}if(Array.isArray(t.customerList)){const i=t.customerList;this._customerList=new A(i.map(s=>s instanceof Q?s:Q.fromRecord(s)),{totalCount:i.totalCount,aggregations:i.aggregations,summary:i.summary,facets:i.facets,isLoaded:i.isLoaded??!0}),this.markLoaded("customerList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),v.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._orderStatusList)e.teaqlAttachRoot(t);for(const e of this._customerList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const r=new N(t);return e?r.teaqlAttachRoot(e):r}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new N({id:String(t)})}static teaqlBootstrapNew(t){return new N().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new b(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new b(this._comment),async r=>(this.teaqlPreflightGraph(t,e,r),this.teaqlSaveWithinGraph(t,e,r)))}teaqlPreflightGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&h){const l=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(l)throw new L([{ruleId:"invalid_type",location:w.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const o=r.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);h&&e.preflightMutation(o);const p=o.scopeFor(this.teaqlEntityKey());for(const[l,a]of this._orderStatusList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("order_status_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}for(const[l,a]of this._customerList.entries()){a.teaqlAttachRoot(this._root);const u=a.platform;(this.id===void 0||!a.isLoaded("platform")||(typeof u=="object"&&u!==null?u.id:u)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,p)}catch(m){if(!(m instanceof L))throw m;const C=w.property("customer_list").index(l);throw new L(m.violations.map(f=>({...f,location:f.location.prefixedBy(C)})))}}}async teaqlSaveWithinGraph(t,e,r,i){i||new b(this._comment);const s=this._action,h=this._root.change(this.teaqlEntityKey()),o={entity:"Platform",action:this._action,payload:s==="Update"?h:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},p=r.request(o,i,this._comment).withLoadedSnapshot(v.forEntity(this)??new v);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=p.scopeFor(this.teaqlEntityKey());for(const[g,y]of this._orderStatusList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("order_status_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}for(const[g,y]of this._customerList.entries()){y.teaqlAttachRoot(this._root);const O=y.platform;(this.id===void 0||!y.isLoaded("platform")||(typeof O=="object"&&O!==null?O.id:O)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,f)}catch(_){if(!(_ instanceof L))throw _;const P=w.property("customer_list").index(g);throw new L(_.violations.map(D=>({...D,location:D.location.prefixedBy(P)})))}}return this}const l=await e.executeMutation(p);for(const[f,g]of Object.entries(o.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,g);if(!l.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:v.forEntity(this)},u=this.teaqlEntityKey();Object.assign(this,l.persistedRecord),v.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(u,m),e.afterGraphRollback(()=>{Object.assign(this,a.payload),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,v.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,u)}),this._loadedFields=new Set(Object.keys(l.persistedRecord)),this._fullyLoaded=!1,o.action!=="Delete"&&(this._action="Update");const C=p.scopeFor(m);for(const[f,g]of this._orderStatusList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("order_status_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}for(const[f,g]of this._customerList.entries()){g.teaqlAttachRoot(this._root);const y=g.platform;(this.id===void 0||!g.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,r,C)}catch(O){if(!(O instanceof L))throw O;const _=w.property("customer_list").index(f);throw new L(O.violations.map(P=>({...P,location:P.location.prefixedBy(_)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}orderStatusList(){return this._orderStatusList}customerList(){return this._customerList}}const J=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({orderStatusList:"OrderStatus",customerList:"Customer"})}),OrderStatus:Object.freeze({fields:Object.freeze({platform:"integer",id:"integer",name:"string",code:"string",color:"string",display_order:"integer",displayOrder:"integer",version:"integer"}),queryFields:Object.freeze({platform:"platform",id:"id",name:"name",code:"code",color:"color",display_order:"displayOrder",displayOrder:"displayOrder",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),Customer:Object.freeze({fields:Object.freeze({id:"integer",platform:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",platform:"platform",name:"name",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),CustomerOrder:Object.freeze({fields:Object.freeze({id:"integer",customer:"integer",status:"integer",order_number:"string",orderNumber:"string",order_date:"date",orderDate:"date",total_amount:"decimal",totalAmount:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer:"customer",status:"status",order_number:"orderNumber",orderNumber:"orderNumber",order_date:"orderDate",orderDate:"orderDate",total_amount:"totalAmount",totalAmount:"totalAmount",version:"version"}),relations:Object.freeze({customer:"Customer",status:"OrderStatus",orderItemList:"OrderItem"})}),OrderItem:Object.freeze({fields:Object.freeze({id:"integer",customer_order:"integer",customerOrder:"integer",product_name:"string",productName:"string",quantity:"integer",unit_price:"decimal",unitPrice:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer_order:"customerOrder",customerOrder:"customerOrder",product_name:"productName",productName:"productName",quantity:"quantity",unit_price:"unitPrice",unitPrice:"unitPrice",version:"version"}),relations:Object.freeze({customer_order:"CustomerOrder",customerOrder:"CustomerOrder"})})});class st{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new vt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectOrderStatusListWith(t){return this.query.relationQuery("orderStatusList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectOrderStatusListWith",relation:"orderStatusList"}),this}selectCustomerListWith(t){return this.query.relationQuery("customerList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectCustomerListWith",relation:"customerList"}),this}haveOrderStatuses(){return this.withOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}haveNoOrderStatuses(){return this.withoutOrderStatusListMatching({toQuery:()=>new c("OrderStatus")})}withOrderStatusListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutOrderStatusListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}haveCustomers(){return this.withCustomerListMatching({toQuery:()=>new c("Customer")})}haveNoCustomers(){return this.withoutCustomerListMatching({toQuery:()=>new c("Customer")})}withCustomerListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutCustomerListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countOrderStatuses(){return this.countOrderStatusesAs("countOrderStatuses")}countOrderStatusesAs(t){const e=new c("OrderStatus").filter({version:{$gte:1}});return this.countOrderStatusesWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderStatusesAs",relation:"orderStatusList",alias:t},this}countOrderStatusesWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"relation-count",method:"countOrderStatusesWith",relation:"orderStatusList",alias:t}),this}minDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.minDisplayOrderOfOrderStatusesAs("minOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}minDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"minDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}maxDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.maxDisplayOrderOfOrderStatusesAs("maxOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}maxDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"maxDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sumDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sumDisplayOrderOfOrderStatusesAs("sumOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sumDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sumDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}avgDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.avgDisplayOrderOfOrderStatusesAs("avgOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}avgDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"avgDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}standardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.standardDeviationDisplayOrderOfOrderStatusesAs("standardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}standardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"standardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs("squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sampleVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.sampleVarianceDisplayOrderOfOrderStatusesAs("sampleVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}sampleVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sampleVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}samplePopulationVarianceDisplayOrderOfOrderStatuses(){const t=new c("OrderStatus").filter({version:{$gte:1}});return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs("samplePopulationVarianceOfDisplayOrderOfOrderStatuses",{toQuery:()=>t})}samplePopulationVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}countCustomers(){return this.countCustomersAs("countCustomers")}countCustomersAs(t){const e=new c("Customer").filter({version:{$gte:1}});return this.countCustomersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomersAs",relation:"customerList",alias:t},this}countCustomersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerList",t,r,!0,{kind:"relation-count",method:"countCustomersWith",relation:"customerList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof N?o:N.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof N?u:N.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof N?o:N.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class vt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new N}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ot{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderStatus"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new It(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["platform","id","name","code","color","displayOrder","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectCode(){return this.query.select(["code"]),this}selectColor(){return this.query.select(["color"]),this}selectDisplayOrder(){return this.query.select(["displayOrder"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","status",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"status"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"status"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withCodeContaining(t){return this.filters.push({code:{$contains:t}}),this}withCodeIs(t){return this.filters.push({code:{$eq:t}}),this}withCodeIsNot(t){return this.filters.push({code:{$ne:t}}),this}withCodeIn(...t){return this.filters.push({code:{$in:t}}),this}withCodeNotIn(...t){return this.filters.push({code:{$notIn:t}}),this}withCodeGreaterThan(t){return this.filters.push({code:{$gt:t}}),this}withCodeGreaterThanOrEqualTo(t){return this.filters.push({code:{$gte:t}}),this}withCodeLessThan(t){return this.filters.push({code:{$lt:t}}),this}withCodeLessThanOrEqualTo(t){return this.filters.push({code:{$lte:t}}),this}withCodeBetween(t,e){return this.filters.push({code:{$between:[t,e]}}),this}withCodeIsKnown(){return this.filters.push({code:{$isNull:!1}}),this}withCodeIsUnknown(){return this.filters.push({code:{$isNull:!0}}),this}withCodeNotContaining(t){return this.filters.push({code:{$notContains:t}}),this}withCodeStartingWith(t){return this.filters.push({code:{$startsWith:t}}),this}withCodeNotStartingWith(t){return this.filters.push({code:{$notStartsWith:t}}),this}withCodeEndingWith(t){return this.filters.push({code:{$endsWith:t}}),this}withCodeNotEndingWith(t){return this.filters.push({code:{$notEndsWith:t}}),this}withCodeSoundingLike(t){return this.filters.push({code:{$soundLike:t}}),this}withColorContaining(t){return this.filters.push({color:{$contains:t}}),this}withColorIs(t){return this.filters.push({color:{$eq:t}}),this}withColorIsNot(t){return this.filters.push({color:{$ne:t}}),this}withColorIn(...t){return this.filters.push({color:{$in:t}}),this}withColorNotIn(...t){return this.filters.push({color:{$notIn:t}}),this}withColorGreaterThan(t){return this.filters.push({color:{$gt:t}}),this}withColorGreaterThanOrEqualTo(t){return this.filters.push({color:{$gte:t}}),this}withColorLessThan(t){return this.filters.push({color:{$lt:t}}),this}withColorLessThanOrEqualTo(t){return this.filters.push({color:{$lte:t}}),this}withColorBetween(t,e){return this.filters.push({color:{$between:[t,e]}}),this}withColorIsKnown(){return this.filters.push({color:{$isNull:!1}}),this}withColorIsUnknown(){return this.filters.push({color:{$isNull:!0}}),this}withColorNotContaining(t){return this.filters.push({color:{$notContains:t}}),this}withColorStartingWith(t){return this.filters.push({color:{$startsWith:t}}),this}withColorNotStartingWith(t){return this.filters.push({color:{$notStartsWith:t}}),this}withColorEndingWith(t){return this.filters.push({color:{$endsWith:t}}),this}withColorNotEndingWith(t){return this.filters.push({color:{$notEndsWith:t}}),this}withColorSoundingLike(t){return this.filters.push({color:{$soundLike:t}}),this}withDisplayOrderIs(t){return this.filters.push({displayOrder:{$eq:t}}),this}withDisplayOrderIsNot(t){return this.filters.push({displayOrder:{$ne:t}}),this}withDisplayOrderIn(...t){return this.filters.push({displayOrder:{$in:t}}),this}withDisplayOrderNotIn(...t){return this.filters.push({displayOrder:{$notIn:t}}),this}withDisplayOrderGreaterThan(t){return this.filters.push({displayOrder:{$gt:t}}),this}withDisplayOrderGreaterThanOrEqualTo(t){return this.filters.push({displayOrder:{$gte:t}}),this}withDisplayOrderLessThan(t){return this.filters.push({displayOrder:{$lt:t}}),this}withDisplayOrderLessThanOrEqualTo(t){return this.filters.push({displayOrder:{$lte:t}}),this}withDisplayOrderBetween(t,e){return this.filters.push({displayOrder:{$between:[t,e]}}),this}withDisplayOrderIsKnown(){return this.filters.push({displayOrder:{$isNull:!1}}),this}withDisplayOrderIsUnknown(){return this.filters.push({displayOrder:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByCodeAscending(){return this.query.orderBy("code","asc"),this}orderByCodeDescending(){return this.query.orderBy("code","desc"),this}orderByColorAscending(){return this.query.orderBy("color","asc"),this}orderByColorDescending(){return this.query.orderBy("color","desc"),this}orderByDisplayOrderAscending(){return this.query.orderBy("displayOrder","asc"),this}orderByDisplayOrderDescending(){return this.query.orderBy("displayOrder","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minDisplayOrder(){return this.minDisplayOrderAs("minOfDisplayOrder")}minDisplayOrderAs(t){return this.query.aggregate("min","displayOrder",t),this}maxDisplayOrder(){return this.maxDisplayOrderAs("maxOfDisplayOrder")}maxDisplayOrderAs(t){return this.query.aggregate("max","displayOrder",t),this}sumDisplayOrder(){return this.sumDisplayOrderAs("sumOfDisplayOrder")}sumDisplayOrderAs(t){return this.query.aggregate("sum","displayOrder",t),this}avgDisplayOrder(){return this.avgDisplayOrderAs("avgOfDisplayOrder")}avgDisplayOrderAs(t){return this.query.aggregate("avg","displayOrder",t),this}standardDeviationDisplayOrder(){return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder")}standardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev","displayOrder",t),this}squareRootOfPopulationStandardDeviationDisplayOrder(){return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder")}squareRootOfPopulationStandardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev_pop","displayOrder",t),this}sampleVarianceDisplayOrder(){return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder")}sampleVarianceDisplayOrderAs(t){return this.query.aggregate("var_samp","displayOrder",t),this}samplePopulationVarianceDisplayOrder(){return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder")}samplePopulationVarianceDisplayOrderAs(t){return this.query.aggregate("var_pop","displayOrder",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByCode(){return this.query.groupBy("code"),this}groupByCodeAs(t){return this.query.groupBy("code"),this}groupByColor(){return this.query.groupBy("color"),this}groupByColorAs(t){return this.query.groupBy("color"),this}groupByDisplayOrder(){return this.query.groupBy("displayOrder"),this}groupByDisplayOrderAs(t){return this.query.groupBy("displayOrder"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof S?o:S.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof S?u:S.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof S?o:S.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class It{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new S}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class nt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("Customer"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Lt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","platform","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","customer",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({toQuery:()=>new c("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customer"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customer"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new c("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new c("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof Q?o:Q.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof Q?u:Q.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof Q?o:Q.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class Lt{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new Q}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class at{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("CustomerOrder"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new At(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customer","status","orderNumber","orderDate","totalAmount","version"]),this}selectId(){return this.query.select(["id"]),this}selectOrderNumber(){return this.query.select(["orderNumber"]),this}selectOrderDate(){return this.query.select(["orderDate"]),this}selectTotalAmount(){return this.query.select(["totalAmount"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerWith(t){return this.query.select(["customer"]),this.query.relationQuery("customer",t.toQuery(),"customer","id",!1,{kind:"relation-select",method:"selectCustomerWith",relation:"customer"}),this}selectStatusWith(t){return this.query.select(["status"]),this.query.relationQuery("status",t.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this}withCustomerMatching(t){return this.filters.push({customer:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerMatching(t){return this.filters.push({customer:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withStatusMatching(t){return this.filters.push({status:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutStatusMatching(t){return this.filters.push({status:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectOrderItemListWith(t){return this.query.relationQuery("orderItemList",t.toQuery(),"id","customerOrder",!0,{kind:"relation-select",method:"selectOrderItemListWith",relation:"orderItemList"}),this}haveOrderItems(){return this.withOrderItemListMatching({toQuery:()=>new c("OrderItem")})}haveNoOrderItems(){return this.withoutOrderItemListMatching({toQuery:()=>new c("OrderItem")})}withOrderItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}withoutOrderItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}countOrderItems(){return this.countOrderItemsAs("countOrderItems")}countOrderItemsAs(t){const e=new c("OrderItem").filter({version:{$gte:1}});return this.countOrderItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderItemsAs",relation:"orderItemList",alias:t},this}countOrderItemsWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"relation-count",method:"countOrderItemsWith",relation:"orderItemList",alias:t}),this}minQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minQuantityOfOrderItemsAs("minOfQuantityOfOrderItems",{toQuery:()=>t})}minQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxQuantityOfOrderItemsAs("maxOfQuantityOfOrderItems",{toQuery:()=>t})}maxQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumQuantityOfOrderItemsAs("sumOfQuantityOfOrderItems",{toQuery:()=>t})}sumQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgQuantityOfOrderItemsAs("avgOfQuantityOfOrderItems",{toQuery:()=>t})}avgQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationQuantityOfOrderItemsAs("standardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}standardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceQuantityOfOrderItemsAs("sampleVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}sampleVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceQuantityOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceQuantityOfOrderItemsAs("samplePopulationVarianceOfQuantityOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}minUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.minUnitPriceOfOrderItemsAs("minOfUnitPriceOfOrderItems",{toQuery:()=>t})}minUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.maxUnitPriceOfOrderItemsAs("maxOfUnitPriceOfOrderItems",{toQuery:()=>t})}maxUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sumUnitPriceOfOrderItemsAs("sumOfUnitPriceOfOrderItems",{toQuery:()=>t})}sumUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.avgUnitPriceOfOrderItemsAs("avgOfUnitPriceOfOrderItems",{toQuery:()=>t})}avgUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.standardDeviationUnitPriceOfOrderItemsAs("standardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}standardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems",{toQuery:()=>t})}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceUnitPriceOfOrderItemsAs("sampleVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}sampleVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceUnitPriceOfOrderItems(){const t=new c("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceUnitPriceOfOrderItemsAs("samplePopulationVarianceOfUnitPriceOfOrderItems",{toQuery:()=>t})}samplePopulationVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomer(t){return this.filters.push({customer:{$eq:t}}),this}filterByCustomerIn(...t){return this.filters.push({customer:{$in:t}}),this}withCustomerIsKnown(){return this.filters.push({customer:{$isNull:!1}}),this}withCustomerIsUnknown(){return this.filters.push({customer:{$isNull:!0}}),this}filterByStatus(t){return this.filters.push({status:{$eq:t}}),this}filterByStatusIn(...t){return this.filters.push({status:{$in:t}}),this}withStatusIsKnown(){return this.filters.push({status:{$isNull:!1}}),this}withStatusIsUnknown(){return this.filters.push({status:{$isNull:!0}}),this}withStatusIsNew(){return this.filters.push({status:{$eq:"1001"}}),this}withStatusIsPaid(){return this.filters.push({status:{$eq:"1002"}}),this}withStatusIsCancelled(){return this.filters.push({status:{$eq:"1003"}}),this}withOrderNumberContaining(t){return this.filters.push({orderNumber:{$contains:t}}),this}withOrderNumberIs(t){return this.filters.push({orderNumber:{$eq:t}}),this}withOrderNumberIsNot(t){return this.filters.push({orderNumber:{$ne:t}}),this}withOrderNumberIn(...t){return this.filters.push({orderNumber:{$in:t}}),this}withOrderNumberNotIn(...t){return this.filters.push({orderNumber:{$notIn:t}}),this}withOrderNumberGreaterThan(t){return this.filters.push({orderNumber:{$gt:t}}),this}withOrderNumberGreaterThanOrEqualTo(t){return this.filters.push({orderNumber:{$gte:t}}),this}withOrderNumberLessThan(t){return this.filters.push({orderNumber:{$lt:t}}),this}withOrderNumberLessThanOrEqualTo(t){return this.filters.push({orderNumber:{$lte:t}}),this}withOrderNumberBetween(t,e){return this.filters.push({orderNumber:{$between:[t,e]}}),this}withOrderNumberIsKnown(){return this.filters.push({orderNumber:{$isNull:!1}}),this}withOrderNumberIsUnknown(){return this.filters.push({orderNumber:{$isNull:!0}}),this}withOrderNumberNotContaining(t){return this.filters.push({orderNumber:{$notContains:t}}),this}withOrderNumberStartingWith(t){return this.filters.push({orderNumber:{$startsWith:t}}),this}withOrderNumberNotStartingWith(t){return this.filters.push({orderNumber:{$notStartsWith:t}}),this}withOrderNumberEndingWith(t){return this.filters.push({orderNumber:{$endsWith:t}}),this}withOrderNumberNotEndingWith(t){return this.filters.push({orderNumber:{$notEndsWith:t}}),this}withOrderNumberSoundingLike(t){return this.filters.push({orderNumber:{$soundLike:t}}),this}withOrderDateIs(t){return this.filters.push({orderDate:{$eq:t}}),this}withOrderDateIsNot(t){return this.filters.push({orderDate:{$ne:t}}),this}withOrderDateIn(...t){return this.filters.push({orderDate:{$in:t}}),this}withOrderDateNotIn(...t){return this.filters.push({orderDate:{$notIn:t}}),this}withOrderDateGreaterThan(t){return this.filters.push({orderDate:{$gt:t}}),this}withOrderDateGreaterThanOrEqualTo(t){return this.filters.push({orderDate:{$gte:t}}),this}withOrderDateLessThan(t){return this.filters.push({orderDate:{$lt:t}}),this}withOrderDateLessThanOrEqualTo(t){return this.filters.push({orderDate:{$lte:t}}),this}withOrderDateBetween(t,e){return this.filters.push({orderDate:{$between:[t,e]}}),this}withOrderDateIsKnown(){return this.filters.push({orderDate:{$isNull:!1}}),this}withOrderDateIsUnknown(){return this.filters.push({orderDate:{$isNull:!0}}),this}withTotalAmountIs(t){return this.filters.push({totalAmount:{$eq:t}}),this}withTotalAmountIsNot(t){return this.filters.push({totalAmount:{$ne:t}}),this}withTotalAmountIn(...t){return this.filters.push({totalAmount:{$in:t}}),this}withTotalAmountNotIn(...t){return this.filters.push({totalAmount:{$notIn:t}}),this}withTotalAmountGreaterThan(t){return this.filters.push({totalAmount:{$gt:t}}),this}withTotalAmountGreaterThanOrEqualTo(t){return this.filters.push({totalAmount:{$gte:t}}),this}withTotalAmountLessThan(t){return this.filters.push({totalAmount:{$lt:t}}),this}withTotalAmountLessThanOrEqualTo(t){return this.filters.push({totalAmount:{$lte:t}}),this}withTotalAmountBetween(t,e){return this.filters.push({totalAmount:{$between:[t,e]}}),this}withTotalAmountIsKnown(){return this.filters.push({totalAmount:{$isNull:!1}}),this}withTotalAmountIsUnknown(){return this.filters.push({totalAmount:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByOrderNumberAscending(){return this.query.orderBy("orderNumber","asc"),this}orderByOrderNumberDescending(){return this.query.orderBy("orderNumber","desc"),this}orderByOrderDateAscending(){return this.query.orderBy("orderDate","asc"),this}orderByOrderDateDescending(){return this.query.orderBy("orderDate","desc"),this}orderByTotalAmountAscending(){return this.query.orderBy("totalAmount","asc"),this}orderByTotalAmountDescending(){return this.query.orderBy("totalAmount","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minTotalAmount(){return this.minTotalAmountAs("minOfTotalAmount")}minTotalAmountAs(t){return this.query.aggregate("min","totalAmount",t),this}maxTotalAmount(){return this.maxTotalAmountAs("maxOfTotalAmount")}maxTotalAmountAs(t){return this.query.aggregate("max","totalAmount",t),this}sumTotalAmount(){return this.sumTotalAmountAs("sumOfTotalAmount")}sumTotalAmountAs(t){return this.query.aggregate("sum","totalAmount",t),this}avgTotalAmount(){return this.avgTotalAmountAs("avgOfTotalAmount")}avgTotalAmountAs(t){return this.query.aggregate("avg","totalAmount",t),this}standardDeviationTotalAmount(){return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount")}standardDeviationTotalAmountAs(t){return this.query.aggregate("stddev","totalAmount",t),this}squareRootOfPopulationStandardDeviationTotalAmount(){return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount")}squareRootOfPopulationStandardDeviationTotalAmountAs(t){return this.query.aggregate("stddev_pop","totalAmount",t),this}sampleVarianceTotalAmount(){return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount")}sampleVarianceTotalAmountAs(t){return this.query.aggregate("var_samp","totalAmount",t),this}samplePopulationVarianceTotalAmount(){return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount")}samplePopulationVarianceTotalAmountAs(t){return this.query.aggregate("var_pop","totalAmount",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomer(){return this.query.groupBy("customer"),this}groupByCustomerAs(t){return this.query.groupBy("customer"),this}groupByStatus(){return this.query.groupBy("status"),this}groupByStatusAs(t){return this.query.groupBy("status"),this}groupByOrderNumber(){return this.query.groupBy("orderNumber"),this}groupByOrderNumberAs(t){return this.query.groupBy("orderNumber"),this}groupByOrderDate(){return this.query.groupBy("orderDate"),this}groupByOrderDateAs(t){return this.query.groupBy("orderDate"),this}groupByTotalAmount(){return this.query.groupBy("totalAmount"),this}groupByTotalAmountAs(t){return this.query.groupBy("totalAmount"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerAs(t,e,r=!0){return this.query.facetBy(t,"customer",e,r,{kind:"facet",method:"facetByCustomerAs",relation:"customer",alias:t}),this}facetByStatusAs(t,e,r=!0){return this.query.facetBy(t,"status",e,r,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof $?o:$.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof $?u:$.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof $?o:$.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class At{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new $}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class ut{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new c("OrderItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=G(r,t,J,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new _t(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customerOrder","productName","quantity","unitPrice","version"]),this}selectId(){return this.query.select(["id"]),this}selectProductName(){return this.query.select(["productName"]),this}selectQuantity(){return this.query.select(["quantity"]),this}selectUnitPrice(){return this.query.select(["unitPrice"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerOrderWith(t){return this.query.select(["customerOrder"]),this.query.relationQuery("customerOrder",t.toQuery(),"customerOrder","id",!1,{kind:"relation-select",method:"selectCustomerOrderWith",relation:"customerOrder"}),this}withCustomerOrderMatching(t){return this.filters.push({customerOrder:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerOrderMatching(t){return this.filters.push({customerOrder:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomerOrder(t){return this.filters.push({customerOrder:{$eq:t}}),this}filterByCustomerOrderIn(...t){return this.filters.push({customerOrder:{$in:t}}),this}withCustomerOrderIsKnown(){return this.filters.push({customerOrder:{$isNull:!1}}),this}withCustomerOrderIsUnknown(){return this.filters.push({customerOrder:{$isNull:!0}}),this}withProductNameContaining(t){return this.filters.push({productName:{$contains:t}}),this}withProductNameIs(t){return this.filters.push({productName:{$eq:t}}),this}withProductNameIsNot(t){return this.filters.push({productName:{$ne:t}}),this}withProductNameIn(...t){return this.filters.push({productName:{$in:t}}),this}withProductNameNotIn(...t){return this.filters.push({productName:{$notIn:t}}),this}withProductNameGreaterThan(t){return this.filters.push({productName:{$gt:t}}),this}withProductNameGreaterThanOrEqualTo(t){return this.filters.push({productName:{$gte:t}}),this}withProductNameLessThan(t){return this.filters.push({productName:{$lt:t}}),this}withProductNameLessThanOrEqualTo(t){return this.filters.push({productName:{$lte:t}}),this}withProductNameBetween(t,e){return this.filters.push({productName:{$between:[t,e]}}),this}withProductNameIsKnown(){return this.filters.push({productName:{$isNull:!1}}),this}withProductNameIsUnknown(){return this.filters.push({productName:{$isNull:!0}}),this}withProductNameNotContaining(t){return this.filters.push({productName:{$notContains:t}}),this}withProductNameStartingWith(t){return this.filters.push({productName:{$startsWith:t}}),this}withProductNameNotStartingWith(t){return this.filters.push({productName:{$notStartsWith:t}}),this}withProductNameEndingWith(t){return this.filters.push({productName:{$endsWith:t}}),this}withProductNameNotEndingWith(t){return this.filters.push({productName:{$notEndsWith:t}}),this}withProductNameSoundingLike(t){return this.filters.push({productName:{$soundLike:t}}),this}withQuantityIs(t){return this.filters.push({quantity:{$eq:t}}),this}withQuantityIsNot(t){return this.filters.push({quantity:{$ne:t}}),this}withQuantityIn(...t){return this.filters.push({quantity:{$in:t}}),this}withQuantityNotIn(...t){return this.filters.push({quantity:{$notIn:t}}),this}withQuantityGreaterThan(t){return this.filters.push({quantity:{$gt:t}}),this}withQuantityGreaterThanOrEqualTo(t){return this.filters.push({quantity:{$gte:t}}),this}withQuantityLessThan(t){return this.filters.push({quantity:{$lt:t}}),this}withQuantityLessThanOrEqualTo(t){return this.filters.push({quantity:{$lte:t}}),this}withQuantityBetween(t,e){return this.filters.push({quantity:{$between:[t,e]}}),this}withQuantityIsKnown(){return this.filters.push({quantity:{$isNull:!1}}),this}withQuantityIsUnknown(){return this.filters.push({quantity:{$isNull:!0}}),this}withUnitPriceIs(t){return this.filters.push({unitPrice:{$eq:t}}),this}withUnitPriceIsNot(t){return this.filters.push({unitPrice:{$ne:t}}),this}withUnitPriceIn(...t){return this.filters.push({unitPrice:{$in:t}}),this}withUnitPriceNotIn(...t){return this.filters.push({unitPrice:{$notIn:t}}),this}withUnitPriceGreaterThan(t){return this.filters.push({unitPrice:{$gt:t}}),this}withUnitPriceGreaterThanOrEqualTo(t){return this.filters.push({unitPrice:{$gte:t}}),this}withUnitPriceLessThan(t){return this.filters.push({unitPrice:{$lt:t}}),this}withUnitPriceLessThanOrEqualTo(t){return this.filters.push({unitPrice:{$lte:t}}),this}withUnitPriceBetween(t,e){return this.filters.push({unitPrice:{$between:[t,e]}}),this}withUnitPriceIsKnown(){return this.filters.push({unitPrice:{$isNull:!1}}),this}withUnitPriceIsUnknown(){return this.filters.push({unitPrice:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByProductNameAscending(){return this.query.orderBy("productName","asc"),this}orderByProductNameDescending(){return this.query.orderBy("productName","desc"),this}orderByQuantityAscending(){return this.query.orderBy("quantity","asc"),this}orderByQuantityDescending(){return this.query.orderBy("quantity","desc"),this}orderByUnitPriceAscending(){return this.query.orderBy("unitPrice","asc"),this}orderByUnitPriceDescending(){return this.query.orderBy("unitPrice","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minQuantity(){return this.minQuantityAs("minOfQuantity")}minQuantityAs(t){return this.query.aggregate("min","quantity",t),this}maxQuantity(){return this.maxQuantityAs("maxOfQuantity")}maxQuantityAs(t){return this.query.aggregate("max","quantity",t),this}sumQuantity(){return this.sumQuantityAs("sumOfQuantity")}sumQuantityAs(t){return this.query.aggregate("sum","quantity",t),this}avgQuantity(){return this.avgQuantityAs("avgOfQuantity")}avgQuantityAs(t){return this.query.aggregate("avg","quantity",t),this}standardDeviationQuantity(){return this.standardDeviationQuantityAs("standardDeviationOfQuantity")}standardDeviationQuantityAs(t){return this.query.aggregate("stddev","quantity",t),this}squareRootOfPopulationStandardDeviationQuantity(){return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity")}squareRootOfPopulationStandardDeviationQuantityAs(t){return this.query.aggregate("stddev_pop","quantity",t),this}sampleVarianceQuantity(){return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity")}sampleVarianceQuantityAs(t){return this.query.aggregate("var_samp","quantity",t),this}samplePopulationVarianceQuantity(){return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity")}samplePopulationVarianceQuantityAs(t){return this.query.aggregate("var_pop","quantity",t),this}minUnitPrice(){return this.minUnitPriceAs("minOfUnitPrice")}minUnitPriceAs(t){return this.query.aggregate("min","unitPrice",t),this}maxUnitPrice(){return this.maxUnitPriceAs("maxOfUnitPrice")}maxUnitPriceAs(t){return this.query.aggregate("max","unitPrice",t),this}sumUnitPrice(){return this.sumUnitPriceAs("sumOfUnitPrice")}sumUnitPriceAs(t){return this.query.aggregate("sum","unitPrice",t),this}avgUnitPrice(){return this.avgUnitPriceAs("avgOfUnitPrice")}avgUnitPriceAs(t){return this.query.aggregate("avg","unitPrice",t),this}standardDeviationUnitPrice(){return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice")}standardDeviationUnitPriceAs(t){return this.query.aggregate("stddev","unitPrice",t),this}squareRootOfPopulationStandardDeviationUnitPrice(){return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice")}squareRootOfPopulationStandardDeviationUnitPriceAs(t){return this.query.aggregate("stddev_pop","unitPrice",t),this}sampleVarianceUnitPrice(){return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice")}sampleVarianceUnitPriceAs(t){return this.query.aggregate("var_samp","unitPrice",t),this}samplePopulationVarianceUnitPrice(){return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice")}samplePopulationVarianceUnitPriceAs(t){return this.query.aggregate("var_pop","unitPrice",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByCustomerOrder(){return this.query.groupBy("customerOrder"),this}groupByCustomerOrderAs(t){return this.query.groupBy("customerOrder"),this}groupByProductName(){return this.query.groupBy("productName"),this}groupByProductNameAs(t){return this.query.groupBy("productName"),this}groupByQuantity(){return this.query.groupBy("quantity"),this}groupByQuantityAs(t){return this.query.groupBy("quantity"),this}groupByUnitPrice(){return this.query.groupBy("unitPrice"),this}groupByUnitPriceAs(t){return this.query.groupBy("unitPrice"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByCustomerOrderAs(t,e,r=!0){return this.query.facetBy(t,"customerOrder",e,r,{kind:"facet",method:"facetByCustomerOrderAs",relation:"customerOrder",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(o=>o instanceof B?o:B.fromRecord(o,new T)),h=new A(s);return i&&r[0]&&Object.assign(h.aggregations,r[0]),this.query.facets.length>0&&(h.facets=await F(e,o=>t.prepareQuery(o),this.query,this.query.facets)),h}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new A(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},h=i?void 0:await e.executeCount(r,this._pageCountAlias,s),o=r.clone();o.aggregateItems=o.aggregateItems.filter(u=>!(String(u.function).toLowerCase()==="count"&&u.alias===this._pageCountAlias));const p=await e.executeQuery(o),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:h??await e.executeCount(r,this._pageCountAlias,s),a=new A(p.map(u=>u instanceof B?u:B.fromRecord(u,new T)));return a.totalCount=l,this._pageCountAlias!==void 0&&(a.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(a.facets=await F(e,u=>t.prepareQuery(u),r,r.facets)),a}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const h of s)for(const o of h)yield o instanceof B?o:B.fromRecord(o,new T)})()}ensureIntent(){new z(this._comment,this._purpose)}}class _t{constructor(t,e,r,i,s,h){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=h}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new B}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class E{static platforms(){return new st(!1)}static platformsWithMinimalFields(){return new st(!0)}static orderStatuses(){return new ot(!1)}static orderStatusesWithMinimalFields(){return new ot(!0)}static customers(){return new nt(!1)}static customersWithMinimalFields(){return new nt(!0)}static customerOrders(){return new at(!1)}static customerOrdersWithMinimalFields(){return new at(!0)}static orderItems(){return new ut(!1)}static orderItemsWithMinimalFields(){return new ut(!0)}}class I extends Error{constructor(t,e,r){const i=`select${r.charAt(0).toUpperCase()}${r.slice(1)}(...)`,s={error:"TeaQLNotLoadedError",root:t,accessPath:e.split("."),breakPoint:r,missingPreload:[r],suggestedFix:i,severity:"error",humanMessage:`访问 ${t}.${e} 时缺少预加载。请在查询中加入 ${i}`};super(JSON.stringify(s)),this.root=t,this.accessPath=e,this.breakPoint=r,this.name="TeaQLNotLoadedError",this.details=s}root;accessPath;breakPoint;details}function q(d,t){return d?`${d}.${t}`:t}class n{constructor(t,e=!0,r){this.value=t,this.present=e,this.notLoaded=r}value;present;notLoaded;static missing(){return new n(void 0,!1)}static notLoaded(t){return new n(void 0,!1,t)}eval(){if(this.notLoaded)throw this.notLoaded;return this.present?this.value:void 0}isPresent(){if(this.notLoaded)throw this.notLoaded;return this.present}orElse(t){const e=this.eval();return this.present&&e!=null?e:t}}class x{constructor(t,e="Platform(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}orderStatusList(){const t=q(this.path,"orderStatusList");return this.notLoaded?new U([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderStatusList")?new U(this.value.orderStatusList(),this.root,t):new U([],this.root,t,!1,new I(this.root,t,"orderStatusList")):U.missing(this.root,t)}customerList(){const t=q(this.path,"customerList");return this.notLoaded?new M([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerList")?new M(this.value.customerList(),this.root,t):new M([],this.root,t,!1,new I(this.root,t,"customerList")):M.missing(this.root,t)}}class V{constructor(t,e="OrderStatus(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}code(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"code");return this.value.isLoaded("code")?new n(this.value.code):n.notLoaded(new I(this.root,t,"code"))}color(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"color");return this.value.isLoaded("color")?new n(this.value.color):n.notLoaded(new I(this.root,t,"color"))}displayOrder(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"displayOrder");return this.value.isLoaded("displayOrder")?new n(this.value.displayOrder):n.notLoaded(new I(this.root,t,"displayOrder"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class W{constructor(t,e="Customer(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}name(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"name");return this.value.isLoaded("name")?new n(this.value.name):n.notLoaded(new I(this.root,t,"name"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}platformId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"platform");if(!this.value.isLoaded("platform"))return n.notLoaded(new I(this.root,t,"platform"));const e=this.value.platform;return new n(e instanceof N?e.id:e)}platform(){const t=q(this.path,"platform");if(this.notLoaded)return new x(void 0,this.root,t,this.notLoaded);if(!this.value)return new x(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new x(void 0,this.root,t,new I(this.root,t,"platform"));const e=this.value.platform,r=e==null?void 0:e instanceof N?e:N.fromRecord({id:e});return new x(r,this.root,t)}customerOrderList(){const t=q(this.path,"customerOrderList");return this.notLoaded?new k([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("customerOrderList")?new k(this.value.customerOrderList(),this.root,t):new k([],this.root,t,!1,new I(this.root,t,"customerOrderList")):k.missing(this.root,t)}}class K{constructor(t,e="CustomerOrder(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}orderNumber(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderNumber");return this.value.isLoaded("orderNumber")?new n(this.value.orderNumber):n.notLoaded(new I(this.root,t,"orderNumber"))}orderDate(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"orderDate");return this.value.isLoaded("orderDate")?new n(this.value.orderDate):n.notLoaded(new I(this.root,t,"orderDate"))}totalAmount(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"totalAmount");return this.value.isLoaded("totalAmount")?new n(this.value.totalAmount):n.notLoaded(new I(this.root,t,"totalAmount"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customer");if(!this.value.isLoaded("customer"))return n.notLoaded(new I(this.root,t,"customer"));const e=this.value.customer;return new n(e instanceof Q?e.id:e)}statusId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"status");if(!this.value.isLoaded("status"))return n.notLoaded(new I(this.root,t,"status"));const e=this.value.status;return new n(e instanceof S?e.id:e)}customer(){const t=q(this.path,"customer");if(this.notLoaded)return new W(void 0,this.root,t,this.notLoaded);if(!this.value)return new W(void 0,this.root,t);if(!this.value.isLoaded("customer"))return new W(void 0,this.root,t,new I(this.root,t,"customer"));const e=this.value.customer,r=e==null?void 0:e instanceof Q?e:Q.fromRecord({id:e});return new W(r,this.root,t)}status(){const t=q(this.path,"status");if(this.notLoaded)return new V(void 0,this.root,t,this.notLoaded);if(!this.value)return new V(void 0,this.root,t);if(!this.value.isLoaded("status"))return new V(void 0,this.root,t,new I(this.root,t,"status"));const e=this.value.status,r=e==null?void 0:e instanceof S?e:S.fromRecord({id:e});return new V(r,this.root,t)}orderItemList(){const t=q(this.path,"orderItemList");return this.notLoaded?new j([],this.root,t,!1,this.notLoaded):this.value?this.value.isLoaded("orderItemList")?new j(this.value.orderItemList(),this.root,t):new j([],this.root,t,!1,new I(this.root,t,"orderItemList")):j.missing(this.root,t)}}class H{constructor(t,e="OrderItem(null)",r="",i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded;return this.value}id(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"id");return this.value.isLoaded("id")?new n(this.value.id):n.notLoaded(new I(this.root,t,"id"))}productName(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"productName");return this.value.isLoaded("productName")?new n(this.value.productName):n.notLoaded(new I(this.root,t,"productName"))}quantity(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"quantity");return this.value.isLoaded("quantity")?new n(this.value.quantity):n.notLoaded(new I(this.root,t,"quantity"))}unitPrice(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"unitPrice");return this.value.isLoaded("unitPrice")?new n(this.value.unitPrice):n.notLoaded(new I(this.root,t,"unitPrice"))}version(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"version");return this.value.isLoaded("version")?new n(this.value.version):n.notLoaded(new I(this.root,t,"version"))}customerOrderId(){if(this.notLoaded)return n.notLoaded(this.notLoaded);if(!this.value)return n.missing();const t=q(this.path,"customerOrder");if(!this.value.isLoaded("customerOrder"))return n.notLoaded(new I(this.root,t,"customerOrder"));const e=this.value.customerOrder;return new n(e instanceof $?e.id:e)}customerOrder(){const t=q(this.path,"customerOrder");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded);if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("customerOrder"))return new K(void 0,this.root,t,new I(this.root,t,"customerOrder"));const e=this.value.customerOrder,r=e==null?void 0:e instanceof $?e:$.fromRecord({id:e});return new K(r,this.root,t)}}class U{constructor(t,e="OrderStatus(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new U([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new V(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new V(void 0,this.root,e):new V(this.items[t],this.root,e)}}class M{constructor(t,e="Customer(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new M([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new W(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new W(void 0,this.root,e):new W(this.items[t],this.root,e)}}class k{constructor(t,e="CustomerOrder(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new k([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new K(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new K(void 0,this.root,e):new K(this.items[t],this.root,e)}}class j{constructor(t,e="OrderItem(null)",r="",i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=""){return new j([],t,e,!1)}size(){return this.notLoaded?n.notLoaded(this.notLoaded):this.present?new n(this.items.length):n.missing()}first(){return this.get(0)}get(t){const e=q(this.path,`get(${t})`);return this.notLoaded?new H(void 0,this.root,e,this.notLoaded):!this.present||t<0||t>=this.items.length?new H(void 0,this.root,e):new H(this.items[t],this.root,e)}}class et{static platform(t){return new x(t,`Platform(id=${t?.id??"null"})`)}static orderStatus(t){return new V(t,`OrderStatus(id=${t?.id??"null"})`)}static customer(t){return new W(t,`Customer(id=${t?.id??"null"})`)}static customerOrder(t){return new K(t,`CustomerOrder(id=${t?.id??"null"})`)}static orderItem(t){return new H(t,`OrderItem(id=${t?.id??"null"})`)}}const ht={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{orderStatusList:{targetEntity:"OrderStatus",localKey:"id",foreignKey:"platform",many:!0},customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platform",many:!0}}},OrderStatus:{table:"order_status_data",auditMaskFields:[],columns:{platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},code:{columnName:"code",modelName:"code",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},color:{columnName:"color",modelName:"color",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},displayOrder:{columnName:"display_order",modelName:"display_order",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},Customer:{table:"customer_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customer",many:!0}}},CustomerOrder:{table:"customer_order_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customer:{columnName:"customer",modelName:"customer",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},status:{columnName:"status",modelName:"status",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},orderNumber:{columnName:"order_number",modelName:"order_number",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},orderDate:{columnName:"order_date",modelName:"order_date",logPolicy:"plain",logicalType:"date",decode:"date",nullable:!1},totalAmount:{columnName:"total_amount",modelName:"total_amount",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customer:{targetEntity:"Customer",localKey:"customer",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},orderItemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"customerOrder",many:!0}}},OrderItem:{table:"order_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customerOrder:{columnName:"customer_order",modelName:"customer_order",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},productName:{columnName:"product_name",modelName:"product_name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},quantity:{columnName:"quantity",modelName:"quantity",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1},unitPrice:{columnName:"unit_price",modelName:"unit_price",logPolicy:"plain",logicalType:"decimal",decode:"number",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customerOrder:{targetEntity:"CustomerOrder",localKey:"customerOrder",foreignKey:"id",many:!1}}}};async function Ct(d){let t=(await E.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];t||(t=N.teaqlBootstrapNew("1"),t.updateName("Commerce Test Platform"),await t.auditAs("create generated Domain Root Platform").save(d)),d.withActiveRoot({entity:"Platform",id:t.id});let e=(await E.orderStatuses().withIdIs("1001").comment("what: locate generated constant OrderStatus(1001)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!e)e=S.teaqlBootstrapNew("1001"),e.updatePlatform(t),e.updateName("New"),e.updateCode("NEW"),e.updateColor("#94A3B8"),e.updateDisplayOrder(1),await e.auditAs("create model constant OrderStatus(1001)").save(d);else{let s=!1;String(e.platform?.id??e.platform)!==String(t.id)&&(e.updatePlatform(t),s=!0),e.name!=="New"&&(e.updateName("New"),s=!0),e.code!=="NEW"&&(e.updateCode("NEW"),s=!0),e.color!=="#94A3B8"&&(e.updateColor("#94A3B8"),s=!0),e.displayOrder!==1&&(e.updateDisplayOrder(1),s=!0),s&&await e.auditAs("reconcile model constant OrderStatus(1001)").save(d)}let r=(await E.orderStatuses().withIdIs("1002").comment("what: locate generated constant OrderStatus(1002)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!r)r=S.teaqlBootstrapNew("1002"),r.updatePlatform(t),r.updateName("Paid"),r.updateCode("PAID"),r.updateColor("#22C55E"),r.updateDisplayOrder(2),await r.auditAs("create model constant OrderStatus(1002)").save(d);else{let s=!1;String(r.platform?.id??r.platform)!==String(t.id)&&(r.updatePlatform(t),s=!0),r.name!=="Paid"&&(r.updateName("Paid"),s=!0),r.code!=="PAID"&&(r.updateCode("PAID"),s=!0),r.color!=="#22C55E"&&(r.updateColor("#22C55E"),s=!0),r.displayOrder!==2&&(r.updateDisplayOrder(2),s=!0),s&&await r.auditAs("reconcile model constant OrderStatus(1002)").save(d)}let i=(await E.orderStatuses().withIdIs("1003").comment("what: locate generated constant OrderStatus(1003)").purpose("why: idempotent runtime bootstrap").executeForList(d))[0];if(!i)i=S.teaqlBootstrapNew("1003"),i.updatePlatform(t),i.updateName("Cancelled"),i.updateCode("CANCELLED"),i.updateColor("#EF4444"),i.updateDisplayOrder(3),await i.auditAs("create model constant OrderStatus(1003)").save(d);else{let s=!1;String(i.platform?.id??i.platform)!==String(t.id)&&(i.updatePlatform(t),s=!0),i.name!=="Cancelled"&&(i.updateName("Cancelled"),s=!0),i.code!=="CANCELLED"&&(i.updateCode("CANCELLED"),s=!0),i.color!=="#EF4444"&&(i.updateColor("#EF4444"),s=!0),i.displayOrder!==3&&(i.updateDisplayOrder(3),s=!0),s&&await i.auditAs("reconcile model constant OrderStatus(1003)").save(d)}}const Pt=new pt(ht,{Platform:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},OrderStatus:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100}),(t.action==="Create"&&t.payload.code===void 0||t.payload.code===null)&&e.push({ruleId:"required",location:w.property("code")}),t.payload.code!=null&&[...String(t.payload.code)].length>100&&e.push({ruleId:"max_length",location:w.property("code"),inputValue:t.payload.code,systemValue:100}),(t.action==="Create"&&t.payload.color===void 0||t.payload.color===null)&&e.push({ruleId:"required",location:w.property("color")}),t.payload.color!=null&&[...String(t.payload.color)].length>100&&e.push({ruleId:"max_length",location:w.property("color"),inputValue:t.payload.color,systemValue:100}),(t.action==="Create"&&t.payload.display_order===void 0||t.payload.display_order===null)&&e.push({ruleId:"required",location:w.property("display_order")})}},Customer:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:w.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:w.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:w.property("name"),inputValue:t.payload.name,systemValue:100})}},CustomerOrder:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer===void 0||t.payload.customer===null)&&e.push({ruleId:"required",location:w.property("customer")}),(t.action==="Create"&&t.payload.status===void 0||t.payload.status===null)&&e.push({ruleId:"required",location:w.property("status")}),(t.action==="Create"&&t.payload.order_number===void 0||t.payload.order_number===null)&&e.push({ruleId:"required",location:w.property("order_number")}),t.payload.order_number!=null&&[...String(t.payload.order_number)].length>100&&e.push({ruleId:"max_length",location:w.property("order_number"),inputValue:t.payload.order_number,systemValue:100}),(t.action==="Create"&&t.payload.order_date===void 0||t.payload.order_date===null)&&e.push({ruleId:"required",location:w.property("order_date")}),(t.action==="Create"&&t.payload.total_amount===void 0||t.payload.total_amount===null)&&e.push({ruleId:"required",location:w.property("total_amount")})}},OrderItem:{checkAndFix(d,t,e){d.getResource("fixTime"),(t.action==="Create"&&t.payload.customer_order===void 0||t.payload.customer_order===null)&&e.push({ruleId:"required",location:w.property("customer_order")}),(t.action==="Create"&&t.payload.product_name===void 0||t.payload.product_name===null)&&e.push({ruleId:"required",location:w.property("product_name")}),t.payload.product_name!=null&&[...String(t.payload.product_name)].length>100&&e.push({ruleId:"max_length",location:w.property("product_name"),inputValue:t.payload.product_name,systemValue:100}),(t.action==="Create"&&t.payload.quantity===void 0||t.payload.quantity===null)&&e.push({ruleId:"required",location:w.property("quantity")}),(t.action==="Create"&&t.payload.unit_price===void 0||t.payload.unit_price===null)&&e.push({ruleId:"required",location:w.property("unit_price")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Commerce Test Platform"}},constants:[{entity:"OrderStatus",id:"1001",values:{platform:"1",name:"New",code:"NEW",color:"#94A3B8",displayOrder:1}},{entity:"OrderStatus",id:"1002",values:{platform:"1",name:"Paid",code:"PAID",color:"#22C55E",displayOrder:2}},{entity:"OrderStatus",id:"1003",values:{platform:"1",name:"Cancelled",code:"CANCELLED",color:"#EF4444",displayOrder:3}}],ensure:Ct}),it=document.querySelector("#status"),St=document.querySelector("#result"),Nt=document.querySelector("#trace"),$t=document.querySelector("#sql"),bt=document.querySelector("#evidence-rows"),Z=document.querySelector("#persist"),dt=document.querySelector("#logging"),rt=document.querySelector("#reset"),Y=document.querySelector("#query"),lt=document.querySelector("#search"),Tt={filter:{orderNumber:{$contains:"KEEP"}}};let R;Z.checked=localStorage.getItem("teaql-browser-order-storage")==="opfs";async function Qt(d){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await ft.open(t,{...ht},{storage:d,databaseName:"teaql-browser-orders.sqlite3"});e.install(Pt),e.setDiagnosticSQLLogSink(void 0).setMutationLoggingEnabled(!1);const r=Object.freeze({policyId:"browser-order-seed",version:"1",fingerprint:"sha256:browser-order-seed-v1"}),i=new gt().insertResource("dataService",e).withMutationPolicyRegistry(new Ot(()=>({identity:r,review:(s,h)=>h.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new wt(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(i),await i.ensureSchema(),await i.ensureSchema(),{client:e,context:i,evidence:new qt,diagnostics:[]}}async function ct({context:d}){if((await E.customerOrdersWithMinimalFields().limit(1).comment("detect existing order demo").purpose("keep mutation seeding idempotent").executeForList(d)).length)return;const e=(await E.platforms().limit(2).comment("load bootstrap platform").purpose("prepare order demo").executeForList(d))[0],r=E.customers().comment("initialize demo customer").purpose("prepare order demo").newEntity(d);r.updateName("North Star Retail").updatePlatform(e.id),await r.auditAs("seed browser order customer").save(d);for(let i=1;i<=4;i++){const s=E.customerOrders().comment("initialize demo order").purpose("prepare order demo").newEntity(d);s.updateCustomer(r.id).updateOrderNumber(i<4?`KEEP-00${i}`:"DROP-004").updateOrderDate(`2026-10-0${i}`).updateTotalAmount(i<4?i*100:900),i===1?s.updateStatusToNew():s.updateStatusToPaid(),await s.auditAs("seed browser order").save(d);for(let h=1;h<=5;h++){const o=E.orderItems().comment("initialize demo item").purpose("prepare item previews").newEntity(d);o.updateCustomerOrder(s.id).updateProductName(`Box ${h}`).updateQuantity(h).updateUnitPrice(20),await o.auditAs("seed browser order item").save(d)}}}async function tt(d){const t=JSON.parse(lt.value),e=E.customerOrdersWithMinimalFields().filterByJson(t);d.evidence.enableAll(),d.diagnostics.length=0,d.client.setRuntimeTelemetrySink(d.evidence).setQueryLoggingEnabled(dt.checked).setDiagnosticSQLLogSink({write:o=>d.diagnostics.push(o)});const r=await e.countAs("totalOrders").facetByStatusAs("statusCounts",E.orderStatusesWithMinimalFields().selectName().selectColor().countAs("orderCount").sumTotalAmountOfCustomerOrdersAs("orderTotalAmount",E.customerOrdersWithMinimalFields()).orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(E.orderStatusesWithMinimalFields().selectName().selectColor().comment("load status")).selectOrderItemListWith(E.orderItemsWithMinimalFields().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countOrderItemsAs("itemCount").orderByOrderDateDescending().orderByIdDescending().offset(1).limit(1).comment("load order list").purpose("render order list page").executeForList(d.context),i={data:r.data.map(o=>{const p=et.customerOrder(o),l=p.orderItemList().size().eval();if(l==null)throw new Error("Selected item list unexpectedly has a null size");return{id:o.id,version:o.version,orderNumber:p.orderNumber().eval(),orderDate:p.orderDate().eval(),status:{name:p.status().name().eval(),color:p.status().color().eval()},items:Array.from({length:l},(a,u)=>({productName:p.orderItemList().get(u).productName().eval(),quantity:p.orderItemList().get(u).quantity().eval()})),itemCount:o.itemCount}}),metadata:{totalCount:r.totalCount,pageOffset:1,pageSize:1,aggregations:r.data.aggregations,searchWarnings:e.dynamicSearchWarnings},facets:{statusCounts:r.data.facets.statusCounts.map(o=>({id:o.id,name:et.orderStatus(S.fromRecord(o)).name().eval(),color:et.orderStatus(S.fromRecord(o)).color().eval(),orderCount:o.orderCount,orderTotalAmount:o.orderTotalAmount}))}};St.textContent=JSON.stringify(i,null,2);const s=d.evidence.snapshot(),h=s.map(o=>{const p=o.traceChain??[],l=p.filter(m=>m.kind==="purpose"),a=l.length===1?`${l[0].detail}: ${p.filter(m=>m.kind==="comment").map(m=>m.detail).join(" → ")}`:"TraceChain unavailable",u=document.createElement("tr");for(const m of[`${o.elapsedMicros} µs`,o.tracePath.find(C=>C.kind==="request")?.name??"—",a,o.debugSQL]){const C=document.createElement("td");C.textContent=m,u.append(C)}return{row:u,businessTrace:a}});bt.replaceChildren(...h.map(o=>o.row)),Nt.textContent=h.map(o=>o.businessTrace).join(` `),$t.textContent=JSON.stringify(s,null,2),it.textContent=`${d.client.storage.toUpperCase()} · ${r.totalCount} matches · ${s.length} SQL statements · ${d.diagnostics.length} diagnostics · policy installed · ready`}async function mt(d){it.textContent=`Opening ${d.toUpperCase()} SQLite/WASM…`;const t=R;R=void 0,await t?.client.close();const e=await Qt(d);R=e,await ct(e),await tt(e)}function X(d){it.textContent=d instanceof Error?`${d.name}: ${d.message}`:String(d)}Y.addEventListener("click",async()=>{if(R){Y.disabled=!0;try{await tt(R)}catch(d){X(d)}finally{Y.disabled=!1}}});document.querySelector("#preset").addEventListener("click",()=>{lt.value=JSON.stringify(Tt,null,2),Y.click()});dt.addEventListener("change",()=>{R&&tt(R).catch(X)});Z.addEventListener("change",()=>{const d=Z.checked?"opfs":"memory";localStorage.setItem("teaql-browser-order-storage",d),mt(d).catch(X)});rt.addEventListener("click",async()=>{if(R){rt.disabled=!0;try{await R.client.reset(R.context),await ct(R),await tt(R)}catch(d){X(d)}finally{rt.disabled=!1}}});mt(Z.checked?"opfs":"memory").catch(X); diff --git a/dist/assets/style-DVG2mb5q.css b/dist/assets/style-DVG2mb5q.css new file mode 100644 index 0000000000000000000000000000000000000000..157f87557015f22314aed6b4a1d4dfaa73445f8e --- /dev/null +++ b/dist/assets/style-DVG2mb5q.css @@ -0,0 +1 @@ +:root{font:16px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;color:#17231b;background:#f5f4ed;font-synthesis:none;--ink: #17231b;--muted: #677067;--paper: #fffef8;--line: #d8ddd3;--green: #145b37;--green-deep: #0e4329;--lime: #dff45c;--orange: #ef8354;--blue: #2b66d9}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;min-width:320px;background:#f5f4ed}button,input{font:inherit}button,a{-webkit-tap-highlight-color:transparent}.page-shell{width:min(1440px,100%);margin:0 auto;padding:0 42px}.site-header{height:76px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand,.docs-link{color:var(--ink);text-decoration:none;font-weight:750}.brand{display:inline-flex;align-items:center;gap:11px;letter-spacing:-.02em}.brand-mark{width:30px;height:30px;display:grid;place-items:center;border-radius:50%;color:var(--lime);background:var(--green-deep);font-family:Georgia,serif;font-style:italic}.docs-link{color:var(--green);font-size:14px}.header-actions{display:flex;align-items:center;gap:18px}.language-switch{display:flex;gap:3px;padding:3px;border:1px solid var(--line);border-radius:8px}.language-switch button{padding:3px 7px;border:0;border-radius:5px;color:var(--muted);background:transparent;font-size:11px;cursor:pointer}.language-switch button.active{color:#fff;background:var(--green)}.hero{min-height:460px;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(440px,.9fr);align-items:center;gap:72px;padding:76px 0 66px}.eyebrow,.section-index,.query-card-label{margin:0 0 14px;color:var(--green);font-size:11px;font-weight:850;letter-spacing:.18em}h1{margin:0;max-width:820px;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(42px,5.6vw,78px);font-weight:500;line-height:1.08;letter-spacing:-.055em}.hero-intro{max-width:680px;margin:26px 0 0;color:var(--muted);font-size:18px}.model-map{position:relative;min-height:310px;padding:38px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:12px;border:1px solid #bfc8bb;border-radius:28px;background:linear-gradient(145deg,#fdfdf8,#e9eee5);box-shadow:0 18px 48px #213c280f;overflow:hidden}.model-map:before{content:"DOMAIN MODEL";position:absolute;top:18px;left:22px;color:#708073;font-size:10px;font-weight:800;letter-spacing:.16em}.model-flow{width:100%;display:grid;grid-template-columns:1fr auto 1fr auto 1fr;align-items:center;gap:10px}.model-flow>span:not(.model-arrow),.model-leaves span{min-width:0;padding:15px 17px;border:1px solid #b8c2b7;border-radius:12px;background:#fffffadb;font:750 14px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;box-shadow:0 8px 22px #1e3a260d}.model-map small{display:block;margin-top:7px;color:var(--muted);font:12px/1.2 Inter,sans-serif}.model-flow>span.model-root{color:#fff;border-color:var(--green);background:var(--green)}.model-map .model-root small{color:#cce4d4}.model-arrow{color:#809087;font-size:22px;text-align:center}.model-arrow-split{height:22px;line-height:18px}.model-leaves{width:100%;display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.runtime-language-panel{margin-bottom:28px;padding:24px;display:grid;grid-template-columns:minmax(240px,.72fr) minmax(0,1.8fr);align-items:center;gap:30px;border:1px solid var(--line);border-radius:18px;background:var(--paper)}.runtime-language-copy .section-index{margin-bottom:8px}.runtime-language-copy h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(22px,2.4vw,31px);font-weight:500;line-height:1.15;letter-spacing:-.035em}.runtime-language-copy p:last-child{margin:11px 0 0;color:var(--muted);font-size:13px}.runtime-language-selector{display:grid;grid-template-columns:repeat(7,minmax(82px,1fr));gap:8px}.runtime-language{min-width:0;padding:13px 8px 11px;display:flex;align-items:center;flex-direction:column;gap:4px;border:1px solid #d7ddd5;border-radius:12px;color:var(--ink);background:#fafbf7;text-align:center;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.runtime-language:hover{border-color:#98aa9d;background:#fff;transform:translateY(-2px)}.runtime-language.active{color:#fff;border-color:var(--green);background:var(--green);box-shadow:0 8px 20px #145b3724}.runtime-language-icon{font-size:25px;line-height:1.1}.runtime-language strong{overflow:hidden;max-width:100%;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.runtime-language small{color:#78837a;font-size:8px;line-height:1.25}.runtime-language.active small{color:#d5e7da}.runtime-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.runtime-language-panel{grid-template-columns:1fr}.runtime-language-selector{grid-template-columns:repeat(4,minmax(100px,1fr))}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-language-panel{padding:20px 16px;gap:20px}.runtime-language-selector{grid-template-columns:repeat(2,minmax(0,1fr))}.runtime-language:last-child{grid-column:1 / -1}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}} diff --git a/dist/assets/style-SCdXWqgK.css b/dist/assets/style-SCdXWqgK.css deleted file mode 100644 index 8274d2f8ef8b83862a47b0c69f23f755fda89d67..0000000000000000000000000000000000000000 --- a/dist/assets/style-SCdXWqgK.css +++ /dev/null @@ -1 +0,0 @@ -:root{font:16px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;color:#17231b;background:#f5f4ed;font-synthesis:none;--ink: #17231b;--muted: #677067;--paper: #fffef8;--line: #d8ddd3;--green: #145b37;--green-deep: #0e4329;--lime: #dff45c;--orange: #ef8354;--blue: #2b66d9}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;min-width:320px;background:#f5f4ed}button,input{font:inherit}button,a{-webkit-tap-highlight-color:transparent}.page-shell{width:min(1440px,100%);margin:0 auto;padding:0 42px}.site-header{height:76px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand,.docs-link{color:var(--ink);text-decoration:none;font-weight:750}.brand{display:inline-flex;align-items:center;gap:11px;letter-spacing:-.02em}.brand-mark{width:30px;height:30px;display:grid;place-items:center;border-radius:50%;color:var(--lime);background:var(--green-deep);font-family:Georgia,serif;font-style:italic}.docs-link{color:var(--green);font-size:14px}.header-actions{display:flex;align-items:center;gap:18px}.language-switch{display:flex;gap:3px;padding:3px;border:1px solid var(--line);border-radius:8px}.language-switch button{padding:3px 7px;border:0;border-radius:5px;color:var(--muted);background:transparent;font-size:11px;cursor:pointer}.language-switch button.active{color:#fff;background:var(--green)}.hero{min-height:460px;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(440px,.9fr);align-items:center;gap:72px;padding:76px 0 66px}.eyebrow,.section-index,.query-card-label{margin:0 0 14px;color:var(--green);font-size:11px;font-weight:850;letter-spacing:.18em}h1{margin:0;max-width:820px;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(42px,5.6vw,78px);font-weight:500;line-height:1.08;letter-spacing:-.055em}.hero-intro{max-width:680px;margin:26px 0 0;color:var(--muted);font-size:18px}.model-map{position:relative;min-height:310px;padding:38px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:12px;border:1px solid #bfc8bb;border-radius:28px;background:linear-gradient(145deg,#fdfdf8,#e9eee5);box-shadow:0 18px 48px #213c280f;overflow:hidden}.model-map:before{content:"DOMAIN MODEL";position:absolute;top:18px;left:22px;color:#708073;font-size:10px;font-weight:800;letter-spacing:.16em}.model-flow{width:100%;display:grid;grid-template-columns:1fr auto 1fr auto 1fr;align-items:center;gap:10px}.model-flow>span:not(.model-arrow),.model-leaves span{min-width:0;padding:15px 17px;border:1px solid #b8c2b7;border-radius:12px;background:#fffffadb;font:750 14px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;box-shadow:0 8px 22px #1e3a260d}.model-map small{display:block;margin-top:7px;color:var(--muted);font:12px/1.2 Inter,sans-serif}.model-flow>span.model-root{color:#fff;border-color:var(--green);background:var(--green)}.model-map .model-root small{color:#cce4d4}.model-arrow{color:#809087;font-size:22px;text-align:center}.model-arrow-split{height:22px;line-height:18px}.model-leaves{width:100%;display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.runtime-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}} diff --git a/dist/assets/workItems-DraVJWt7.js b/dist/assets/workItems-B6je_A1X.js similarity index 99% rename from dist/assets/workItems-DraVJWt7.js rename to dist/assets/workItems-B6je_A1X.js index b0ae6062d03594b1ac8317d6b745a9cb72d5e143..5058f7c29922f93499efbf63d1d76571fef79cc6 100644 --- a/dist/assets/workItems-DraVJWt7.js +++ b/dist/assets/workItems-B6je_A1X.js @@ -1 +1 @@ -import{S as G,L as c,M as k,C as v,a as I,d as O,e as C,Q as K,R as U,B as z,U as H,D as J,c as Y}from"./dynamic-search-BBmdgl4H.js";import{E as $,O as g}from"./object-location-xgYMemK6.js";class L extends G{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",s=!0,a){return super.relationQuery(t,e,i,r,s,a)}}class m{static teaqlTemporaryId=0;id;title;description;platform;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const i={...t};Object.assign(this,i),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof y?t.platform:y.fromRecord(t.platform),this.markLoaded("platform"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=new m(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new m({id:String(t)})}static teaqlBootstrapNew(t){return new m().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new v([{ruleId:"invalid_type",location:g.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n),n.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"WorkItem",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);for(const[S,f]of Object.entries(n.payload))S!=="id"&&S!=="version"&&this._root.set(this.teaqlEntityKey(),S,f);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();return this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update"),d.scopeFor(p),e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}class y{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--y.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:t?.id?I.empty():new I,writable:!0,enumerable:!1}),t){const i={...t};if(delete i.workItemList,Object.assign(this,i),Array.isArray(t.workItemList)){const r=t.workItemList;this._workItemList=new I(r.map(s=>s instanceof m?s:m.fromRecord(s)),{totalCount:r.totalCount,aggregations:r.aggregations,summary:r.summary,facets:r.facets,isLoaded:r.isLoaded??!0}),this.markLoaded("workItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._workItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const i=new y(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new y({id:String(t)})}static teaqlBootstrapNew(t){return new y().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(h=>!this.isLoaded(h.member));if(u)throw new v([{ruleId:"invalid_type",location:g.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n);const d=n.scopeFor(this.teaqlEntityKey());for(const[u,h]of this._workItemList.entries()){h.teaqlAttachRoot(this._root);const l=h.platform;(this.id===void 0||!h.isLoaded("platform")||(typeof l=="object"&&l!==null?l.id:l)!==this.id)&&h.updatePlatform(this);try{h.teaqlPreflightGraph(t,e,i,d)}catch(p){if(!(p instanceof v))throw p;const S=g.property("work_item_list").index(u);throw new v(p.violations.map(f=>({...f,location:f.location.prefixedBy(S)})))}}}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"Platform",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=d.scopeFor(this.teaqlEntityKey());for(const[q,w]of this._workItemList.entries()){w.teaqlAttachRoot(this._root);const _=w.platform;(this.id===void 0||!w.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&w.updatePlatform(this);try{await w.teaqlSaveWithinGraph(t,e,i,f)}catch(N){if(!(N instanceof v))throw N;const P=g.property("work_item_list").index(q);throw new v(N.violations.map(B=>({...B,location:B.location.prefixedBy(P)})))}}return this}const u=await e.executeMutation(d);for(const[f,q]of Object.entries(n.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,q);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update");const S=d.scopeFor(p);for(const[f,q]of this._workItemList.entries()){q.teaqlAttachRoot(this._root);const w=q.platform;(this.id===void 0||!q.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,i,S)}catch(_){if(!(_ instanceof v))throw _;const N=g.property("work_item_list").index(f);throw new v(_.violations.map(P=>({...P,location:P.location.prefixedBy(N)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const D=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class A{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new X(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({toQuery:()=>new L("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({toQuery:()=>new L("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new L("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof y?n:y.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof y?l:y.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof y?n:y.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class X{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new y}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class x{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Z(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title"),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof m?n:m.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof m?l:m.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof m?n:m.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class Z{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new m}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class R{static platforms(){return new A(!1)}static platformsWithMinimalFields(){return new A(!0)}static workItems(){return new x(!1)}static workItemsWithMinimalFields(){return new x(!0)}}const tt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function et(o){let t=(await R.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(o))[0];t||(t=y.teaqlBootstrapNew("1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(o)),o.withActiveRoot({entity:"Platform",id:t.id})}const it=new U(tt,{Platform:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:g.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:g.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:g.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:g.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:g.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:g.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:g.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:et}),rt={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},F=document.querySelector("#status"),st=document.querySelector("#result"),T=document.querySelector("#persist"),E=document.querySelector("#reset");let b;const M=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";T.checked=M==="opfs";async function nt(o){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await z.open(t,{...rt},{storage:o,databaseName:"teaql-browser-example.sqlite3"});e.install(it);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new H().insertResource("dataService",e).withMutationPolicyRegistry(new J(()=>({identity:i,review:(s,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Y(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Q({context:o}){if(!(await R.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(o)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await new m().updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(o)}async function V(o){const t=await R.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(o.context);st.textContent=JSON.stringify(t,null,2),F.textContent=`${o.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function j(o){F.textContent=`Opening ${o.toUpperCase()} SQLite/WASM…`;const t=b;b=void 0,await t?.client.close();const e=await nt(o);b=e,await Q(e),await V(e)}T.addEventListener("change",()=>{const o=T.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",o),j(o).catch(W)});E.addEventListener("click",async()=>{if(b){E.disabled=!0;try{await b.client.reset(b.context),await Q(b),await V(b)}catch(o){W(o)}finally{E.disabled=!1}}});function W(o){const t=o instanceof Error?o:new Error(String(o));F.textContent=`${t.name}: ${t.message}`}j(M).catch(W); +import{S as G,L as c,M as k,C as v,a as I,d as O,e as C,Q as K,R as U,B as z,U as H,D as J,c as Y}from"./dynamic-search-Ch_QcWVU.js";import{E as $,O as g}from"./object-location-CJfVWqJC.js";class L extends G{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",s=!0,a){return super.relationQuery(t,e,i,r,s,a)}}class m{static teaqlTemporaryId=0;id;title;description;platform;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const i={...t};Object.assign(this,i),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof y?t.platform:y.fromRecord(t.platform),this.markLoaded("platform"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=new m(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new m({id:String(t)})}static teaqlBootstrapNew(t){return new m().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new v([{ruleId:"invalid_type",location:g.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n),n.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"WorkItem",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);for(const[S,f]of Object.entries(n.payload))S!=="id"&&S!=="version"&&this._root.set(this.teaqlEntityKey(),S,f);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();return this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update"),d.scopeFor(p),e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}class y{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--y.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:t?.id?I.empty():new I,writable:!0,enumerable:!1}),t){const i={...t};if(delete i.workItemList,Object.assign(this,i),Array.isArray(t.workItemList)){const r=t.workItemList;this._workItemList=new I(r.map(s=>s instanceof m?s:m.fromRecord(s)),{totalCount:r.totalCount,aggregations:r.aggregations,summary:r.summary,facets:r.facets,isLoaded:r.isLoaded??!0}),this.markLoaded("workItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._workItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const i=new y(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new y({id:String(t)})}static teaqlBootstrapNew(t){return new y().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(h=>!this.isLoaded(h.member));if(u)throw new v([{ruleId:"invalid_type",location:g.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n);const d=n.scopeFor(this.teaqlEntityKey());for(const[u,h]of this._workItemList.entries()){h.teaqlAttachRoot(this._root);const l=h.platform;(this.id===void 0||!h.isLoaded("platform")||(typeof l=="object"&&l!==null?l.id:l)!==this.id)&&h.updatePlatform(this);try{h.teaqlPreflightGraph(t,e,i,d)}catch(p){if(!(p instanceof v))throw p;const S=g.property("work_item_list").index(u);throw new v(p.violations.map(f=>({...f,location:f.location.prefixedBy(S)})))}}}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"Platform",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=d.scopeFor(this.teaqlEntityKey());for(const[q,w]of this._workItemList.entries()){w.teaqlAttachRoot(this._root);const _=w.platform;(this.id===void 0||!w.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&w.updatePlatform(this);try{await w.teaqlSaveWithinGraph(t,e,i,f)}catch(N){if(!(N instanceof v))throw N;const P=g.property("work_item_list").index(q);throw new v(N.violations.map(B=>({...B,location:B.location.prefixedBy(P)})))}}return this}const u=await e.executeMutation(d);for(const[f,q]of Object.entries(n.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,q);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update");const S=d.scopeFor(p);for(const[f,q]of this._workItemList.entries()){q.teaqlAttachRoot(this._root);const w=q.platform;(this.id===void 0||!q.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,i,S)}catch(_){if(!(_ instanceof v))throw _;const N=g.property("work_item_list").index(f);throw new v(_.violations.map(P=>({...P,location:P.location.prefixedBy(N)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const D=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class A{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new X(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({toQuery:()=>new L("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({toQuery:()=>new L("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new L("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof y?n:y.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof y?l:y.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof y?n:y.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class X{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new y}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class x{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Z(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title"),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof m?n:m.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof m?l:m.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof m?n:m.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class Z{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new m}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class R{static platforms(){return new A(!1)}static platformsWithMinimalFields(){return new A(!0)}static workItems(){return new x(!1)}static workItemsWithMinimalFields(){return new x(!0)}}const tt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function et(o){let t=(await R.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(o))[0];t||(t=y.teaqlBootstrapNew("1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(o)),o.withActiveRoot({entity:"Platform",id:t.id})}const it=new U(tt,{Platform:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:g.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:g.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:g.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:g.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:g.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:g.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:g.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:et}),rt={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},F=document.querySelector("#status"),st=document.querySelector("#result"),T=document.querySelector("#persist"),E=document.querySelector("#reset");let b;const M=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";T.checked=M==="opfs";async function nt(o){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await z.open(t,{...rt},{storage:o,databaseName:"teaql-browser-example.sqlite3"});e.install(it);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new H().insertResource("dataService",e).withMutationPolicyRegistry(new J(()=>({identity:i,review:(s,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Y(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Q({context:o}){if(!(await R.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(o)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await new m().updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(o)}async function V(o){const t=await R.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(o.context);st.textContent=JSON.stringify(t,null,2),F.textContent=`${o.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function j(o){F.textContent=`Opening ${o.toUpperCase()} SQLite/WASM…`;const t=b;b=void 0,await t?.client.close();const e=await nt(o);b=e,await Q(e),await V(e)}T.addEventListener("change",()=>{const o=T.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",o),j(o).catch(W)});E.addEventListener("click",async()=>{if(b){E.disabled=!0;try{await b.client.reset(b.context),await Q(b),await V(b)}catch(o){W(o)}finally{E.disabled=!1}}});function W(o){const t=o instanceof Error?o:new Error(String(o));F.textContent=`${t.name}: ${t.message}`}j(M).catch(W); diff --git a/dist/index.html b/dist/index.html index dfbc2fdc83b0c384a9dfa15482fc83bb3dfd8f08..b3a201e6990dcf640e8a34723f9e6ef0bc7e6948 100644 --- a/dist/index.html +++ b/dist/index.html @@ -6,9 +6,9 @@ TeaQL Order Query Playground - - - + + +
@@ -51,6 +51,51 @@
+
+
+

RUNTIME COVERAGE

+

This demo runs TypeScript in your browser.

+

The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.

+
+ +
+

Starting SQLite/WASM…

diff --git a/dist/orders.html b/dist/orders.html index da4005c10592e553808339dc4827e059ea60b5d5..dcff34e2692aa528ed9df1cb7fc61449f83aa1e3 100644 --- a/dist/orders.html +++ b/dist/orders.html @@ -5,10 +5,10 @@ TeaQL browser order TraceChain - - - - + + + +
diff --git a/dist/work-items.html b/dist/work-items.html index 5678d61125ebad3bb4c143319b0d5ca5b52015e5..b23ddbf029e4c4748ef1196d6322f43bc53c3919 100644 --- a/dist/work-items.html +++ b/dist/work-items.html @@ -5,9 +5,9 @@ TeaQL Browser SQLite WorkItems - - - + + + diff --git a/index.html b/index.html index dfbc2fdc83b0c384a9dfa15482fc83bb3dfd8f08..b3a201e6990dcf640e8a34723f9e6ef0bc7e6948 100644 --- a/index.html +++ b/index.html @@ -6,9 +6,9 @@ TeaQL Order Query Playground - - - + + +
@@ -51,6 +51,51 @@
+
+
+

RUNTIME COVERAGE

+

This demo runs TypeScript in your browser.

+

The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.

+
+ +
+

Starting SQLite/WASM…

diff --git a/orders.html b/orders.html index da4005c10592e553808339dc4827e059ea60b5d5..dcff34e2692aa528ed9df1cb7fc61449f83aa1e3 100644 --- a/orders.html +++ b/orders.html @@ -5,10 +5,10 @@ TeaQL browser order TraceChain - - - - + + + +
diff --git a/source/provenance.json b/source/provenance.json index f6a9c0e7c3b1f2c5fa6db6ed011ce2d43ac73fb2..f827ec0616e7e05ec6e1d8bcf16bcf09b1de5704 100644 --- a/source/provenance.json +++ b/source/provenance.json @@ -1,14 +1,14 @@ { "repository": "https://github.com/teaql/teaql-ts", - "commit": "e87b5d843a1bc2ae5f677f402b6b3177a7d40b50", + "commit": "9341b0a1fe5f2c090a39a46f9c03c50e55e27341", "branch": "main", "runtimeVersion": "0.3.1", "sourceDirectory": "source/teaql-ts", "applicationDirectory": "source/teaql-ts/examples/browser-sqlite", "buildDirectory": "dist", "validation": { - "runtimeSuitesPassed": 56, - "runtimeTestsPassed": 604, + "runtimeSuitesPassed": 57, + "runtimeTestsPassed": 608, "runtimeTestsSkipped": 6, "browserSmoke": "passed", "generatedOrderSmoke": "passed" diff --git a/source/teaql-ts/.gitattributes b/source/teaql-ts/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..d4a292f1e396e027ff78e7086a5fcdacde42c6da --- /dev/null +++ b/source/teaql-ts/.gitattributes @@ -0,0 +1 @@ +test-vectors/*.tsv whitespace=-blank-at-eol diff --git a/source/teaql-ts/.github/workflows/example-gate.yml b/source/teaql-ts/.github/workflows/example-gate.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a73d0f86dfa36599e4e77d4c2d5ceacf0703653 --- /dev/null +++ b/source/teaql-ts/.github/workflows/example-gate.yml @@ -0,0 +1,48 @@ +name: Example Gate +on: + pull_request: + push: + branches: [main] + workflow_dispatch: +jobs: + examples: + runs-on: ubuntu-latest + env: + TEAQL_S3_ENDPOINT: http://127.0.0.1:19010 + TEAQL_S3_BUCKET: teaql-ts-example-ci + TEAQL_S3_ACCESS_KEY: teaql-ts-example-ci + TEAQL_S3_SECRET_KEY: teaql-ts-example-ci-fixture-only + steps: + - uses: actions/checkout@v4 + - name: Install example verification tools + run: sudo apt-get update && sudo apt-get install -y ripgrep + - uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + - run: npm install + - run: npm run build + - name: Start dedicated S3 example fixture + run: | + docker run -d --name teaql-ts-example-s3 \ + -p 127.0.0.1:19010:9000 \ + -e RUSTFS_ACCESS_KEY="$TEAQL_S3_ACCESS_KEY" \ + -e RUSTFS_SECRET_KEY="$TEAQL_S3_SECRET_KEY" \ + -e RUSTFS_CONSOLE_ENABLE=false \ + rustfs/rustfs@sha256:41fe89380f4120a337790c02af192c3fe7bb55c3edc2e6e9357b487b47c6ab21 /data + for attempt in {1..30}; do + if curl -sS -o /dev/null --max-time 2 "$TEAQL_S3_ENDPOINT/"; then + exit 0 + fi + if [[ "$(docker inspect --format '{{.State.Running}}' teaql-ts-example-s3)" != true ]]; then + docker logs teaql-ts-example-s3 + exit 1 + fi + sleep 1 + done + docker logs teaql-ts-example-s3 + exit 1 + - run: ./scripts/verify-examples.sh + - name: Stop dedicated S3 example fixture + if: always() + run: docker rm -f teaql-ts-example-s3 || true diff --git a/source/teaql-ts/.github/workflows/release.yml b/source/teaql-ts/.github/workflows/release.yml new file mode 100644 index 0000000000000000000000000000000000000000..392144899ba916714a66532205d7da2e8dbfc672 --- /dev/null +++ b/source/teaql-ts/.github/workflows/release.yml @@ -0,0 +1,32 @@ +name: Publish TypeScript package + +on: + workflow_dispatch: + push: + tags: + - "typescript-v*" + +jobs: + publish: + runs-on: ubuntu-latest + environment: npm + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "24" + registry-url: https://registry.npmjs.org + cache: npm + - run: npm ci + - name: Verify tag matches package version + run: test "${GITHUB_REF_NAME#typescript-v}" = "$(node -p 'require("./package.json").version')" + # Keep native SQLite lifecycle coverage deterministic and verify the + # current Node LTS used by generated TeaQL projects. + - run: npm test -- --runInBand + - run: npm run build + - name: Upgrade npm for trusted publishing + run: npm install --global npm@latest + - run: npm publish --access public diff --git a/source/teaql-ts/.gitignore b/source/teaql-ts/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ef5a7e7b07abaf45fcfc586604728dc44f42ea70 --- /dev/null +++ b/source/teaql-ts/.gitignore @@ -0,0 +1,2 @@ +node_modules +/examples/browser-sqlite/dist/ diff --git a/source/teaql-ts/README.md b/source/teaql-ts/README.md index f5ce049d8bf705f7ea9a42699b3faa05b152d47d..91eb927cc29bb23fc8be71cbaf6440977a7273f3 100644 --- a/source/teaql-ts/README.md +++ b/source/teaql-ts/README.md @@ -352,6 +352,7 @@ Request JSON is not allowed to replace those trusted capabilities. - [Browser SQLite example](examples/browser-sqlite/README.md) - [Facet example](examples/facet-trace/README.md) - [Trace Chain example](examples/trace-chain/README.md) +- [Binary object storage and temporary S3 URLs](examples/object-storage/README.md) ## Safe troubleshooting diff --git a/source/teaql-ts/RUNTIME_GUIDE.md b/source/teaql-ts/RUNTIME_GUIDE.md new file mode 100644 index 0000000000000000000000000000000000000000..905c7d11a804da0f151148f85e9f98742e6475ee --- /dev/null +++ b/source/teaql-ts/RUNTIME_GUIDE.md @@ -0,0 +1,363 @@ +# TeaQL TypeScript Runtime Guide + +Reference details for the runtime and its extension points. Start with the +[README](README.md) for the application-facing APIs and runnable examples. + +Current published versions and acceptance status are tracked in +[TeaQL Conformance](https://github.com/teaql/teaql-conformance). Individual +verification notes below describe their own scope, not all-provider parity. + +## Request intent and version compatibility + +The 0.3.0 runtime provides validated, request-owned `QueryIntent` and +`MutationIntent`. Query Request requires non-blank `comment` and `purpose`; Mutation +Request requires non-blank `comment`, also exposed to policy/audit as its root +reason. Existing generated `.comment(...).purpose(...)` and `.auditAs(...)` +spelling stays unchanged after regeneration. + +Missing intent fails with `REQUEST_COMMENT_REQUIRED` at `comment`, or +`QUERY_PURPOSE_REQUIRED` at `purpose`, before policies and provider access. +The errors identify the request kind without echoing payload values. Context +resources, fabricated trace frames, child comments, and logging switches do +not supply a missing request property. Unicode whitespace validation follows +Rust; valid text is preserved without trimming. + +Low-level adapters can construct `QueryRequest(query)` or +`MutationRequest(mutation)`. Envelopes capture intent independently of mutable +builders. SQL relations, aggregates, Facets and TFP Facet serialization inherit +the root intent. Generated library guards delegate to the runtime validators; +pair the changed generator with this local runtime before testing. + +The SQL execution path now uses the Rust-baseline canonical algorithm. Typed +nodes separate entity/relation names from operation/qualified-property detail. +The physical path contains no intent nodes; validated comment, purpose and root +audit reason are separate fields. Mutation lineage is a separate typed carrier, +not another name for the physical SQL path. Readback failure records a distinct +`Sql(select)` path instead of adding a second SQL node to a mutation path. + +Query provenance belongs to immutable request snapshots. Derived relation, +aggregate and Facet requests carry the original root and append the local +relation name with its qualified property. Provenance never comes from a +caller-supplied `__teaqlTracePath` or a mutable Context stack. This also preserves +the root through overlapping queries and stream execution. Privacy projection +scrubs reason text without removing structural typed identity or path shape. + +Graph saves now receive an explicit validated `MutationIntent` and an +operation-owned `GraphMutationSession`. Persistent immutable parent scopes carry +branch-local reasons; an unrelated request cannot join the active transaction +or borrow another graph's scope. Type plus ID distinguishes ledger entries; +an entity's complete ledger chain replaces its graph fallback. Database-assigned +IDs are captured before saving descendants. Context owns no lineage stack. + +Audits are queued until the whole graph commits and discarded on rollback. +After commit, a failing sink does not stop remaining cleanup/audits or pretend +the database rolled back. `GraphCommittedError.committed` tells callers not to +retry the operation as an uncommitted write. SQL metadata still distinguishes +the physical path, root intent and each entity's mutation lineage. Failed +readback remains a separate SELECT outcome. + +Successful SQL mutations also retain the actual persisted-row SELECT, not just +failed readbacks. `MutationResult.metadata` is a trusted internal logical write +summary; its frozen `statements` array contains ordered write/SELECT facts. +There is no additional query for tracing. Safe sinks receive each physical fact +once with inherited intent and per-item lineage, without double-counting audits. +Query/mutation log switches control diagnostic output independently; an installed +evidence sink and returned raw result metadata remain available when logs are +off. Use the evidence store's own modes to disable evidence collection. Do not +serialize raw result metadata across a trust boundary or log it directly. + +The runtime adapter SPI is intentionally changed to +`executeGraphSave(intent, async graph => ...)`; adapter code must create each +request with `graph.request(...)`. Regenerate domain libraries rather than +patching their source. The generated public `.auditAs(...).save(context)` API +is unchanged. A child can supply its own local reason or inherit its parent; +save no longer overwrites child reasons with the root reason. + +The [generated SQLite example](examples/trace-chain/README.md) verifies the +six-entity graph through real Q/E/Mutation APIs, independent overlapping saves, +provider/readback failures and two runs on the same database without cleanup. +Its generated library is hash-checked and unmodified. Shared graph vectors, +native transaction/audit tests and the prior canonical SQL cases are separate +evidence, not substitutes for generated acceptance. + +The [generated School Facet example](examples/facet-trace/) verifies 48 +root/nested/loaded-relation combinations twice on a retained SQLite database. +It covers exact/prefix operands, empty metadata, full counts despite a limit-one +list, exact ordered ancestry and future-binding masking. Diagnostic logging +on/off is distinct from its explicitly installed safe evidence collector. +`bash examples/facet-trace/verify.sh` rebuilds and resolves the local runtime; +the all-examples gate includes it and checks generated library fingerprints. + +Relation assembly preserves scalar keys before hydrated references or aggregate +aliases replace their source fields. A reference filtered to null does not +remove its child from an enclosing list or break a sibling using the same FK. +Private per-load key capture and per-chunk snapshots cover lists and streams; +no key cache is added to records, mutation ledgers or UserContext. The example +gate runs a small real-SQLite fixture with text keys, empty parents, nested +graphs, filtered references and diagnostic logging on/off. These are native +regression cases, separate from the generated Q/E/save acceptance above. + +Prepared same-type batches, complete entry-point/deep privacy coverage, +file-backed/Expo graph acceptance and immutable internal Registry replay remain +open. Verify local source with `npm test -- --runInBand` and +`bash scripts/verify-examples.sh` before any internal artifact or public release. +The 0.3.0 release is verified separately from these individual source cases; +no complete Trace Chain or all-provider claim is implied. + +## Sensitive log data + +Runtime diagnostic logs redact payload values by default, before delivery to +file, console, buffers, or custom logging sinks. Selecting a diagnostic sink +alone does not authorize plaintext. For controlled troubleshooting only: + +```bash +export TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS=I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK +``` + +Only this exact value enables plaintext permission; empty values, `true`, and +whitespace variants do not. Enabling it emits a warning. Credential-classified +fields remain redacted. The flag does not force every sink to expose values. +SQL without reliable field/literal provenance may be suppressed and marked +`NOT REPLAYABLE`. Execution parameters and persisted business data are unchanged. + +Do not put sensitive data in free-text comments or purpose declarations. +TeaQL cannot govern arbitrary application prints or independent driver loggers; +configure those separately. This setting does not erase older plaintext files. +Restrict access and retention when using plaintext diagnostics, then unset the +variable and restart processes when troubleshooting is complete. + +`@teaql/teaql` is the core TypeScript runtime framework for the **TEAQL Federation Protocol (TFP)**. It provides an ultra-lightweight engine responsible for securely translating elegant chained DSLs into cross-language ASTs, allowing you to enjoy a strongly-typed, highly expressive data fetching experience on the frontend (or Node.js). + +## Recommended Agent Harness + +When building database-backed or federated applications with the TeaQL +TypeScript runtime, we recommend using it together with the [TeaQL Agent Kit](https://github.com/teaql/teaql-agent-kit). +The Agent Kit is TeaQL's continuously evolving **Harness Engineering** method. +It gives coding agents a model-mediated, executable workflow for domain +modeling, deterministic evaluation and repair, code generation, implementation, +and evidence-based verification as the generator and runtimes evolve. + +## Runtime Profiles + +`@teaql/teaql` uses explicit package entry points as runtime profiles. Import only the +profile needed by the application: + +| Profile | Import | Runtime | Database driver | +| --- | --- | --- | --- | +| Browser / TFP | `@teaql/teaql` | Browser or Node HTTP client | None | +| PostgreSQL | `@teaql/teaql/sql/postgres` | Node.js | `pg` | +| MySQL | `@teaql/teaql/sql/mysql` | Node.js | `mysql2` | +| SQLite | `@teaql/teaql/sql/sqlite` | Node.js | `better-sqlite3` | +| Expo SQLite | `@teaql/teaql/sql/expo-sqlite` | React Native / Expo | `expo-sqlite` | +| Browser SQLite | `@teaql/teaql/sql/browser-sqlite` | Browser Web Worker | `@sqlite.org/sqlite-wasm` | + +## Security Boundary + +The browser/TFP profile is a client, not a key-custody service. It produces a +controlled AST and sends declared comment/purpose to a trusted TeaQL backend; +it cannot override server tenant, role, field, hard-limit, or optimistic-lock +policy. Browser SQLite is local application storage and does not turn the +browser into a public TFP server. + +When a Java, Rust, Go, or .NET backend returns a TeaQL opaque entity reference, +TypeScript treats it as an indivisible string and returns it only for the +operation and purpose for which it was issued. Client code must not parse, +rewrite, log, or manufacture the token, and must not fall back to exposing a raw +internal ID/version pair. The current TypeScript profile deliberately does not +hold backend AES keys or provide local encode/decode APIs; this is a supported +frontend boundary rather than a conformance defect. + +Local SQL diagnostics show expanded SQL with parameters masked by default. +Plaintext submitted values require the explicit, access-controlled diagnostic +opt-in above. The server-side envelope, golden vector, stable errors, and +development-only raw-reference acknowledgement are defined in the canonical +[opaque entity reference contract](https://github.com/teaql/teaql-conformance/blob/main/design/opaque-entity-references.md). + +## Mutation Policy installation + +All profiles support the same application-owned Mutation Policy identity, +approval, warning, and evidence contract. Node SQL and browser SQLite review a +complete generated graph after Checker/Fix and before the first provider +mutation. The TFP browser/Node client applies the policy before `fetch` as +defense in depth; the receiving server still performs the authoritative review. + +```typescript +const context = new UserContext() + .withMutationPolicyRegistry(policyRegistry) + .withMutationPolicyApprovalProvider(approvalProvider) + .withMutationGovernanceSink(warningSink); + +client.setUserContext(context); +``` + +A customer policy denial reaches neither SQL, the browser SQLite worker, nor a +TFP mutation request. Missing customer policy or exact approval uses stable +warning codes and remains fail-open, while explicit denial and incomplete graph +plans fail closed. Policy implementations are installed only through trusted +context assembly and are never accepted from JSON or TFP payloads. + +### Browser / TFP profile + +The default entry point contains the AST, Peggy-generated controlled query +parser, and TFP HTTP client. It does not import or bundle PostgreSQL, MySQL, or +SQLite drivers. + +```bash +npm install @teaql/teaql +``` + +```typescript +import { SelectQuery, TeaQLClient } from "@teaql/teaql"; + +const client = new TeaQLClient({ baseUrl: "/api/teaql" }); +const tasks = await client.executeQuery( + new SelectQuery("Task") + .comment("task board initial load") + .limit(20) + .purpose("show current tasks"), +); +``` + +Database drivers are optional peer dependencies. A browser application should +import only from `@teaql/teaql` and should not install a SQL driver package. + +### Node SQL profiles + +Install only the driver selected by the service: + +```bash +# PostgreSQL +npm install @teaql/teaql pg + +# MySQL +npm install @teaql/teaql mysql2 + +# SQLite +npm install @teaql/teaql better-sqlite3 +``` + +Use the matching subpath when building a runtime manually. `ENTITY_SCHEMAS` is +normally generated by `teaql-code-gen`: + +```typescript +import { PostgreSQLTeaQLClient } from "@teaql/teaql/sql/postgres"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; + +const client = new PostgreSQLTeaQLClient( + process.env.DATABASE_URL!, + ENTITY_SCHEMAS, +); +const ctx = { client }; +``` + +The MySQL and SQLite forms are identical apart from the selected profile: + +```typescript +import { MySQLTeaQLClient } from "@teaql/teaql/sql/mysql"; +import { SQLiteTeaQLClient } from "@teaql/teaql/sql/sqlite"; +``` + +Generated Node projects wrap these classes in `teaql-node-postgres.ts`, +`teaql-node-mysql.ts`, or `teaql-node-sqlite.ts`, so application code normally +imports the generated wrapper and does not pass `ENTITY_SCHEMAS` itself. + +In a TeaQL model, `data_service="postgres"`, `data_service="mysql"`, or +`data_service="sqlite"` selects the corresponding generated SQL profile. The +regular TypeScript/browser generation profile continues to use TFP and has no +database-driver import. + +### React Native / Expo SQLite profile + +Generated `typescript-app-expo` workspaces open and ensure their local schema +on first launch, so a new user does not need to download or prepare a database +file. The generated schema remains the source of truth: + +```typescript +import * as SQLite from "expo-sqlite"; +import { ExpoSQLiteTeaQLClient } from "@teaql/teaql/sql/expo-sqlite"; +import { ENTITY_SCHEMAS } from "./teaql-expo-sql"; + +const database = await SQLite.openDatabaseAsync("order-management.db"); +const client = new ExpoSQLiteTeaQLClient(database, ENTITY_SCHEMAS); +``` + +Local queries still require `comment(...)` and `purpose(...)`, and saves still +require an audit reason. The same generated model can instead use the default +TFP client for authenticated server queries. Tenant, user, permission, purpose +policy, hard-limit policy, and continuous-page cursor policy must be supplied +by trusted runtime context; they are not accepted from federation JSON. + +### Browser SQLite/WASM profile + +Browser-local applications can execute the same generated Q API, E API, +Checker/Fix rules, audited mutations, and Runtime Module bootstrap without a +backend. Install the official SQLite/WASM package and create an +application-owned worker entry point so bundlers can package the worker and +WASM assets correctly: + +```bash +npm install @teaql/teaql @sqlite.org/sqlite-wasm +``` + +```typescript title="sqlite.worker.ts" +import sqliteWasmUrl from "@sqlite.org/sqlite-wasm/sqlite3.wasm?url"; +import { startBrowserSQLiteWorker } from "@teaql/teaql/sql/browser-sqlite-worker"; + +startBrowserSQLiteWorker({ wasmUrl: sqliteWasmUrl }); +``` + +```typescript +import { BrowserSQLiteTeaQLClient } from "@teaql/teaql/sql/browser-sqlite"; + +const worker = new Worker(new URL("./sqlite.worker.ts", import.meta.url), { + type: "module", +}); +const client = await BrowserSQLiteTeaQLClient.open(worker, ENTITY_SCHEMAS, { + storage: "memory", // deterministic default; use "opfs" only by explicit choice +}); +client.install(GENERATED_RUNTIME_MODULE); +const context = new UserContext().insertResource("dataService", client); +client.setUserContext(context); +await context.ensureSchema(); +``` + +`client.reset(context)` drops browser-local tables, explicitly reconciles the +schema again, and runs the generated mutation bootstrap. OPFS requires the +COOP/COEP headers documented by SQLite. The first browser profile deliberately +buffers stream results and does not promise multi-tab database coordination. +It is intended for Playground, offline, and local-data scenarios—not as a +trusted authorization boundary for tenant or permission enforcement. + +See [`examples/browser-sqlite`](./examples/browser-sqlite) for the executable +memory, OPFS, Mutation Policy, generated-mutation seed, Q API, and reset +verification. + +## Generated query and mutation APIs + +See the [README examples](README.md#query-and-read-the-result) for generated +Q/E and audited Save usage. Always supply non-empty comment and purpose; +load complete fields before modifying a persisted object. `QueryParser` returns +a controlled request, not arbitrary executable JavaScript. Supply the generated +Q entry point and an intentional, bounded query before executing it. + +## 📂 Project Architecture and Domain Examples + +Architecturally, `@teaql/teaql` adheres to the philosophy of absolute isolation between the **Framework Layer** and the **Business Layer**. The `src` directory in this repository is the pure, uncontaminated core engine, while all practical business demonstrations are divided by domain in the `examples` directory. + +```text +teaql-ts/ +├── src/ # [Framework Layer] Pure core engine, no business code +│ ├── core/ # AST definitions +│ ├── parser/ # DSL reflection and secure interpreter +│ ├── tfp/ # Federation network transport protocol layer +│ └── sql/ # Explicit Node, Expo and browser SQLite profiles +│ +└── examples/ # [Business Example Layer] Integrated demos for various use cases + │ + ├── task-board/ # Example 1: Task Board System Domain + │ ├── ts-lib-core/ # Strongly-typed domain models generated by the code generator (e.g. Task, Q.ts) + │ ├── app-dynamic/ # Runtime Demo based on dynamic string parsing + │ └── app-native/ # Demo based on fluent hardcoded API + │ + └── ecommerce-system/ # Example 2: [Planned] E-commerce System Example +``` diff --git a/source/teaql-ts/docs/releases/0.3.1.md b/source/teaql-ts/docs/releases/0.3.1.md new file mode 100644 index 0000000000000000000000000000000000000000..5dbc259db191e968fd4caf5fb3d1e47cf63e4dab --- /dev/null +++ b/source/teaql-ts/docs/releases/0.3.1.md @@ -0,0 +1,19 @@ +# TypeScript 0.3.1 + +Tracking: [TypeScript #51](https://github.com/teaql/teaql-ts/issues/51) and +[conformance #109](https://github.com/teaql/teaql-conformance/issues/109). + +The optional Node standard telemetry module uses trusted environment activation +and reports enabled/disabled startup settings. Supported runtime operations +produce full safe traces, metrics and logs without per-method instrumentation. +Expanded SQL stays masked, and each completion carries its own physical identity. +Owned SDK queues, acknowledgement handling and finite shutdown preserve customer +globals, business outcomes and independent audit. + +Node telemetry is not enabled in browser SQLite or Expo. Regenerate libraries to +retire the separate page terminal and adopt the current request-tree/search metadata; +use ordinary list execution with offset/limit and explicit count when needed. + +The conformance `2026-10-13-standard-telemetry-onboarding` report retains source and +internal-candidate tests. Signed-tag, final-package and public-consumer verification +are separate gates, not inferred from those candidate results. diff --git a/source/teaql-ts/examples/browser-sqlite/README.md b/source/teaql-ts/examples/browser-sqlite/README.md index 41ae6eb627c02b5e2ce2be329a32c2b359aeff75..807076bf82a6c4bbc2d30095fa96d086f366a5ba 100644 --- a/source/teaql-ts/examples/browser-sqlite/README.md +++ b/source/teaql-ts/examples/browser-sqlite/README.md @@ -6,6 +6,12 @@ dedicated browser worker. It includes deterministic, internally consistent demo data and thirteen runnable examples organized as basic, aggregate, filtered, and dynamic queries. +This page executes the TeaQL TypeScript runtime and SQLite/WASM directly in the +browser. The model-driven Q and TraceChain contract is also implemented by the +Java, Rust, Go, Python, .NET and Swift runtimes. The seven-language strip links +to each runtime source and marks TypeScript as the current browser runtime; it +does not imply that selecting another link swaps the page's execution engine. + `OrderStatus` is a seventh, constant model object rather than a string field. Its five fixed values are reconciled through `RuntimeModule` bootstrap, orders store the status object ID, and generated Q expressions select, filter, and @@ -41,8 +47,8 @@ page query. The order-center projection intentionally contains only the four visible table columns: order number, order date, the `OrderStatus` object, and item preview. It does not load Platform or Customer. The Q chain follows the page vertically: -dynamic filter, `countAs('totalOrders')`, status facet, four table projections, then page -execution. +dynamic filter, `countAs('totalOrders')`, status facet, four table projections, +then bounded `offset` / `limit` list execution. ```bash npm install diff --git a/source/teaql-ts/examples/browser-sqlite/index.html b/source/teaql-ts/examples/browser-sqlite/index.html index 6a34167138fc53442292c66bf6a6192dad4c5459..2ce8e83c0a8b975f355b001297e113fc0523bcc0 100644 --- a/source/teaql-ts/examples/browser-sqlite/index.html +++ b/source/teaql-ts/examples/browser-sqlite/index.html @@ -48,6 +48,51 @@
+
+
+

RUNTIME COVERAGE

+

This demo runs TypeScript in your browser.

+

The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.

+
+ +
+

Starting SQLite/WASM…

diff --git a/source/teaql-ts/examples/browser-sqlite/package-lock.json b/source/teaql-ts/examples/browser-sqlite/package-lock.json index bf06ad3a555e96b2e4d468f0aa9b76bf2f23967c..ef72c29e372820bf833e30eaa268e48c7e557440 100644 --- a/source/teaql-ts/examples/browser-sqlite/package-lock.json +++ b/source/teaql-ts/examples/browser-sqlite/package-lock.json @@ -19,18 +19,21 @@ }, "../..": { "name": "@teaql/teaql", - "version": "0.3.0", + "version": "0.3.1", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" }, "devDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", "@opentelemetry/api-logs": "^0.221.0", "@opentelemetry/context-async-hooks": "^2.10.0", "@opentelemetry/core": "^2.10.0", "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", "@opentelemetry/resources": "^2.10.0", "@opentelemetry/sdk-logs": "^0.221.0", "@opentelemetry/sdk-metrics": "^2.10.0", @@ -52,8 +55,20 @@ "typescript": "5.4.5" }, "peerDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", "@opentelemetry/api": "^1.9.1", "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", "better-sqlite3": "^12.10.0", "expo-sqlite": "*", @@ -62,12 +77,48 @@ "pg-query-stream": "^4.7.0" }, "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/s3-request-presigner": { + "optional": true + }, "@opentelemetry/api": { "optional": true }, "@opentelemetry/api-logs": { "optional": true }, + "@opentelemetry/context-async-hooks": { + "optional": true + }, + "@opentelemetry/core": { + "optional": true + }, + "@opentelemetry/exporter-logs-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-metrics-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-http": { + "optional": true + }, + "@opentelemetry/otlp-transformer": { + "optional": true + }, + "@opentelemetry/resources": { + "optional": true + }, + "@opentelemetry/sdk-logs": { + "optional": true + }, + "@opentelemetry/sdk-metrics": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, "@sqlite.org/sqlite-wasm": { "optional": true }, diff --git a/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs b/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs index 2dcce59961fb89e6906eea87f8539cb0b2a5c9d8..964f2434b9a9dfe6223996396b8989a6f80d5d98 100644 --- a/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs +++ b/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs @@ -65,6 +65,20 @@ try { if (defaultLocale.lang !== 'en' || defaultLocale.title !== 'Choose a query' || !defaultLocale.englishActive) { throw new Error(`English was not the default locale: ${JSON.stringify(defaultLocale)}`); } + const runtimeLanguages = await page.evaluate(() => ({ + title: document.querySelector('#runtime-language-title')?.textContent || '', + links: [...document.querySelectorAll('.runtime-language')].map(element => ({ + name: element.querySelector('strong')?.textContent || '', + href: element.getAttribute('href') || '', + active: element.classList.contains('active'), + })), + })); + if (runtimeLanguages.title !== 'This demo runs TypeScript in your browser.' + || runtimeLanguages.links.length !== 7 + || runtimeLanguages.links.filter(language => language.active).map(language => language.name).join() !== 'TypeScript' + || runtimeLanguages.links.some(language => !language.href.startsWith('https://github.com/teaql/'))) { + throw new Error(`Seven-runtime selector is incomplete: ${JSON.stringify(runtimeLanguages)}`); + } if (!firstStatus.includes('policy installed')) { throw new Error(`Browser runtime did not install Mutation Policy: ${firstStatus}`); } @@ -184,7 +198,9 @@ try { || !dashboardQuery.includes(".sumOrderTotalAmountAs('orderTotalAmount')") || !dashboardQuery.includes(".facetByStatusAs('statusCounts'") || !dashboardQuery.includes('.filterByJson(searchParams)') - || !dashboardQuery.includes('.executeForPage(ctx, pageOffset, pageSize)') + || !dashboardQuery.includes('.offset(pageOffset)') + || !dashboardQuery.includes('.limit(pageSize)') + || !dashboardQuery.includes('.executeForList(ctx)') || dashboardQuery.includes('new SelectQuery') || dashboardQuery.includes('.selectCode()') || dashboardQuery.includes('Q.orderStatuses()\n') @@ -208,7 +224,9 @@ try { '.selectOrderDate()', '.selectStatusWith(', '.selectItemListWith(', - '.executeForPage(ctx, pageOffset, pageSize)', + '.offset(pageOffset)', + '.limit(pageSize)', + '.executeForList(ctx)', ].map(fragment => dashboardQuery.indexOf(fragment)); if (visualQueryOrder.some(index => index < 0) || visualQueryOrder.some((index, position) => position > 0 && index <= visualQueryOrder[position - 1])) { @@ -323,12 +341,16 @@ try { && document.querySelector('#result-title')?.textContent === '动态:字段白名单'); const chineseLocale = await page.evaluate(() => ({ title: document.querySelector('#query-browser-title')?.textContent || '', + runtimeTitle: document.querySelector('#runtime-language-title')?.textContent || '', + currentRuntime: document.querySelector('.runtime-language.active small')?.textContent || '', evidenceTitle: document.querySelector('.sql-card-heading .query-card-label')?.textContent || '', evidenceColumns: [...document.querySelectorAll('.execution-evidence th')].map(element => element.textContent || ''), executionId: document.querySelector('.evidence-time')?.dataset.executedAt || '', rows: [...document.querySelectorAll('#sql-output .evidence-row')].map(element => element.textContent || ''), })); if (chineseLocale.title !== '选择一个查询' + || chineseLocale.runtimeTitle !== '这个演示在浏览器中运行 TypeScript。' + || chineseLocale.currentRuntime !== '当前浏览器 runtime' || chineseLocale.evidenceTitle !== '执行证据' || chineseLocale.evidenceColumns.join('|') !== '时间|身份|追踪链|SQL' || chineseLocale.executionId !== beforeLocaleSwitch.executionId diff --git a/source/teaql-ts/examples/browser-sqlite/src/generated/Q.ts b/source/teaql-ts/examples/browser-sqlite/src/generated/Q.ts index d7208fef9c851483a0fb906753200bfc391f4e63..eeb3b24a95ae7c0f6af8d1372b65fd86ba131fa8 100644 --- a/source/teaql-ts/examples/browser-sqlite/src/generated/Q.ts +++ b/source/teaql-ts/examples/browser-sqlite/src/generated/Q.ts @@ -6,7 +6,6 @@ import { UserContext, executeRelationFacets, type QueryOperation, - type TeaQLPage, } from 'teaql-ts'; import { ORDER_STATUS } from '../order-model'; @@ -103,48 +102,38 @@ abstract class GeneratedRequest { } async executeForList(context: UserContext): Promise> { - this.ensureIntent(); - const service = this.service(context); - const query = this.toQuery(); - const rows = await service.executeQuery(context.prepareQuery(query)); - const data = new SmartList(rows); - if (query.facets.length) { - data.facets = await executeRelationFacets( - service, nested => context.prepareQuery(nested), query, query.facets, - ); - } - return data; + return this.executeList(context, this.pageTotalAlias !== undefined); } async executeForRows(context: UserContext): Promise> { - return this.executeForList(context); + return this.executeList(context, false); } - async executeForPage(context: UserContext, offset: number, limit: number): Promise> { + private async executeList(context: UserContext, counted: boolean): Promise> { this.ensureIntent(); const service = this.service(context); - const countQuery = this.toQuery(); - // The runtime derives the count child request and its comment from this - // alias. Generated requests do not manufacture TraceChain text. - const totalCount = await service.executeCount( - countQuery, + const query = this.toQuery(); + const totalCount = counted ? await service.executeCount( + query, this.pageTotalAlias, - this.pageTotalAlias - ? { kind: 'named-count', method: 'countAs', alias: this.pageTotalAlias } - : undefined, - ); - const pageQuery = this.toQuery().offset(offset).limit(limit); - const data = new SmartList( - await service.executeQuery(context.prepareQuery(pageQuery)), - { totalCount }, - ); - if (this.pageTotalAlias) data.aggregations[this.pageTotalAlias] = totalCount; - if (countQuery.facets.length) { + { kind: 'named-count', method: 'countAs', alias: this.pageTotalAlias }, + ) : undefined; + const rowsQuery = query.clone(); + if (counted) { + rowsQuery.aggregateItems = rowsQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === 'count' && item.alias === this.pageTotalAlias)); + } + const rows = await service.executeQuery(context.prepareQuery(rowsQuery)); + const data = new SmartList(rows, { totalCount }); + if (counted && this.pageTotalAlias !== undefined) { + data.aggregations[this.pageTotalAlias] = totalCount; + } + if (query.facets.length) { data.facets = await executeRelationFacets( - service, nested => context.prepareQuery(nested), countQuery, countQuery.facets, + service, nested => context.prepareQuery(nested), query, query.facets, ); } - return { data, totalCount, offset, limit }; + return data; } protected addFilter(filter: unknown): this { this.filters.push(filter); return this; } protected select(...fields: string[]): this { this.query.select(fields); return this; } @@ -390,22 +379,13 @@ export class CustomerOrderRequest extends GeneratedRequest { averageTotalAmountAs(alias: string): this { return this.aggregate('Avg', 'totalAmount', alias); } override executeForList(context: UserContext): Promise> { - this.applyRowCount(); + if (this.countAlias) this.includePageTotalAs(this.countAlias); return super.executeForList(context); } override executeForRows(context: UserContext): Promise> { this.applyRowCount(); - return super.executeForList(context); - } - - override executeForPage( - context: UserContext, - offset: number, - limit: number, - ): Promise> { - if (this.countAlias) this.includePageTotalAs(this.countAlias); - return super.executeForPage(context, offset, limit); + return super.executeForRows(context); } private applyRowCount(): void { diff --git a/source/teaql-ts/examples/browser-sqlite/src/main.ts b/source/teaql-ts/examples/browser-sqlite/src/main.ts index 2bd68ea67295da25f04d27c10e917a7c48038f9e..d9c7369838c668e7dbf0bab6f63d197b5569d175 100644 --- a/source/teaql-ts/examples/browser-sqlite/src/main.ts +++ b/source/teaql-ts/examples/browser-sqlite/src/main.ts @@ -65,6 +65,11 @@ type LocalizedCopy = Readonly<{ en: string; zh: string }>; const UI_COPY: Readonly> = { heroTitle: { en: 'Understand TeaQL queries through a familiar order model.', zh: '用一个熟悉的订单模型,看懂 TeaQL 查询。' }, heroIntro: { en: 'Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.', zh: '平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。' }, + runtimeCoverage: { en: 'RUNTIME COVERAGE', zh: 'RUNTIME 覆盖' }, + runtimeTitle: { en: 'This demo runs TypeScript in your browser.', zh: '这个演示在浏览器中运行 TypeScript。' }, + runtimeIntro: { en: 'The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.', zh: '同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。' }, + currentBrowserRuntime: { en: 'Current browser runtime', zh: '当前浏览器 runtime' }, + supportedRuntime: { en: 'Supported runtime', zh: '已支持 runtime' }, platform: { en: 'Platform', zh: '平台' }, customer: { en: 'Customer', zh: '用户' }, order: { en: 'Order', zh: '订单' }, item: { en: 'Item', zh: '明细' }, payment: { en: 'Payment', zh: '支付' }, shipment: { en: 'Shipment', zh: '物流' }, @@ -209,16 +214,16 @@ async function runOrderCenter(active: Runtime): Promise { .orderByIdDescending() .comment('load order list') .purpose('render order list page'); - const page = await request.executeForPage( - active.context, - dashboardState.page * dashboardState.pageSize, - dashboardState.pageSize, - ); - const statusRows = page.data.facet('statusCounts') ?? []; + const queryExpression = request.toQExpression('offset(pageOffset)\n .limit(pageSize)\n .executeForList(ctx);'); + const orders = await request + .offset(dashboardState.page * dashboardState.pageSize) + .limit(dashboardState.pageSize) + .executeForList(active.context); + const statusRows = orders.facet('statusCounts') ?? []; return { - orders: page.data, - totalOrders: Number(page.data.aggregations.totalOrders ?? page.totalCount), - filteredOrders: page.totalCount, + orders, + totalOrders: Number(orders.aggregations.totalOrders ?? orders.totalCount), + filteredOrders: orders.totalCount ?? 0, statusFacets: statusRows.map(row => ({ code: statusCodeFor(row), name: String(row.name ?? ''), @@ -229,7 +234,7 @@ async function runOrderCenter(active: Runtime): Promise { search: dashboardState.search, page: dashboardState.page, pageSize: dashboardState.pageSize, - queryExpression: request.toQExpression('executeForPage(ctx, pageOffset, pageSize);'), + queryExpression, }; } @@ -1127,6 +1132,7 @@ function applyLocale(): void { document.querySelector('.language-switch')?.setAttribute('aria-label', locale === 'en' ? 'Language' : '语言'); document.querySelector('.brand')?.setAttribute('aria-label', locale === 'en' ? 'TeaQL Playground home' : 'TeaQL 演练场首页'); document.querySelector('.model-map')?.setAttribute('aria-label', locale === 'en' ? 'Order domain model' : '订单领域模型'); + document.querySelector('.runtime-language-selector')?.setAttribute('aria-label', locale === 'en' ? 'TeaQL runtimes' : 'TeaQL 运行时'); document.querySelector('.runtime-bar')?.setAttribute('aria-label', locale === 'en' ? 'Runtime settings' : '运行时设置'); queryCatalog.setAttribute('aria-label', locale === 'en' ? 'Example queries' : '示例查询'); document.querySelector('.result-view-switch')?.setAttribute('aria-label', locale === 'en' ? 'Result views' : '结果视图'); diff --git a/source/teaql-ts/examples/browser-sqlite/src/style.css b/source/teaql-ts/examples/browser-sqlite/src/style.css index 3d54aecaba2c5b23cc0fa2f7947281db8b961112..0f4ae1db3f1b4406c910cfac06da68b1b4ec326b 100644 --- a/source/teaql-ts/examples/browser-sqlite/src/style.css +++ b/source/teaql-ts/examples/browser-sqlite/src/style.css @@ -115,6 +115,50 @@ h1 { .model-arrow-split { height: 22px; line-height: 18px; } .model-leaves { width: 100%; display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } +.runtime-language-panel { + margin-bottom: 28px; + padding: 24px; + display: grid; + grid-template-columns: minmax(240px, .72fr) minmax(0, 1.8fr); + align-items: center; + gap: 30px; + border: 1px solid var(--line); + border-radius: 18px; + background: var(--paper); +} +.runtime-language-copy .section-index { margin-bottom: 8px; } +.runtime-language-copy h2 { + margin: 0; + font-family: Georgia, "Noto Serif SC", serif; + font-size: clamp(22px, 2.4vw, 31px); + font-weight: 500; + line-height: 1.15; + letter-spacing: -.035em; +} +.runtime-language-copy p:last-child { margin: 11px 0 0; color: var(--muted); font-size: 13px; } +.runtime-language-selector { display: grid; grid-template-columns: repeat(7, minmax(82px, 1fr)); gap: 8px; } +.runtime-language { + min-width: 0; + padding: 13px 8px 11px; + display: flex; + align-items: center; + flex-direction: column; + gap: 4px; + border: 1px solid #d7ddd5; + border-radius: 12px; + color: var(--ink); + background: #fafbf7; + text-align: center; + text-decoration: none; + transition: border-color .16s ease, background .16s ease, transform .16s ease; +} +.runtime-language:hover { border-color: #98aa9d; background: white; transform: translateY(-2px); } +.runtime-language.active { color: white; border-color: var(--green); background: var(--green); box-shadow: 0 8px 20px rgba(20, 91, 55, .14); } +.runtime-language-icon { font-size: 25px; line-height: 1.1; } +.runtime-language strong { overflow: hidden; max-width: 100%; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; } +.runtime-language small { color: #78837a; font-size: 8px; line-height: 1.25; } +.runtime-language.active small { color: #d5e7da; } + .runtime-bar { min-height: 72px; padding: 14px 18px 14px 22px; @@ -409,6 +453,8 @@ footer { .page-shell { padding: 0 24px; } .hero { grid-template-columns: 1fr; gap: 46px; padding-top: 58px; } .model-map { min-height: 260px; } + .runtime-language-panel { grid-template-columns: 1fr; } + .runtime-language-selector { grid-template-columns: repeat(4, minmax(100px, 1fr)); } .result-panel { margin: 0 -24px; padding-left: 24px; padding-right: 24px; } .result-grid { grid-template-columns: 1fr; } } @@ -426,6 +472,9 @@ footer { .model-flow > span:not(.model-arrow), .model-leaves span { width: 100%; } .model-flow .model-arrow { transform: rotate(90deg); } .model-leaves { grid-template-columns: 1fr; } + .runtime-language-panel { padding: 20px 16px; gap: 20px; } + .runtime-language-selector { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .runtime-language:last-child { grid-column: 1 / -1; } .runtime-bar, .section-heading, .result-heading { align-items: flex-start; flex-direction: column; } .runtime-bar { padding: 18px; } .controls { width: 100%; justify-content: space-between; } diff --git a/source/teaql-ts/examples/conformance/.gitignore b/source/teaql-ts/examples/conformance/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..27b98fda57c0687aac384992c3c062c41b378450 --- /dev/null +++ b/source/teaql-ts/examples/conformance/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.local/ diff --git a/source/teaql-ts/examples/conformance/README.md b/source/teaql-ts/examples/conformance/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a007f6c3ab88a3082cec8a4bc5859f7b8e56a111 --- /dev/null +++ b/source/teaql-ts/examples/conformance/README.md @@ -0,0 +1,11 @@ +# TypeScript runtime conformance example + +This retained SQLite example is generated from `model.xml` and verifies the minimum runtime-owned contract: explicit `ensureSchema`, Create, Update, Delete, typed Q, E loaded/null/not-loaded semantics, Checker rejection before SQL, and optimistic-version isolation for different entity types that share a numeric ID. + +```bash +npm install +npm run build +npm start +``` + +The generated workspace targets `@teaql/teaql` 0.1.17. Regenerate it with the local code generator's `typescript-app-console` target before checking a new generator/runtime combination. diff --git a/source/teaql-ts/examples/conformance/evidence/2026-08-26.md b/source/teaql-ts/examples/conformance/evidence/2026-08-26.md new file mode 100644 index 0000000000000000000000000000000000000000..4c0963b073397bcf909c65faae24c92afd19b600 --- /dev/null +++ b/source/teaql-ts/examples/conformance/evidence/2026-08-26.md @@ -0,0 +1,28 @@ +# TypeScript minimum runtime conformance — 2026-08-26 + +- Generator: `bb904a621e982bb86aaf057e36ee9c1cbb9c1c6b` +- Runtime baseline: `a3eeee8f9b24c7016ca4ab2ef88ae4fd7f128d78` plus the projection correction tracked by issue #9 +- Database: SQLite (`better-sqlite3`), fresh local database +- KSML evaluation: 0 errors, 0 warnings, 0 suggestions, 8 solids + +Executed commands: + +```text +npm run build +npm start +``` + +Retained result: + +```text +PASS ensureSchema (explicit SQLite DDL and Platform(1) bootstrap) +PASS Checker (canonical title key, rejected before SQL) +PASS Create (id=1, version=1) +PASS Q API (typed WorkItem) +PASS E API (loaded, null fallback, and not-loaded are distinct) +PASS Update (version 1 -> 2) +PASS Delete (default Q excludes deleted rows) +PASS TypeScript minimum runtime conformance: 7/7 +``` + +The full runtime suite also passed: 21 suites passed, 1 skipped; 73 tests passed, 2 skipped. diff --git a/source/teaql-ts/examples/conformance/model.xml b/source/teaql-ts/examples/conformance/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..85424d414cb3ef55c1b2259b2fee48da7bd573db --- /dev/null +++ b/source/teaql-ts/examples/conformance/model.xml @@ -0,0 +1,16 @@ + + + + diff --git a/source/teaql-ts/examples/conformance/package-lock.json b/source/teaql-ts/examples/conformance/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..cfdb768821331f7cfbd96eec8faa2058b32e7c52 --- /dev/null +++ b/source/teaql-ts/examples/conformance/package-lock.json @@ -0,0 +1,828 @@ +{ + "name": "runtime-example-conformance-service-lib", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "runtime-example-conformance-service-lib", + "version": "1.0.0", + "dependencies": { + "better-sqlite3": "^12.10.0", + "teaql-ts": "file:../.." + }, + "devDependencies": { + "@types/better-sqlite3": "^7.6.12", + "@types/node": "^22.0.0", + "ts-node": "^10.9.2", + "typescript": "^5.0.0" + } + }, + "../..": { + "name": "@teaql/teaql", + "version": "0.3.1", + "license": "Apache-2.0", + "dependencies": { + "node-fetch": "^2.7.0" + }, + "devDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "@types/better-sqlite3": "^7.6.12", + "@types/jest": "^29.5.0", + "@types/node-fetch": "^2.6.13", + "@types/pg": "^8.11.0", + "better-sqlite3": "^12.10.0", + "esbuild": "^0.28.2", + "jest": "^29.5.0", + "jest-util": "^29.7.0", + "mysql2": "^3.11.0", + "peggy": "^5.1.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0", + "ts-jest": "^29.1.0", + "typescript": "5.4.5" + }, + "peerDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "better-sqlite3": "^12.10.0", + "expo-sqlite": "*", + "mysql2": "^3.11.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/s3-request-presigner": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/api-logs": { + "optional": true + }, + "@opentelemetry/context-async-hooks": { + "optional": true + }, + "@opentelemetry/core": { + "optional": true + }, + "@opentelemetry/exporter-logs-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-metrics-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-http": { + "optional": true + }, + "@opentelemetry/otlp-transformer": { + "optional": true + }, + "@opentelemetry/resources": { + "optional": true + }, + "@opentelemetry/sdk-logs": { + "optional": true + }, + "@opentelemetry/sdk-metrics": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "@sqlite.org/sqlite-wasm": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "expo-sqlite": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-query-stream": { + "optional": true + } + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.13.tgz", + "integrity": "sha512-gcLdvR9HO1ZJBypsOGqaP6TFEzb6vIta0KSTLt9NAQ6pXQO3cRgSVyCN6pzYqI9DlJgY71XKO0dpDhCf08b3pg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "22.20.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz", + "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true, + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "12.11.1", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", + "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/node-abi": { + "version": "3.95.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.95.0.tgz", + "integrity": "sha512-T9iGctuocf0qIWFFOTxPzjT5q0SILqaBYXt272tlBHvTKC5+3JnkMirLxNJNkXHtFyBjU2Jx+NL4Zipr0B/c6Q==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/teaql-ts": { + "resolved": "../..", + "link": true + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + } + } +} diff --git a/source/teaql-ts/examples/conformance/package.json b/source/teaql-ts/examples/conformance/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b77d589c5d8684c8d47cd5bb39828ce97352aeed --- /dev/null +++ b/source/teaql-ts/examples/conformance/package.json @@ -0,0 +1,18 @@ +{ + "name": "runtime-example-conformance-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit", + "start": "ts-node src/main.ts" + }, + "dependencies": { + "teaql-ts": "file:../..", + "better-sqlite3": "^12.10.0"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} diff --git a/source/teaql-ts/examples/conformance/src/generated-bootstrap.ts b/source/teaql-ts/examples/conformance/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..c970b56625635970689e62ec725b8d5feb41411f --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Platform } from './generated/models/Platform'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot.updateName("Runtime Example"); + await domainRoot.auditAs('create generated Domain Root Platform').save(context); + } + context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/conformance/src/generated-search-models.ts b/source/teaql-ts/examples/conformance/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..b28e81724cbe93032b3118bb0db4f2dbe2f60f71 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated-search-models.ts @@ -0,0 +1,39 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Platform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "version": "version", + }), + relations: Object.freeze({ + "workItemList": "WorkItem", + }), + }), + "WorkItem": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "title": "string" as const, + "description": "string" as const, + "platform": "integer" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "title": "title", + "description": "description", + "platform": "platform", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/generated/E.ts b/source/teaql-ts/examples/conformance/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ccc5635ccd4119ac905d45e55cbd74d8673c17f --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated/E.ts @@ -0,0 +1,315 @@ +import { Platform } from './models/Platform'; +import { WorkItem } from './models/WorkItem'; + +export class TeaQLNotLoadedError extends Error { + readonly details: Record; + + constructor( + readonly root: string, + readonly accessPath: string, + readonly breakPoint: string, + ) { + const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; + const details = { + error: 'TeaQLNotLoadedError', + root, + accessPath: accessPath.split('.'), + breakPoint, + missingPreload: [breakPoint], + suggestedFix, + severity: 'error', + humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, + }; + super(JSON.stringify(details)); + this.name = 'TeaQLNotLoadedError'; + this.details = details; + } +} + +function expressionPath(prefix: string, field: string): string { + return prefix ? `${prefix}.${field}` : field; +} + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded; + return this.present; + } + + orElse(fallback: T): T { + const value = this.eval(); + return this.present && value != null ? value : fallback; + } +} + +export class PlatformExpression { + constructor( + private readonly value: Platform | null | undefined, + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Platform | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + workItemList(): WorkItemListExpression { + const path = expressionPath(this.path, 'workItemList'); + if (this.notLoaded) { + return new WorkItemListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return WorkItemListExpression.missing(this.root, path); + if (!this.value.isLoaded('workItemList')) { + return new WorkItemListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'workItemList')); + } + return new WorkItemListExpression( + this.value.workItemList(), this.root, path, + ); + } +} + +export class WorkItemExpression { + constructor( + private readonly value: WorkItem | null | undefined, + private readonly root = 'WorkItem(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): WorkItem | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + title(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'title'); + if (!this.value.isLoaded('title')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'title'), + ); + } + return new ValueExpression(this.value.title); + } + + description(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'description'); + if (!this.value.isLoaded('description')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'description'), + ); + } + return new ValueExpression(this.value.description); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'platform'); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = expressionPath(this.path, 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'platform')); + } + const relation = this.value.platform; + const target = relation == null + ? undefined + : relation instanceof Platform + ? relation + : Platform.fromRecord({ id: relation }); + return new PlatformExpression(target, this.root, path); + } + +} + +export class PlatformListExpression { + constructor( + private readonly items: readonly Platform[], + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): PlatformListExpression { + return new PlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): PlatformExpression { + return this.get(0); + } + + get(index: number): PlatformExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new PlatformExpression(undefined, this.root, itemPath) + : new PlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class WorkItemListExpression { + constructor( + private readonly items: readonly WorkItem[], + private readonly root = 'WorkItem(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): WorkItemListExpression { + return new WorkItemListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): WorkItemExpression { + return this.get(0); + } + + get(index: number): WorkItemExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new WorkItemExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new WorkItemExpression(undefined, this.root, itemPath) + : new WorkItemExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static platform( + value: Platform | null | undefined, + ): PlatformExpression { + return new PlatformExpression( + value, `Platform(id=${value?.id ?? 'null'})`, + ); + } + + static workItem( + value: WorkItem | null | undefined, + ): WorkItemExpression { + return new WorkItemExpression( + value, `WorkItem(id=${value?.id ?? 'null'})`, + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/generated/Q.ts b/source/teaql-ts/examples/conformance/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..446c78ca5a5ed91821d7fc04d6059482848ff0c1 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../teaql-ts'; +import { PlatformRequest } from './requests/PlatformRequest'; +import { WorkItemRequest } from './requests/WorkItemRequest'; + +export class Q { + static platforms(): PlatformRequest { + return new PlatformRequest(false); + } + + static platformsWithMinimalFields(): PlatformRequest { + return new PlatformRequest(true); + } + static workItems(): WorkItemRequest { + return new WorkItemRequest(false); + } + + static workItemsWithMinimalFields(): WorkItemRequest { + return new WorkItemRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/generated/models/Platform.ts b/source/teaql-ts/examples/conformance/src/generated/models/Platform.ts new file mode 100644 index 0000000000000000000000000000000000000000..a464f45ae27c6f1adfd653ca46350285ee11271b --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated/models/Platform.ts @@ -0,0 +1,262 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { WorkItem } from './WorkItem'; + +export class Platform { + private static teaqlTemporaryId = 0; + id?: string; + name?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_workItemList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["workItemList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).workItemList)) { + const selected = (init as any).workItemList; + (this as any)._workItemList = new SmartList(selected.map( + (child: unknown) => child instanceof WorkItem + ? child + : WorkItem.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("workItemList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._workItemList) child.teaqlAttachRoot(root); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Platform { + const entity = new Platform(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Platform { + return new Platform({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Platform { + return new Platform().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Platform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._workItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("work_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Platform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._workItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("work_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._workItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("work_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + workItemList(): SmartList { + return (this as any)._workItemList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/generated/models/WorkItem.ts b/source/teaql-ts/examples/conformance/src/generated/models/WorkItem.ts new file mode 100644 index 0000000000000000000000000000000000000000..3008446a91296326a7fa9835fa8f0cd4b77041b8 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated/models/WorkItem.ts @@ -0,0 +1,228 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; + +export class WorkItem { + private static teaqlTemporaryId = 0; + id?: string; + title?: string; + description?: string; + platform?: Platform | string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --WorkItem.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "WorkItem", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): WorkItem { + const entity = new WorkItem(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): WorkItem { + return new WorkItem({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): WorkItem { + return new WorkItem().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "title", canonical: "title" }, { member: "description", canonical: "description" }, { member: "platform", canonical: "platform" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "WorkItem", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "WorkItem", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "title": this.title, + "description": this.description, + "platform": this.platform, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateTitle(value: string): this { + this.title = value; + this.markLoaded("title"); + (this as any)._root.set(this.teaqlEntityKey(), "title", value); + return this; + } + + updateDescription(value: string): this { + this.description = value; + this.markLoaded("description"); + (this as any)._root.set(this.teaqlEntityKey(), "description", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/conformance/src/generated/requests/PlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..13411fde2029f019a860ebf78f102aefeb026187 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated/requests/PlatformRequest.ts @@ -0,0 +1,607 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Platform } from '../models/Platform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class PlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Platform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutablePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutablePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectWorkItemListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "workItemList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectWorkItemListWith", relation: "workItemList" }); + return this; + } + + haveWorkItems(): this { + return this.withWorkItemListMatching({ + toQuery: () => new SelectQuery("WorkItem"), + }); + } + + haveNoWorkItems(): this { + return this.withoutWorkItemListMatching({ + toQuery: () => new SelectQuery("WorkItem"), + }); + } + + withWorkItemListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutWorkItemListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + countWorkItems(): this { + return this.countWorkItemsAs("countWorkItems"); + } + + countWorkItemsAs(alias: string): this { + const query = new SelectQuery("WorkItem").filter({ version: { "$gte": 1 } }); + this.countWorkItemsWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countWorkItemsAs", relation: "workItemList", alias }; + return this; + } + + countWorkItemsWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("workItemList", alias, query, true, + { kind: "relation-count", method: "countWorkItemsWith", relation: "workItemList", alias }); + return this; + } + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Platform + ? entity + : Platform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutablePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Platform { + this.ensureIntent(); + return new Platform(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/generated/requests/WorkItemRequest.ts b/source/teaql-ts/examples/conformance/src/generated/requests/WorkItemRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..134b124febb994f01d43aac5cc4432c7dabf4007 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/generated/requests/WorkItemRequest.ts @@ -0,0 +1,724 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { WorkItem } from '../models/WorkItem'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class WorkItemRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("WorkItem"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableWorkItemRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableWorkItemRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "title", "description", "platform", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectTitle(): this { + this.query.select(["title"]); + return this; + } + + selectDescription(): this { + this.query.select(["description"]); + return this; + } + + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + + withPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withTitleContaining(val: string): this { + this.filters.push({ "title": { "$contains": val } }); + return this; + } + + withTitleIs(val: string): this { + this.filters.push({ "title": { "$eq": val } }); + return this; + } + + withTitleIsNot(val: any): this { + this.filters.push({ "title": { "$ne": val } }); + return this; + } + + withTitleIn(...vals: any[]): this { + this.filters.push({ "title": { "$in": vals } }); + return this; + } + + withTitleNotIn(...vals: any[]): this { + this.filters.push({ "title": { "$notIn": vals } }); + return this; + } + + withTitleGreaterThan(val: any): this { + this.filters.push({ "title": { "$gt": val } }); + return this; + } + + withTitleGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "title": { "$gte": val } }); + return this; + } + + withTitleLessThan(val: any): this { + this.filters.push({ "title": { "$lt": val } }); + return this; + } + + withTitleLessThanOrEqualTo(val: any): this { + this.filters.push({ "title": { "$lte": val } }); + return this; + } + + withTitleBetween(lower: any, upper: any): this { + this.filters.push({ "title": { "$between": [lower, upper] } }); + return this; + } + + withTitleIsKnown(): this { + this.filters.push({ "title": { "$isNull": false } }); + return this; + } + + withTitleIsUnknown(): this { + this.filters.push({ "title": { "$isNull": true } }); + return this; + } + withTitleNotContaining(val: string): this { + this.filters.push({ "title": { "$notContains": val } }); + return this; + } + + withTitleStartingWith(val: string): this { + this.filters.push({ "title": { "$startsWith": val } }); + return this; + } + + withTitleNotStartingWith(val: string): this { + this.filters.push({ "title": { "$notStartsWith": val } }); + return this; + } + + withTitleEndingWith(val: string): this { + this.filters.push({ "title": { "$endsWith": val } }); + return this; + } + + withTitleNotEndingWith(val: string): this { + this.filters.push({ "title": { "$notEndsWith": val } }); + return this; + } + + withTitleSoundingLike(val: string): this { + this.filters.push({ "title": { "$soundLike": val } }); + return this; + } + + withDescriptionContaining(val: string): this { + this.filters.push({ "description": { "$contains": val } }); + return this; + } + + withDescriptionIs(val: string): this { + this.filters.push({ "description": { "$eq": val } }); + return this; + } + + withDescriptionIsNot(val: any): this { + this.filters.push({ "description": { "$ne": val } }); + return this; + } + + withDescriptionIn(...vals: any[]): this { + this.filters.push({ "description": { "$in": vals } }); + return this; + } + + withDescriptionNotIn(...vals: any[]): this { + this.filters.push({ "description": { "$notIn": vals } }); + return this; + } + + withDescriptionGreaterThan(val: any): this { + this.filters.push({ "description": { "$gt": val } }); + return this; + } + + withDescriptionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "description": { "$gte": val } }); + return this; + } + + withDescriptionLessThan(val: any): this { + this.filters.push({ "description": { "$lt": val } }); + return this; + } + + withDescriptionLessThanOrEqualTo(val: any): this { + this.filters.push({ "description": { "$lte": val } }); + return this; + } + + withDescriptionBetween(lower: any, upper: any): this { + this.filters.push({ "description": { "$between": [lower, upper] } }); + return this; + } + + withDescriptionIsKnown(): this { + this.filters.push({ "description": { "$isNull": false } }); + return this; + } + + withDescriptionIsUnknown(): this { + this.filters.push({ "description": { "$isNull": true } }); + return this; + } + withDescriptionNotContaining(val: string): this { + this.filters.push({ "description": { "$notContains": val } }); + return this; + } + + withDescriptionStartingWith(val: string): this { + this.filters.push({ "description": { "$startsWith": val } }); + return this; + } + + withDescriptionNotStartingWith(val: string): this { + this.filters.push({ "description": { "$notStartsWith": val } }); + return this; + } + + withDescriptionEndingWith(val: string): this { + this.filters.push({ "description": { "$endsWith": val } }); + return this; + } + + withDescriptionNotEndingWith(val: string): this { + this.filters.push({ "description": { "$notEndsWith": val } }); + return this; + } + + withDescriptionSoundingLike(val: string): this { + this.filters.push({ "description": { "$soundLike": val } }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByTitleAscending(): this { + this.query.orderBy("title", "asc"); + return this; + } + + orderByTitleDescending(): this { + this.query.orderBy("title", "desc"); + return this; + } + + orderByDescriptionAscending(): this { + this.query.orderBy("description", "asc"); + return this; + } + + orderByDescriptionDescending(): this { + this.query.orderBy("description", "desc"); + return this; + } + + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByTitle(): this { + this.query.groupBy("title"); + return this; + } + + groupByTitleAs(retName: string): this { + this.query.groupBy("title"); // In TS we don't alias group by yet natively + return this; + } + groupByDescription(): this { + this.query.groupBy("description"); + return this; + } + + groupByDescriptionAs(retName: string): this { + this.query.groupBy("description"); // In TS we don't alias group by yet natively + return this; + } + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } + + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByPlatformAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof WorkItem + ? row + : WorkItem.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof WorkItem + ? row + : WorkItem.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof WorkItem + ? entity + : WorkItem.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableWorkItemRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): WorkItem { + this.ensureIntent(); + return new WorkItem(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/main.ts b/source/teaql-ts/examples/conformance/src/main.ts new file mode 100644 index 0000000000000000000000000000000000000000..06bb0f2d09280f7e405de863e0f7ba890e87230f --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/main.ts @@ -0,0 +1,88 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { CheckException, EntityRoot, UserContext } from "./teaql-ts"; +import { E, TeaQLNotLoadedError } from "./generated/E"; +import { Q } from "./generated/Q"; +import { WorkItem } from "./generated/models/WorkItem"; +import { SQLiteTeaQLClient } from "./teaql-node-sqlite"; +import { verifyMaskingLifecycle } from './masking-verification'; + +async function main(): Promise { + const orderKey = { entity: "Order", id: 1 } as const; + const executionKey = { entity: "InferenceExecution", id: 1 } as const; + const target = new EntityRoot(); + const source = new EntityRoot(); + target.setOriginalVersion(orderKey, 3); + source.setOriginalVersion(executionKey, 9); + source.set(executionKey, "execution_status", "COMPLETED"); + target.mergeFrom(source); + assert.equal(target.originalVersion(orderKey), 3); + assert.equal(target.originalVersion(executionKey), 9); + console.log("PASS Mutation ledger identity (same ID, different entity types keep versions 3/9)"); + + const database = path.resolve(__dirname, "../.local/conformance.sqlite"); + fs.mkdirSync(path.dirname(database), { recursive: true }); + fs.rmSync(database, { force: true }); + const client = new SQLiteTeaQLClient(database); + const context = new UserContext().insertResource("dataService", client); + client.setUserContext(context); + + await context.ensureSchema(); + console.log("PASS ensureSchema (explicit SQLite DDL and Platform(1) bootstrap)"); + + const sqlBeforeInvalidSave = client.sqlTrace.length; + const invalid = new WorkItem().updatePlatform("1"); + await assert.rejects(invalid.auditAs("Checker must reject a missing title").save(context), (error: unknown) => { + assert(error instanceof CheckException); + assert(error.violations.some(item => item.ruleId === "required" && String(item.location).includes("title"))); + return true; + }); + assert.equal(client.sqlTrace.length, sqlBeforeInvalidSave, "Checker must run before mutation SQL"); + console.log("PASS Checker (canonical title key, rejected before SQL)"); + + const created = await new WorkItem() + .updateTitle("Verify TypeScript runtime") + .updatePlatform("1") + .auditAs("Create conformance work item").save(context); + assert(created.id); + assert.equal(created.version, 1); + console.log(`PASS Create (id=${created.id}, version=${created.version})`); + + const queried = await Q.workItems().withIdIs(created.id) + .selectPlatformWith(Q.platforms().selectName()) + .comment("Load the complete work item before mutation") + .purpose("Verify typed Q API and update semantics").executeForOne(context); + assert(queried); + assert.equal(queried.title, "Verify TypeScript runtime"); + assert.equal(E.workItem(queried).platform().name().eval(), "Runtime Example"); + console.log("PASS Q API (typed WorkItem)"); + + assert.equal(E.workItem(queried).title().eval(), "Verify TypeScript runtime"); + assert.equal(E.workItem(queried).description().orElse("N/A"), "N/A"); + const minimal = await Q.workItemsWithMinimalFields().withIdIs(created.id) + .comment("Load only mandatory identity fields") + .purpose("Verify E not-loaded semantics").executeForOne(context); + assert(minimal); + assert.throws(() => E.workItem(minimal).title().eval(), TeaQLNotLoadedError); + console.log("PASS E API (loaded, null fallback, and not-loaded are distinct)"); + + const previousVersion = queried.version!; + await queried.updateTitle("Verified TypeScript runtime") + .auditAs("Update conformance work item").save(context); + assert.equal(queried.version, previousVersion + 1); + console.log(`PASS Update (version ${previousVersion} -> ${queried.version})`); + + await queried.markForDeletion().auditAs("Delete conformance work item").save(context); + const remaining = await Q.workItems().withIdIs(created.id) + .comment("Verify soft-deleted work item is excluded") + .purpose("Verify delete semantics").executeForList(context); + assert.equal(remaining.length, 0); + console.log("PASS Delete (default Q excludes deleted rows)"); + + await client.close(); + console.log("PASS TypeScript minimum runtime conformance: 8/8"); + await verifyMaskingLifecycle(); +} + +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/conformance/src/masking-verification.ts b/source/teaql-ts/examples/conformance/src/masking-verification.ts new file mode 100644 index 0000000000000000000000000000000000000000..2473dc88e32dd186f9626c1be213219a78a93dfd --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/masking-verification.ts @@ -0,0 +1,122 @@ +// Runtime-owned fixture: no generated library source or descriptor is patched. +import assert from 'node:assert/strict'; +import { appendFileSync, mkdtempSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { GraphMutationSession, MutationIntent, SelectQuery, UserContext } from 'teaql-ts'; +import { SQLiteDriver } from 'teaql-ts/sql/sqlite'; +import { AbstractSQLTeaQLClient, EntitySchema, SQLExecutionMetadata, TextDiagnosticSQLLogSink } from 'teaql-ts/sql/core'; + +export async function verifyMaskingLifecycle(): Promise { + const schemas: Record = { MaskingProbe: { + table: 'masking_probe', auditMaskFields: ['display_name'], columns: { + id: { columnName: 'id', logicalType: 'integer', decode: 'string', logPolicy: 'plain' }, + version: { columnName: 'version', logicalType: 'integer', decode: 'number', logPolicy: 'plain' }, + name: { columnName: 'display_name', logicalType: 'text', decode: 'native', logPolicy: 'plain' }, + address: { columnName: 'address', logicalType: 'text', decode: 'native', logPolicy: 'plain' }, + password: { columnName: 'password', logicalType: 'text', decode: 'native', logPolicy: 'plain' }, + }, + relations: { children: { targetEntity: 'MaskingChild', localKey: 'id', foreignKey: 'parentId', many: true } }, + }, MaskingChild: { table: 'masking_child', columns: { + id: { columnName: 'id', logicalType: 'integer', decode: 'string', logPolicy: 'plain' }, + version: { columnName: 'version', logicalType: 'integer', decode: 'number', logPolicy: 'plain' }, + parentId: { columnName: 'parent_id', logicalType: 'integer', decode: 'string', logPolicy: 'plain' }, + } } }; + const entries: SQLExecutionMetadata[] = [], output: string[] = []; + const driver = new SQLiteDriver(':memory:'); + class ProbeClient extends AbstractSQLTeaQLClient { + constructor() { super(driver, schemas); } + } + const client = new ProbeClient().setDiagnosticSQLLogSink({ write(entry) { + entries.push(entry); new TextDiagnosticSQLLogSink(line => output.push(line)).write(entry); + } }); + const payload = { name: 'Riverside', address: '1 Runtime Road', password: 'PASSWORD-CANARY' }; + try { + await new UserContext().insertResource('dataService', client).ensureSchema(); + for (const id of ['1', '2']) await client.executeMutation({ entity: 'MaskingProbe', + action: 'Create', id, payload, comment: 'seed mask lifecycle fixture' }); + entries.length = 0; output.length = 0; + const query = () => new SelectQuery('MaskingProbe').filter({ name: { $eq: 'Riverside' }, + address: { $eq: '1 Runtime Road' }, password: { $eq: 'PASSWORD-CANARY' } }) + .limit(10).comment('what: bounded private-name lookup').purpose('why: verify mask lifecycle'); + for await (const rows of client.executeForStream(query(), 1)) { + assert.equal(rows[0].name, 'Riverside'); break; + } + assert.equal(entries[0].executionOutcome, 'cancelled'); + assert.equal(entries[0].resultCount, 1); + // Real SQLite UNIQUE failure must still leave safe, useful SQL evidence. + await assert.rejects(client.executeMutation({ entity: 'MaskingProbe', action: 'Create', id: '1', + payload, comment: 'verify duplicate ID failure' }), /UNIQUE/); + assert.equal(entries[1].executionOutcome, 'failure'); + assert.equal(entries[1].affectedRows, undefined); + const rows = await client.executeQuery(query()); + assert.equal(rows.length, 2); + assert.equal(rows[0].name, 'Riverside'); + const text = output.join('\n'); + assert(text.includes('Ri*****de') && text.includes('1 Runtime Road')); + assert(!text.includes('Riverside') && !text.includes('PASSWORD-CANARY')); + assert(text.includes('outcome=cancelled') && text.includes('outcome=failure')); + + await driver.query('CREATE TRIGGER remove_mask_probe AFTER INSERT ON masking_probe WHEN NEW.id = 777 BEGIN DELETE FROM masking_probe WHERE id = NEW.id; END'); + entries.length = 0; output.length = 0; + const create = (id:string, graph?: GraphMutationSession) => { + const mutation = {entity:'MaskingProbe',action:'Create',id, + payload,comment:'what: insert Riverside PASSWORD-CANARY for readback'}; + return client.executeMutation(graph ? graph.request(mutation) : mutation); + }; + await assert.rejects(create('777'),/could not be read back/); + assert.equal(entries.length,2); + assert.equal(entries[0].executionOutcome,'success'); + assert.equal(entries[0].affectedRows,1); + assert.equal(entries[1].executionOutcome,'success'); + assert.equal(entries[1].resultCount,0); + assert(entries[1].auditReason?.includes('what: insert')); + assert(!JSON.stringify([entries,output]).match(/Riverside|PASSWORD-CANARY/)); + + entries.length = 0; output.length = 0; + await assert.rejects(client.executeGraphSave(new MutationIntent('what: insert Riverside PASSWORD-CANARY for readback'), async graph => { + await create('30', graph); + await create('777', graph); + await create('31', graph); + }),/could not be read back/); + assert.deepEqual(entries.map(entry=>[entry.operation,entry.executionOutcome]),[ + ['insert','success'],['select','success'],['insert','success'],['select','success'], + ]); + assert.equal(entries[1].resultCount,1); + assert.equal(entries[3].resultCount,0); + assert(!JSON.stringify([entries,output]).match(/Riverside|PASSWORD-CANARY/)); + assert.equal((await driver.query('SELECT * FROM masking_probe WHERE id IN (30,31,777)')).rowCount,0); + assert.equal((await driver.query('SELECT * FROM masking_probe')).rowCount,2); + await create('32'); + assert.equal((await driver.query('SELECT * FROM masking_probe')).rowCount,3); + console.log('PASS masking lifecycle: stream, SQLite failure, readback intent, partial graph rollback and session reuse'); + + await client.executeMutation({ entity: 'MaskingChild', action: 'Create', id: '1', + payload: { parentId: '1' }, comment: 'seed derived relation log fixture' }); + const relationLog = join(mkdtempSync(join(tmpdir(), 'teaql-ts-relation-log-')), 'sql.log'); + entries.length = 0; + client.setDiagnosticSQLLogSink({ write(entry) { + entries.push(entry); + new TextDiagnosticSQLLogSink(line => appendFileSync(relationLog, line + '\n')).write(entry); + } }); + const related = () => new SelectQuery('MaskingProbe') + .filter({ id: { $eq: '1' }, name: { $eq: 'Riverside' }, password: { $eq: 'PASSWORD-CANARY' } }) + .relationQuery('children', new SelectQuery('MaskingChild').limit(2)).limit(1) + .comment('what: load Riverside PASSWORD-CANARY children').purpose('why: verify inherited relation intent'); + await driver.query('ALTER TABLE masking_child RENAME TO masking_child_fault_probe'); + try { await assert.rejects(client.executeQuery(related()), /no such table/); } + finally { await driver.query('ALTER TABLE masking_child_fault_probe RENAME TO masking_child'); } + assert.equal(entries.length, 2); + assert.equal(entries[0].executionOutcome, 'success'); + assert.equal(entries[1].executionOutcome, 'failure'); + assert(entries[1].comment?.includes('what: load')); + const logText = readFileSync(relationLog, 'utf8'); + assert(logText.includes('masking_child') && logText.includes('outcome=failure')); + assert(!JSON.stringify([entries, logText]).match(/Riverside|PASSWORD-CANARY/)); + const restored = await client.executeQuery(related()); + assert.equal(restored.length, 1); + assert.equal(restored[0].children.length, 1); + assert.equal(restored[0].children[0].id, '1'); + console.log('PASS masking relation: real SQLite failure, file/custom sinks and restored graph'); + } finally { await client.close(); } +} diff --git a/source/teaql-ts/examples/conformance/src/runtime-module.ts b/source/teaql-ts/examples/conformance/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..086251a3faf86275edfe441ff7ab737a6c7fd46e --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/runtime-module.ts @@ -0,0 +1,60 @@ +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-schemas"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Platform": Object.freeze({ + entityType: "Platform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "WorkItem": Object.freeze({ + entityType: "WorkItem", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "title": Object.freeze({ canonicalName: "title", wireName: "title", aliases: Object.freeze([] as string[]) }), + "description": Object.freeze({ canonicalName: "description", wireName: "description", aliases: Object.freeze([] as string[]) }), + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Platform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + + }, + }, + "WorkItem": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["title"] === undefined) || mutation.payload["title"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("title") }); + if (mutation.payload["title"] != null && !([...String(mutation.payload["title"])].length >= 1)) results.push({ ruleId: "min_length", location: ObjectLocation.property("title"), inputValue: mutation.payload["title"], systemValue: 1 }); + if (mutation.payload["title"] != null && [...String(mutation.payload["title"])].length > 80) results.push({ ruleId: "max_length", location: ObjectLocation.property("title"), inputValue: mutation.payload["title"], systemValue: 80 }); + + if (mutation.payload["description"] != null && [...String(mutation.payload["description"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("description"), inputValue: mutation.payload["description"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Runtime Example" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/teaql-node-sql.ts b/source/teaql-ts/examples/conformance/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb7bafb926673892b2f565587d06e1887553f6d2 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/teaql-node-sql.ts @@ -0,0 +1,14 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + columns: {"id": { columnName: "id", modelName: "id", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"workItemList": { targetEntity: "WorkItem", localKey: "id", foreignKey: "platform", many: true }} +}, +"WorkItem": { + table: "work_item_data", + columns: {"id": { columnName: "id", modelName: "id", logicalType: "integer", decode: "string", nullable: false }, "title": { columnName: "title", modelName: "title", logicalType: "text", decode: "native", nullable: false }, "description": { columnName: "description", modelName: "description", logicalType: "text", decode: "native", nullable: true }, "platform": { columnName: "platform", modelName: "platform", logicalType: "integer", decode: "string", nullable: false }, "version": { columnName: "version", modelName: "version", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/conformance/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/teaql-schemas.ts b/source/teaql-ts/examples/conformance/src/teaql-schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f81f553c042276c80ea81434cde9a134b714857 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/teaql-schemas.ts @@ -0,0 +1,16 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"workItemList": { targetEntity: "WorkItem", localKey: "id", foreignKey: "platform", many: true }} +}, +"WorkItem": { + table: "work_item_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "title": { columnName: "title", modelName: "title", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "description": { columnName: "description", modelName: "description", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/teaql-ts.ts b/source/teaql-ts/examples/conformance/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..b54a29ac3c12fb072cf4c292e22bb2e644b56319 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/teaql-ts.ts @@ -0,0 +1,308 @@ +import { + CheckException, EntityChecker, RuntimeModule, + SelectQuery as RuntimeSelectQuery, UserContext, + executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + + constructor(private storagePath?: string) { + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + Object.assign(this.checkers, module.checkers); + return this; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + const graph = new GraphMutationSession(intent); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + try { + this.graphSaveActive = true; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.userContext.insertResource("fixTime", new Date()); + this.userContext.beginFixEvidence(); + fixEvidenceStarted = true; + this.userContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + const result = await work(graph); + this.userContext.ensureMutationPolicyGraphComplete(); + this.persist(); + for (const action of this.graphCommitActions) action(); + return result; + } catch (error) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) action(); + throw error; + } finally { + this.graphSaveActive = false; + this.graphCommitActions = []; + this.graphRollbackActions = []; + if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); + this.userContext.removeResource("fixTime"); + if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + mutation = this.checkAndFixMutation(mutation); + this.userContext.recordMutationPolicyPreflight(mutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + if (mutation instanceof MutationRequest) mutation = mutation.mutation; + if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + const checker = this.checkers[String(mutation.entity)]; + if (!checker) return mutation; + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + this.userContext.translateCheckResults(results); + if (results.length) throw new CheckException(results); + return mutation; + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + mutation = this.checkAndFixMutation(mutation); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + this.mutationGovernanceEvents.push(mutationGovernance); + const table = this.data[mutation.entity] ||= {}; + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + this.nextIds[mutation.entity] = Number(id) + 1; + const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; + } + if (mutation.action === "Update") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + } + if (mutation.action === "Delete") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); + if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); + const relatedRows = (await this.executeQuery(relation.query)).filter( + (row: any) => localValues.has(row[relation.foreignKey || "id"])); + for (const row of rows) { + const matches = relatedRows.filter( + (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/teaql-i18n.json b/source/teaql-ts/examples/conformance/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..83183cccdf5a259000b07930757d63204f5c9ee0 --- /dev/null +++ b/source/teaql-ts/examples/conformance/teaql-i18n.json @@ -0,0 +1,106 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.platform.name": "Name", + "property.workItem.title": "Title", + "entity.platform": "Platform", + "property.platform.id": "Id", + "entity.workItem": "Work Item", + "property.workItem.platform": "Platform", + "property.platform.version": "Version", + "property.workItem.description": "Description", + "property.workItem.id": "Id", + "property.workItem.version": "Version" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/tsconfig.json b/source/teaql-ts/examples/conformance/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/conformance/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/.gitignore b/source/teaql-ts/examples/ensure-schema-bootstrap/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..27b98fda57c0687aac384992c3c062c41b378450 --- /dev/null +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.local/ diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/README.md b/source/teaql-ts/examples/ensure-schema-bootstrap/README.md new file mode 100644 index 0000000000000000000000000000000000000000..561b20c9e1c2316296ab320bd4295a5295bff4b6 --- /dev/null +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/README.md @@ -0,0 +1,24 @@ +# Ensure Schema Bootstrap + +This is the smallest executable TypeScript example of TeaQL's explicit schema +and system-bootstrap contract. + +It proves that: + +- installing a `RuntimeModule` is passive; +- explicit `ensureSchema()` creates the Default Domain Root `Platform(1)`; +- the same call creates or reconciles generated constants; +- a second call is idempotent; +- an additional Platform is allocated without a hard-coded ID and becomes an + Isolated Domain Root for another Data Graph. + +The bootstrap manifest in `app.ts` stands in for generated metadata. Ordinary +sample business data does not belong in this manifest. + +```bash +npm install +npm start +npm start # demonstrates restart idempotency +``` + +The SQLite database is written to `.local/bootstrap.sqlite`. diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/app.ts b/source/teaql-ts/examples/ensure-schema-bootstrap/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..7891deca47d09527e5ea8df7e29004dabf30eb79 --- /dev/null +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/app.ts @@ -0,0 +1,74 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { RuntimeModule, SelectQuery, UserContext } from 'teaql-ts'; +import type { EntitySchema } from 'teaql-ts/sql/core'; +import { SQLiteTeaQLClient } from 'teaql-ts/sql/sqlite'; + +const schemas: Record = { + Platform: { + table: 'platform_data', + columns: { + id: { columnName: 'id', logicalType: 'integer', decode: 'string' }, + version: { columnName: 'version', logicalType: 'integer', decode: 'number' }, + name: { columnName: 'name', logicalType: 'text', decode: 'native' }, + }, + }, + OrderStatus: { + table: 'order_status_data', + columns: { + id: { columnName: 'id', logicalType: 'integer', decode: 'string' }, + version: { columnName: 'version', logicalType: 'integer', decode: 'number' }, + name: { columnName: 'name', logicalType: 'text', decode: 'native' }, + }, + }, +}; + +const generatedModule = new RuntimeModule(schemas, {}, { + defaultDomainRoot: { + entity: 'Platform', id: '1', values: { name: 'Default Platform' }, + }, + constants: [ + { entity: 'OrderStatus', id: '1001', values: { name: 'Pending' } }, + ], +}); + +function read(entity: string): SelectQuery { + return new SelectQuery(entity) + .comment('what: read Ensure Schema bootstrap records') + .purpose('why: demonstrate the TypeScript runtime contract'); +} + +async function main(): Promise { + const directory = path.join(__dirname, '.local'); + fs.mkdirSync(directory, { recursive: true }); + const client = new SQLiteTeaQLClient(path.join(directory, 'bootstrap.sqlite'), {}); + + client.install(generatedModule); // passive: metadata only + const context = new UserContext().insertResource('dataService', client); + await context.ensureSchema(); // explicit: DDL plus system bootstrap + + const platforms = await client.executeQuery(read('Platform')); + const defaultRoot = platforms.find(platform => String(platform.id) === '1'); + if (!defaultRoot) throw new Error('Default Domain Root Platform(1) is missing'); + console.log(`[default-root] Platform(${defaultRoot.id}) ${defaultRoot.name}`); + + let isolatedRoot = platforms.find(platform => platform.name === 'Isolated Platform'); + if (!isolatedRoot) { + const saved = await client.executeMutation({ + entity: 'Platform', action: 'Create', payload: { name: 'Isolated Platform' }, + comment: 'create an isolated data graph without assigning an ID', + }); + isolatedRoot = saved.persistedRecord; + } + if (String(isolatedRoot?.id) === '1') throw new Error('Isolated root reused reserved ID 1'); + console.log(`[isolated-root] Platform(${isolatedRoot?.id}) ${isolatedRoot?.name}`); + + const constants = await client.executeQuery(read('OrderStatus')); + console.log(`[constant] OrderStatus(${constants[0].id}) ${constants[0].name}`); + await client.close(); +} + +main().catch(error => { + console.error(error); + process.exitCode = 1; +}); diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/package-lock.json b/source/teaql-ts/examples/ensure-schema-bootstrap/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..a3a4fcf1aef4c648886a81026edfa0484ef49d66 --- /dev/null +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/package-lock.json @@ -0,0 +1,795 @@ +{ + "name": "teaql-ensure-schema-bootstrap-example", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "teaql-ensure-schema-bootstrap-example", + "dependencies": { + "better-sqlite3": "^12.10.0", + "teaql-ts": "file:../..", + "ts-node": "^10.9.2", + "typescript": "5.4.5" + }, + "devDependencies": { + "@types/node": "^22.0.0" + } + }, + "../..": { + "name": "@teaql/teaql", + "version": "0.3.1", + "license": "Apache-2.0", + "dependencies": { + "node-fetch": "^2.7.0" + }, + "devDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "@types/better-sqlite3": "^7.6.12", + "@types/jest": "^29.5.0", + "@types/node-fetch": "^2.6.13", + "@types/pg": "^8.11.0", + "better-sqlite3": "^12.10.0", + "esbuild": "^0.28.2", + "jest": "^29.5.0", + "jest-util": "^29.7.0", + "mysql2": "^3.11.0", + "peggy": "^5.1.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0", + "ts-jest": "^29.1.0", + "typescript": "5.4.5" + }, + "peerDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "better-sqlite3": "^12.10.0", + "expo-sqlite": "*", + "mysql2": "^3.11.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/s3-request-presigner": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/api-logs": { + "optional": true + }, + "@opentelemetry/context-async-hooks": { + "optional": true + }, + "@opentelemetry/core": { + "optional": true + }, + "@opentelemetry/exporter-logs-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-metrics-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-http": { + "optional": true + }, + "@opentelemetry/otlp-transformer": { + "optional": true + }, + "@opentelemetry/resources": { + "optional": true + }, + "@opentelemetry/sdk-logs": { + "optional": true + }, + "@opentelemetry/sdk-metrics": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "@sqlite.org/sqlite-wasm": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "expo-sqlite": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-query-stream": { + "optional": true + } + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.13.tgz", + "integrity": "sha512-gcLdvR9HO1ZJBypsOGqaP6TFEzb6vIta0KSTLt9NAQ6pXQO3cRgSVyCN6pzYqI9DlJgY71XKO0dpDhCf08b3pg==", + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz", + "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "12.11.1", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", + "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "license": "MIT" + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "license": "ISC" + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/node-abi": { + "version": "3.95.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.95.0.tgz", + "integrity": "sha512-T9iGctuocf0qIWFFOTxPzjT5q0SILqaBYXt272tlBHvTKC5+3JnkMirLxNJNkXHtFyBjU2Jx+NL4Zipr0B/c6Q==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/teaql-ts": { + "resolved": "../..", + "link": true + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + } + } +} diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/package.json b/source/teaql-ts/examples/ensure-schema-bootstrap/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f3003d870b320a8577ab6f9113814efdd8b683a7 --- /dev/null +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/package.json @@ -0,0 +1,17 @@ +{ + "name": "teaql-ensure-schema-bootstrap-example", + "private": true, + "scripts": { + "build": "tsc --noEmit", + "start": "ts-node app.ts" + }, + "dependencies": { + "better-sqlite3": "^12.10.0", + "teaql-ts": "file:../..", + "ts-node": "^10.9.2", + "typescript": "5.4.5" + }, + "devDependencies": { + "@types/node": "^22.0.0" + } +} diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/tsconfig.json b/source/teaql-ts/examples/ensure-schema-bootstrap/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..e87ef5125bd4702d667f272634082fdd2815cbd4 --- /dev/null +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "CommonJS", + "moduleResolution": "Node", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true + }, + "include": ["app.ts"] +} diff --git a/source/teaql-ts/examples/facet-trace/.gitignore b/source/teaql-ts/examples/facet-trace/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3d2bc62692c4b0ba42e61d71a964424f53f9c2be --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/.gitignore @@ -0,0 +1,2 @@ +/dist/ +/node_modules/ diff --git a/source/teaql-ts/examples/facet-trace/README.md b/source/teaql-ts/examples/facet-trace/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ac9513b485bf4c5b8e149b281a17a62a6116c437 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/README.md @@ -0,0 +1,33 @@ +# Generated Facet Trace Chain acceptance + +Run `bash examples/facet-trace/verify.sh`. It rebuilds this repository's runtime, +uses a `file:../..` dependency, verifies runtime resolution to repository `dist`, +and executes twice on one retained fresh SQLite file without cleanup. The +all-examples gate includes it. All 16 generated library inputs (13 TypeScript +sources plus manifests/i18n) remain unchanged. + +The three-object School model isolates `TC-SQL-09` and related privacy: 48 +combinations of root/nested/loaded-relation Facets, exact/prefix predicates, +include-all/matched-only, empty/nonempty matches and diagnostic logging on/off. +It asserts typed `SmartList` carriers, loaded-empty versus NotLoaded, +visible limit one versus full count two, exact count/materialization SQL numbers, +ordered inherited paths, logical edge details, original request intent, and +root/future-only private binding redaction. Fixture writes use generated audited +mutation APIs. This fixture does not claim Facet-specific E API traversal. + +`FACET_OBSERVED` records real counts, returned Facets and safe execution evidence. +An explicitly installed evidence sink continues collecting safe physical facts +when diagnostic logging is off; the diagnostic sink receives zero events in +that mode. This is not a claim that log-off disables an explicitly requested +evidence collector. + +`lib/` is read-only output from producer +`cddabd0976bfcd3251f79333a49e03d732e20b2c`, whose generated carrier repair is +retained under producer #251. Do not inspect generated source for API discovery. +Use model-aware action/entity/field Assist with `model.xml` for new operations; +report `MISSING_ASSIST` instead of guessing. + +Downloaded-package acceptance belongs in a separate workspace with fixed npm +tarball/package hashes and actual module resolution. Never change this local +example to silently exercise an installed release. This fixture does not prove +all Trace Chain cases, external providers or public-release parity. diff --git a/source/teaql-ts/examples/facet-trace/consumer.ts b/source/teaql-ts/examples/facet-trace/consumer.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8d1ae26df1ea3009b54f4f38d81deba13d96bee --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/consumer.ts @@ -0,0 +1,158 @@ +import assert from 'node:assert/strict'; +import { Q } from './lib/src/generated/Q'; +import { School } from './lib/src/generated/models/School'; +import { SmartList, UserContext } from './lib/src/teaql-ts'; +import { SQLiteTeaQLClient } from './lib/src/teaql-node-sqlite'; +import { SQLExecutionEvidenceStore, SQLExecutionMetadata } from 'teaql-ts/sql/core'; + +const privateName = 'FACET-PRIVATE-SCHOOL'; +const privatePlatform = 'Campus Learning Platform'; +const purpose = 'verify generated Facet ownership'; +function schoolFacets(includeAll: boolean, prefix: boolean, nested: boolean) { + const query = Q.schools(); + if (prefix) query.withNameStartingWith(privateName); + else query.withNameIn(privateName, privateName + '-B'); + const types = Q.schoolTypes().orderByIdAscending().limit(10).countAs('schoolCount'); + if (nested) types.facetByPlatformAs('platforms', Q.platforms().withNameIs(privatePlatform) + .orderByIdAscending().limit(10).countAs('typeCount'), includeAll); + return query.orderByIdAscending().limit(1).facetBySchoolTypeAs('types', types, includeAll); +} +function assertFacets(list: SmartList, includeAll: boolean, count: number, nested: boolean) { + const types = list.facets.types; + assert.ok(types instanceof SmartList, 'requested type Facet must exist even when empty'); + const pairs = types.map(row => { + assert.equal(typeof row.schoolCount, 'number', 'count is present, not defaulted'); + return [String(row.id), row.schoolCount]; + }); + assert.deepEqual(pairs, includeAll ? [['1001', count], ['1002', 0]] + : count ? [['1001', count]] : []); + const platforms = types.facets.platforms; + if (!nested) { + assert.equal(platforms, undefined, 'unrequested nested Facet must remain absent'); + return {types: pairs, platforms: null}; + } + assert.ok(platforms instanceof SmartList, 'nested platform Facet must exist'); + const platformPairs = platforms.map(row => [String(row.id), row.typeCount]); + assert.deepEqual(platformPairs, + includeAll ? [['1', 2]] : count ? [['1', 1]] : []); + return {types: pairs, platforms: platformPairs}; +} +function assertEvidence(entries: readonly SQLExecutionMetadata[], diagnostics: unknown[], + root: string, loaded: boolean, nested: boolean, logging: boolean) { + const expectedRoutes = loaded ? ['', 'schoolList', 'schoolList', 'schoolList', + 'schoolList/schoolType', 'schoolList/schoolType', 'schoolList/schoolType/platform', + 'schoolList', 'schoolList/schoolType', 'schoolList/schoolType', 'schoolList/schoolType/platform'] + : nested ? ['', '', 'schoolType', 'schoolType', 'schoolType/platform'] : ['', '', 'schoolType']; + assert.equal(entries.length, expectedRoutes.length, 'physical SQL count'); + assert.deepEqual(entries.map(entry => entry.tracePath.filter(node => node.kind === 'relation') + .map(node => node.name).join('/')), expectedRoutes, 'ordered physical Facet ancestry'); + const allowed = loaded ? [[], ['schoolList'], ['schoolList', 'schoolType'], + ['schoolList', 'schoolType', 'platform']] + : [[], ['schoolType'], ['schoolType', 'platform']]; + for (const entry of entries) { + assert.equal(entry.executionOutcome, 'success'); + assert.equal(entry.purpose, purpose); + assert.match(entry.comment ?? '', /^load /); + const path = entry.tracePath; + assert.deepEqual(path.slice(0, 2).map(n => [n.kind, n.name, n.detail ?? '']), + [['operation', root, 'query'], ['request', root, '']]); + const route = path.slice(2, -2); + assert.ok(allowed.some(a => JSON.stringify(a) === JSON.stringify(route.map(n => n.name)))); + let entity = root; + for (const node of route) { + assert.equal(node.kind, 'relation'); + assert.equal(node.detail, entity + '.' + node.name); + entity = node.name === 'schoolList' ? 'School' : node.name === 'schoolType' ? 'SchoolType' : 'Platform'; + } + assert.deepEqual(path.slice(-2).map(n => [n.kind, n.name]), + [['provider', 'sqlite'], ['sql', 'select']]); + } + const deepest = loaded ? 'schoolList/schoolType/platform' : nested ? 'schoolType/platform' : 'schoolType'; + assert.ok(entries.some(e => e.tracePath.filter(n => n.kind === 'relation') + .map(n => n.name).join('/') === deepest)); + const counts = entries.filter(e => /COUNT\s*\(/i.test(e.parameterizedSQL)); + assert.equal(counts.length, loaded ? 4 : nested ? 2 : 1, 'physical membership count SQL'); + assert.equal(diagnostics.length, logging ? entries.length : 0); + for (const secret of [privateName, privatePlatform]) { + assert.ok(!JSON.stringify(entries).includes(secret), 'private intent leaked in execution evidence: ' + + JSON.stringify(entries.filter(entry => JSON.stringify(entry).includes(secret)))); + assert.ok(!JSON.stringify(diagnostics).includes(secret), 'private intent leaked in diagnostics'); + } +} +async function main() { + const database = process.env.TEAQL_FACET_TRACE_DB; + assert.ok(database, 'Set TEAQL_FACET_TRACE_DB or run examples/facet-trace/verify.sh'); + const client = new SQLiteTeaQLClient(database).setDiagnosticSQLLogSink(undefined); + const context = new UserContext().insertResource('dataService', client); + try { + await context.ensureSchema(); + for (const suffix of ['', '-B']) { + const name = privateName + suffix; + const existing = await Q.schools().withNameIs(name).limit(1) + .comment('find retained fixture').purpose('idempotent seed').executeForList(context); + if (!existing.length) { + const school = Q.schools().comment('initialize fixture').purpose('idempotent seed').newEntity(context); + school.updatePlatform('1').updateSchoolType('1001').updateName(name) + .updateAddress('12 River Road').updateEstablishedDate('1995-09-01') + .updateStudentCapacity(800).updateActive(true); + await school.auditAs('seed retained Facet acceptance').save(context); + } + } + const evidence = new SQLExecutionEvidenceStore(); + const diagnostics: unknown[] = []; + client.setRuntimeTelemetrySink(evidence).setDiagnosticSQLLogSink({write: entry => diagnostics.push(entry)}); + let cases = 0; + for (const prefix of [false, true]) for (const logging of [false, true]) for (const includeAll of [false, true]) + for (const mode of ['root', 'nested', 'loaded']) { + client.setQueryLoggingEnabled(logging); + for (const empty of [false, true]) { + evidence.enableSelect(); diagnostics.length = 0; + const nested = mode !== 'root', loaded = mode === 'loaded'; + const request = schoolFacets(includeAll, prefix, nested); + if (empty) request.withNameIs('absent'); + const comment = 'load ' + privateName + (nested ? ' via ' + privatePlatform : ''); + const results: unknown[] = []; + if (loaded) { + const parents = await Q.schoolTypes().orderByIdAscending().limit(10) + .selectSchoolListWith(request).comment(comment).purpose(purpose).executeForList(context); + assert.deepEqual(parents.map(parent => String(parent.id)), ['1001', '1002']); + for (const parent of parents) { + const children: SmartList = parent.schoolList(); + assert.ok(children instanceof SmartList, 'generated loaded relation lost native SmartList'); + assert.equal(children.isLoaded, true, 'loaded empty and nonempty collections retain loaded state'); + const members = !empty && parent.id === '1001' ? 2 : 0; + assert.equal(children.length, members ? 1 : 0); + if (children.length) assert.ok(children[0] instanceof School); + results.push({parentId: String(parent.id), visibleRows: children.length, + facets: assertFacets(children, includeAll, members, true)}); + } + } else { + const result: SmartList = await request.comment(comment).purpose(purpose).executeForList(context); + assert.equal(result.length, empty ? 0 : 1); + if (!empty) assert.ok(result[0] instanceof School); + results.push({visibleRows: result.length, + facets: assertFacets(result, includeAll, empty ? 0 : 2, nested)}); + } + const entries = evidence.snapshot(); + assertEvidence(entries, diagnostics, loaded ? 'SchoolType' : 'School', loaded, nested, logging); + console.log('FACET_OBSERVED ' + JSON.stringify({mode, prefix, logging, includeAll, empty, + physical: entries.length, counts: entries.filter(entry => /COUNT\s*\(/i.test(entry.parameterizedSQL)).length, + results, diagnostics: diagnostics.length, sql: entries})); + cases++; + } + evidence.enableSelect(); diagnostics.length = 0; + const independent = await Q.schoolTypes().withIdIs('1001').limit(1) + .comment(privateName + ' is ordinary prose in the next request') + .purpose('independent next request').executeForList(context); + assert.equal(evidence.snapshot()[0].comment, + privateName + ' is ordinary prose in the next request'); + const notLoaded: SmartList = independent[0].schoolList(); + assert.equal(notLoaded.isLoaded, false, 'absent relation must remain NotLoaded'); + assert.equal(independent[0].isLoaded('schoolList'), false); + } + assert.equal(cases, 48); + console.log('TypeScript generated Facet acceptance passed: ' + cases + + ' scenarios; both logging modes; exact/prefix; root/nested/loaded/empty/includeAll; retained school.db'); + } finally { await client.close(); } +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/facet-trace/lib/package.json b/source/teaql-ts/examples/facet-trace/lib/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a40b84b543ec6d577cc6334a94479f0da757d521 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/package.json @@ -0,0 +1,17 @@ +{ + "name": "school-management-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.2.10", + "better-sqlite3": "^12.10.0"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated-bootstrap.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3da68070cb03b66985d084711a3d4e417fb6d5a --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated-bootstrap.ts @@ -0,0 +1,48 @@ +import { UserContext } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Platform } from './generated/models/Platform'; +import { SchoolType } from './generated/models/SchoolType'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot.updateName("Campus Learning Platform"); + domainRoot.updateBaseUrl("https://campus.example.com"); + await domainRoot.auditAs('create generated Domain Root Platform').save(context); + } + context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! }); + let constantSchoolType1001 = (await Q.schoolTypes().withIdIs("1001").comment('what: locate generated constant SchoolType(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantSchoolType1001) { + constantSchoolType1001 = SchoolType.teaqlBootstrapNew("1001"); + constantSchoolType1001.updatePlatform(domainRoot); + constantSchoolType1001.updateName("Primary"); + constantSchoolType1001.updateCode("PRIMARY"); + constantSchoolType1001.updateDisplayOrder(1); + await constantSchoolType1001.auditAs('create model constant SchoolType(1001)').save(context); + } else { + let changed = false; + if (String((constantSchoolType1001.platform as any)?.id ?? constantSchoolType1001.platform) !== String(domainRoot.id)) { constantSchoolType1001.updatePlatform(domainRoot); changed = true; } + if (constantSchoolType1001.name !== "Primary") { constantSchoolType1001.updateName("Primary"); changed = true; } + if (constantSchoolType1001.code !== "PRIMARY") { constantSchoolType1001.updateCode("PRIMARY"); changed = true; } + if (constantSchoolType1001.displayOrder !== 1) { constantSchoolType1001.updateDisplayOrder(1); changed = true; } + if (changed) await constantSchoolType1001.auditAs('reconcile model constant SchoolType(1001)').save(context); + } + let constantSchoolType1002 = (await Q.schoolTypes().withIdIs("1002").comment('what: locate generated constant SchoolType(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantSchoolType1002) { + constantSchoolType1002 = SchoolType.teaqlBootstrapNew("1002"); + constantSchoolType1002.updatePlatform(domainRoot); + constantSchoolType1002.updateName("Secondary"); + constantSchoolType1002.updateCode("SECONDARY"); + constantSchoolType1002.updateDisplayOrder(2); + await constantSchoolType1002.auditAs('create model constant SchoolType(1002)').save(context); + } else { + let changed = false; + if (String((constantSchoolType1002.platform as any)?.id ?? constantSchoolType1002.platform) !== String(domainRoot.id)) { constantSchoolType1002.updatePlatform(domainRoot); changed = true; } + if (constantSchoolType1002.name !== "Secondary") { constantSchoolType1002.updateName("Secondary"); changed = true; } + if (constantSchoolType1002.code !== "SECONDARY") { constantSchoolType1002.updateCode("SECONDARY"); changed = true; } + if (constantSchoolType1002.displayOrder !== 2) { constantSchoolType1002.updateDisplayOrder(2); changed = true; } + if (changed) await constantSchoolType1002.auditAs('reconcile model constant SchoolType(1002)').save(context); + } +} diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated-search-models.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4de27ef5dcdaee56b4e5f5b7b711929c22d1b18 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated-search-models.ts @@ -0,0 +1,100 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Platform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "base_url": "string" as const, + "baseUrl": "string" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "base_url": "baseUrl", + "baseUrl": "baseUrl", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "schoolTypeList": "SchoolType", + "schoolList": "School", + }), + }), + "SchoolType": Object.freeze({ + fields: Object.freeze({ + "platform": "integer" as const, + "id": "integer" as const, + "name": "string" as const, + "code": "string" as const, + "display_order": "decimal" as const, + "displayOrder": "decimal" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "platform": "platform", + "id": "id", + "name": "name", + "code": "code", + "display_order": "displayOrder", + "displayOrder": "displayOrder", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + "schoolList": "School", + }), + }), + "School": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "platform": "integer" as const, + "school_type": "integer" as const, + "schoolType": "integer" as const, + "name": "string" as const, + "address": "string" as const, + "established_date": "date" as const, + "establishedDate": "date" as const, + "student_capacity": "integer" as const, + "studentCapacity": "integer" as const, + "active": "boolean" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "platform": "platform", + "school_type": "schoolType", + "schoolType": "schoolType", + "name": "name", + "address": "address", + "established_date": "establishedDate", + "establishedDate": "establishedDate", + "student_capacity": "studentCapacity", + "studentCapacity": "studentCapacity", + "active": "active", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + "school_type": "SchoolType", + "schoolType": "SchoolType", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/E.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..3285a0035cf94d46b353d789edabd6cbe62a8265 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/E.ts @@ -0,0 +1,629 @@ +import { Platform } from './models/Platform'; +import { SchoolType } from './models/SchoolType'; +import { School } from './models/School'; + +export class TeaQLNotLoadedError extends Error { + readonly details: Record; + + constructor( + readonly root: string, + readonly accessPath: string, + readonly breakPoint: string, + ) { + const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; + const details = { + error: 'TeaQLNotLoadedError', + root, + accessPath: accessPath.split('.'), + breakPoint, + missingPreload: [breakPoint], + suggestedFix, + severity: 'error', + humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, + }; + super(JSON.stringify(details)); + this.name = 'TeaQLNotLoadedError'; + this.details = details; + } +} + +function expressionPath(prefix: string, field: string): string { + return prefix ? `${prefix}.${field}` : field; +} + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded; + return this.present; + } + + orElse(fallback: T): T { + const value = this.eval(); + return this.present && value != null ? value : fallback; + } +} + +export class PlatformExpression { + constructor( + private readonly value: Platform | null | undefined, + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Platform | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + baseUrl(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'baseUrl'); + if (!this.value.isLoaded('baseUrl')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'baseUrl'), + ); + } + return new ValueExpression(this.value.baseUrl); + } + + createTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'createTime'); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'createTime'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'updateTime'); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'updateTime'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + schoolTypeList(): SchoolTypeListExpression { + const path = expressionPath(this.path, 'schoolTypeList'); + if (this.notLoaded) { + return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolTypeListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolTypeList')) { + return new SchoolTypeListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolTypeList')); + } + return new SchoolTypeListExpression( + this.value.schoolTypeList(), this.root, path, + ); + } + + schoolList(): SchoolListExpression { + const path = expressionPath(this.path, 'schoolList'); + if (this.notLoaded) { + return new SchoolListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolList')) { + return new SchoolListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolList')); + } + return new SchoolListExpression( + this.value.schoolList(), this.root, path, + ); + } +} + +export class SchoolTypeExpression { + constructor( + private readonly value: SchoolType | null | undefined, + private readonly root = 'SchoolType(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): SchoolType | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + code(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'code'); + if (!this.value.isLoaded('code')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'code'), + ); + } + return new ValueExpression(this.value.code); + } + + displayOrder(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'displayOrder'); + if (!this.value.isLoaded('displayOrder')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'displayOrder'), + ); + } + return new ValueExpression(this.value.displayOrder); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'platform'); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = expressionPath(this.path, 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'platform')); + } + const relation = this.value.platform; + const target = relation == null + ? undefined + : relation instanceof Platform + ? relation + : Platform.fromRecord({ id: relation }); + return new PlatformExpression(target, this.root, path); + } + + schoolList(): SchoolListExpression { + const path = expressionPath(this.path, 'schoolList'); + if (this.notLoaded) { + return new SchoolListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolList')) { + return new SchoolListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolList')); + } + return new SchoolListExpression( + this.value.schoolList(), this.root, path, + ); + } +} + +export class SchoolExpression { + constructor( + private readonly value: School | null | undefined, + private readonly root = 'School(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): School | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + address(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'address'); + if (!this.value.isLoaded('address')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'address'), + ); + } + return new ValueExpression(this.value.address); + } + + establishedDate(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'establishedDate'); + if (!this.value.isLoaded('establishedDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'establishedDate'), + ); + } + return new ValueExpression(this.value.establishedDate); + } + + studentCapacity(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'studentCapacity'); + if (!this.value.isLoaded('studentCapacity')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'studentCapacity'), + ); + } + return new ValueExpression(this.value.studentCapacity); + } + + active(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'active'); + if (!this.value.isLoaded('active')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'active'), + ); + } + return new ValueExpression(this.value.active); + } + + createTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'createTime'); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'createTime'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'updateTime'); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'updateTime'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'platform'); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + schoolTypeId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'schoolType'); + if (!this.value.isLoaded('schoolType')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'schoolType'), + ); + } + const reference = this.value.schoolType; + return new ValueExpression( + reference instanceof SchoolType + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = expressionPath(this.path, 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'platform')); + } + const relation = this.value.platform; + const target = relation == null + ? undefined + : relation instanceof Platform + ? relation + : Platform.fromRecord({ id: relation }); + return new PlatformExpression(target, this.root, path); + } + + schoolType(): SchoolTypeExpression { + const path = expressionPath(this.path, 'schoolType'); + if (this.notLoaded) { + return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new SchoolTypeExpression(undefined, this.root, path); + if (!this.value.isLoaded('schoolType')) { + return new SchoolTypeExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'schoolType')); + } + const relation = this.value.schoolType; + const target = relation == null + ? undefined + : relation instanceof SchoolType + ? relation + : SchoolType.fromRecord({ id: relation }); + return new SchoolTypeExpression(target, this.root, path); + } + +} + +export class PlatformListExpression { + constructor( + private readonly items: readonly Platform[], + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): PlatformListExpression { + return new PlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): PlatformExpression { + return this.get(0); + } + + get(index: number): PlatformExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new PlatformExpression(undefined, this.root, itemPath) + : new PlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class SchoolTypeListExpression { + constructor( + private readonly items: readonly SchoolType[], + private readonly root = 'SchoolType(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): SchoolTypeListExpression { + return new SchoolTypeListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): SchoolTypeExpression { + return this.get(0); + } + + get(index: number): SchoolTypeExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new SchoolTypeExpression(undefined, this.root, itemPath) + : new SchoolTypeExpression(this.items[index], this.root, itemPath); + } +} + +export class SchoolListExpression { + constructor( + private readonly items: readonly School[], + private readonly root = 'School(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): SchoolListExpression { + return new SchoolListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): SchoolExpression { + return this.get(0); + } + + get(index: number): SchoolExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new SchoolExpression(undefined, this.root, itemPath) + : new SchoolExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static platform( + value: Platform | null | undefined, + ): PlatformExpression { + return new PlatformExpression( + value, `Platform(id=${value?.id ?? 'null'})`, + ); + } + + static schoolType( + value: SchoolType | null | undefined, + ): SchoolTypeExpression { + return new SchoolTypeExpression( + value, `SchoolType(id=${value?.id ?? 'null'})`, + ); + } + + static school( + value: School | null | undefined, + ): SchoolExpression { + return new SchoolExpression( + value, `School(id=${value?.id ?? 'null'})`, + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/Q.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..14bc3c4d047059343113a1d18f45876936ea2f3f --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/Q.ts @@ -0,0 +1,28 @@ +import { TeaQLClient } from '../teaql-ts'; +import { PlatformRequest } from './requests/PlatformRequest'; +import { SchoolTypeRequest } from './requests/SchoolTypeRequest'; +import { SchoolRequest } from './requests/SchoolRequest'; + +export class Q { + static platforms(): PlatformRequest { + return new PlatformRequest(false); + } + + static platformsWithMinimalFields(): PlatformRequest { + return new PlatformRequest(true); + } + static schoolTypes(): SchoolTypeRequest { + return new SchoolTypeRequest(false); + } + + static schoolTypesWithMinimalFields(): SchoolTypeRequest { + return new SchoolTypeRequest(true); + } + static schools(): SchoolRequest { + return new SchoolRequest(false); + } + + static schoolsWithMinimalFields(): SchoolRequest { + return new SchoolRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/Platform.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/Platform.ts new file mode 100644 index 0000000000000000000000000000000000000000..6290c60e32711869d3b5361d5553bf014d622502 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/Platform.ts @@ -0,0 +1,349 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { SchoolType } from './SchoolType'; +import { School } from './School'; + +export class Platform { + private static teaqlTemporaryId = 0; + id?: string; + name?: string; + baseUrl?: string; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolTypeList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["schoolTypeList"]; + delete fields["schoolList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).schoolTypeList)) { + const selected = (init as any).schoolTypeList; + (this as any)._schoolTypeList = new SmartList(selected.map( + (child: unknown) => child instanceof SchoolType + ? child + : SchoolType.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolTypeList"); + } + if (Array.isArray((init as any).schoolList)) { + const selected = (init as any).schoolList; + (this as any)._schoolList = new SmartList(selected.map( + (child: unknown) => child instanceof School + ? child + : School.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Platform { + const entity = new Platform(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Platform { + return new Platform({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Platform { + return new Platform().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Platform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Platform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "base_url": this.baseUrl, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateBaseUrl(value: string): this { + this.baseUrl = value; + this.markLoaded("baseUrl"); + (this as any)._root.set(this.teaqlEntityKey(), "base_url", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + schoolTypeList(): SmartList { + return (this as any)._schoolTypeList; + } + + schoolList(): SmartList { + return (this as any)._schoolList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/School.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/School.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0e0932d518e97acbecdeed78ef3e6749956f366 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/School.ts @@ -0,0 +1,302 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; +import { SchoolType } from './SchoolType'; + +export class School { + private static teaqlTemporaryId = 0; + id?: string; + platform?: Platform | string; + schoolType?: SchoolType | string; + name?: string; + address?: string; + establishedDate?: string; + studentCapacity?: number; + active?: boolean; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --School.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if ((init as any).schoolType && typeof (init as any).schoolType === "object") { + this.schoolType = (init as any).schoolType instanceof SchoolType + ? (init as any).schoolType + : SchoolType.fromRecord((init as any).schoolType); + this.markLoaded("schoolType"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "School", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): School { + const entity = new School(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): School { + return new School({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): School { + return new School().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "School", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "School", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "platform": this.platform, + "school_type": this.schoolType, + "name": this.name, + "address": this.address, + "established_date": this.establishedDate, + "student_capacity": this.studentCapacity, + "active": this.active, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateAddress(value: string): this { + this.address = value; + this.markLoaded("address"); + (this as any)._root.set(this.teaqlEntityKey(), "address", value); + return this; + } + + updateEstablishedDate(value: string): this { + this.establishedDate = value; + this.markLoaded("establishedDate"); + (this as any)._root.set(this.teaqlEntityKey(), "established_date", value); + return this; + } + + updateStudentCapacity(value: number): this { + this.studentCapacity = value; + this.markLoaded("studentCapacity"); + (this as any)._root.set(this.teaqlEntityKey(), "student_capacity", value); + return this; + } + + updateActive(value: boolean): this { + this.active = value; + this.markLoaded("active"); + (this as any)._root.set(this.teaqlEntityKey(), "active", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + + updateSchoolType(value: any): this { + this.schoolType = value?.id ?? value; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + public updateSchoolTypeToPrimary(): School { + this.schoolType = "1001"; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + public updateSchoolTypeToSecondary(): School { + this.schoolType = "1002"; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/SchoolType.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/SchoolType.ts new file mode 100644 index 0000000000000000000000000000000000000000..0677cb7d71363977bb4b42d7d44bce7d089cc983 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/SchoolType.ts @@ -0,0 +1,296 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; +import { School } from './School'; + +export class SchoolType { + private static teaqlTemporaryId = 0; + platform?: Platform | string; + id?: string; + name?: string; + code?: string; + displayOrder?: number; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --SchoolType.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["schoolList"]; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if (Array.isArray((init as any).schoolList)) { + const selected = (init as any).schoolList; + (this as any)._schoolList = new SmartList(selected.map( + (child: unknown) => child instanceof School + ? child + : School.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "SchoolType", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): SchoolType { + const entity = new SchoolType(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): SchoolType { + return new SchoolType({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): SchoolType { + return new SchoolType().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "SchoolType", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "SchoolType", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "platform": this.platform, + "id": this.id, + "name": this.name, + "code": this.code, + "display_order": this.displayOrder, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateCode(value: string): this { + this.code = value; + this.markLoaded("code"); + (this as any)._root.set(this.teaqlEntityKey(), "code", value); + return this; + } + + updateDisplayOrder(value: number): this { + this.displayOrder = value; + this.markLoaded("displayOrder"); + (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + schoolList(): SmartList { + return (this as any)._schoolList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..af9cf03a986e08d02115cba30825e5e6b3bbfdf6 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts @@ -0,0 +1,1161 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Platform } from '../models/Platform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class PlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Platform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutablePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutablePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "baseUrl", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectBaseUrl(): this { + this.query.select(["baseUrl"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectSchoolTypeListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolTypeList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectSchoolTypeListWith", relation: "schoolTypeList" }); + return this; + } + selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); + return this; + } + + haveSchoolTypes(): this { + return this.withSchoolTypeListMatching({ + toQuery: () => new SelectQuery("SchoolType"), + }); + } + + haveNoSchoolTypes(): this { + return this.withoutSchoolTypeListMatching({ + toQuery: () => new SelectQuery("SchoolType"), + }); + } + + withSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + haveSchools(): this { + return this.withSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + haveNoSchools(): this { + return this.withoutSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + countSchoolTypes(): this { + return this.countSchoolTypesAs("countSchoolTypes"); + } + + countSchoolTypesAs(alias: string): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + this.countSchoolTypesWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolTypesAs", relation: "schoolTypeList", alias }; + return this; + } + + countSchoolTypesWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "relation-count", method: "countSchoolTypesWith", relation: "schoolTypeList", alias }); + return this; + } + + minDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.minDisplayOrderOfSchoolTypesAs( + "minOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + minDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "minDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + maxDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.maxDisplayOrderOfSchoolTypesAs( + "maxOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + maxDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "maxDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + sumDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.sumDisplayOrderOfSchoolTypesAs( + "sumOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + sumDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "sumDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + avgDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.avgDisplayOrderOfSchoolTypesAs( + "avgOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + avgDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "avgDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + standardDeviationDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.standardDeviationDisplayOrderOfSchoolTypesAs( + "standardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs( + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + sampleVarianceDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceDisplayOrderOfSchoolTypesAs( + "sampleVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + samplePopulationVarianceDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceDisplayOrderOfSchoolTypesAs( + "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + countSchools(): this { + return this.countSchoolsAs("countSchools"); + } + + countSchoolsAs(alias: string): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + this.countSchoolsWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; + return this; + } + + countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "relation-count", method: "countSchoolsWith", relation: "schoolList", alias }); + return this; + } + + minStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.minStudentCapacityOfSchoolsAs( + "minOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "minStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + maxStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.maxStudentCapacityOfSchoolsAs( + "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "maxStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sumStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sumStudentCapacityOfSchoolsAs( + "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sumStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + avgStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.avgStudentCapacityOfSchoolsAs( + "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "avgStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + standardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.standardDeviationStudentCapacityOfSchoolsAs( + "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "standardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sampleVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceStudentCapacityOfSchoolsAs( + "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + samplePopulationVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( + "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withBaseUrlContaining(val: string): this { + this.filters.push({ "baseUrl": { "$contains": val } }); + return this; + } + + withBaseUrlIs(val: string): this { + this.filters.push({ "baseUrl": { "$eq": val } }); + return this; + } + + withBaseUrlIsNot(val: any): this { + this.filters.push({ "baseUrl": { "$ne": val } }); + return this; + } + + withBaseUrlIn(...vals: any[]): this { + this.filters.push({ "baseUrl": { "$in": vals } }); + return this; + } + + withBaseUrlNotIn(...vals: any[]): this { + this.filters.push({ "baseUrl": { "$notIn": vals } }); + return this; + } + + withBaseUrlGreaterThan(val: any): this { + this.filters.push({ "baseUrl": { "$gt": val } }); + return this; + } + + withBaseUrlGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "baseUrl": { "$gte": val } }); + return this; + } + + withBaseUrlLessThan(val: any): this { + this.filters.push({ "baseUrl": { "$lt": val } }); + return this; + } + + withBaseUrlLessThanOrEqualTo(val: any): this { + this.filters.push({ "baseUrl": { "$lte": val } }); + return this; + } + + withBaseUrlBetween(lower: any, upper: any): this { + this.filters.push({ "baseUrl": { "$between": [lower, upper] } }); + return this; + } + + withBaseUrlIsKnown(): this { + this.filters.push({ "baseUrl": { "$isNull": false } }); + return this; + } + + withBaseUrlIsUnknown(): this { + this.filters.push({ "baseUrl": { "$isNull": true } }); + return this; + } + withBaseUrlNotContaining(val: string): this { + this.filters.push({ "baseUrl": { "$notContains": val } }); + return this; + } + + withBaseUrlStartingWith(val: string): this { + this.filters.push({ "baseUrl": { "$startsWith": val } }); + return this; + } + + withBaseUrlNotStartingWith(val: string): this { + this.filters.push({ "baseUrl": { "$notStartsWith": val } }); + return this; + } + + withBaseUrlEndingWith(val: string): this { + this.filters.push({ "baseUrl": { "$endsWith": val } }); + return this; + } + + withBaseUrlNotEndingWith(val: string): this { + this.filters.push({ "baseUrl": { "$notEndsWith": val } }); + return this; + } + + withBaseUrlSoundingLike(val: string): this { + this.filters.push({ "baseUrl": { "$soundLike": val } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: any): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: any): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: any): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: any): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: any): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: any): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByBaseUrlAscending(): this { + this.query.orderBy("baseUrl", "asc"); + return this; + } + + orderByBaseUrlDescending(): this { + this.query.orderBy("baseUrl", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByBaseUrl(): this { + this.query.groupBy("baseUrl"); + return this; + } + + groupByBaseUrlAs(retName: string): this { + this.query.groupBy("baseUrl"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Platform + ? entity + : Platform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutablePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Platform { + this.ensureIntent(); + return new Platform(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..394ab2a4fb412ab2b2e47194914185b0857cf66b --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts @@ -0,0 +1,1260 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { School } from '../models/School'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class SchoolRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("School"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableSchoolRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableSchoolRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "platform", "schoolType", "name", "address", "establishedDate", "studentCapacity", "active", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectAddress(): this { + this.query.select(["address"]); + return this; + } + + selectEstablishedDate(): this { + this.query.select(["establishedDate"]); + return this; + } + + selectStudentCapacity(): this { + this.query.select(["studentCapacity"]); + return this; + } + + selectActive(): this { + this.query.select(["active"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + selectSchoolTypeWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["schoolType"]); + this.query.relationQuery( + "schoolType", request.toQuery(), "schoolType", "id", false, + { kind: "relation-select", method: "selectSchoolTypeWith", relation: "schoolType" }); + return this; + } + + withPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "schoolType": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "schoolType": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + filterBySchoolType(val: any): this { + this.filters.push({ "schoolType": { "$eq": val } }); + return this; + } + + filterBySchoolTypeIn(...vals: any[]): this { + this.filters.push({ "schoolType": { "$in": vals } }); + return this; + } + + withSchoolTypeIsKnown(): this { + this.filters.push({ "schoolType": { "$isNull": false } }); + return this; + } + + withSchoolTypeIsUnknown(): this { + this.filters.push({ "schoolType": { "$isNull": true } }); + return this; + } + withSchoolTypeIsPrimary(): this { + this.filters.push({ "schoolType": { "$eq": "1001" } }); + return this; + } + withSchoolTypeIsSecondary(): this { + this.filters.push({ "schoolType": { "$eq": "1002" } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withAddressContaining(val: string): this { + this.filters.push({ "address": { "$contains": val } }); + return this; + } + + withAddressIs(val: string): this { + this.filters.push({ "address": { "$eq": val } }); + return this; + } + + withAddressIsNot(val: any): this { + this.filters.push({ "address": { "$ne": val } }); + return this; + } + + withAddressIn(...vals: any[]): this { + this.filters.push({ "address": { "$in": vals } }); + return this; + } + + withAddressNotIn(...vals: any[]): this { + this.filters.push({ "address": { "$notIn": vals } }); + return this; + } + + withAddressGreaterThan(val: any): this { + this.filters.push({ "address": { "$gt": val } }); + return this; + } + + withAddressGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "address": { "$gte": val } }); + return this; + } + + withAddressLessThan(val: any): this { + this.filters.push({ "address": { "$lt": val } }); + return this; + } + + withAddressLessThanOrEqualTo(val: any): this { + this.filters.push({ "address": { "$lte": val } }); + return this; + } + + withAddressBetween(lower: any, upper: any): this { + this.filters.push({ "address": { "$between": [lower, upper] } }); + return this; + } + + withAddressIsKnown(): this { + this.filters.push({ "address": { "$isNull": false } }); + return this; + } + + withAddressIsUnknown(): this { + this.filters.push({ "address": { "$isNull": true } }); + return this; + } + withAddressNotContaining(val: string): this { + this.filters.push({ "address": { "$notContains": val } }); + return this; + } + + withAddressStartingWith(val: string): this { + this.filters.push({ "address": { "$startsWith": val } }); + return this; + } + + withAddressNotStartingWith(val: string): this { + this.filters.push({ "address": { "$notStartsWith": val } }); + return this; + } + + withAddressEndingWith(val: string): this { + this.filters.push({ "address": { "$endsWith": val } }); + return this; + } + + withAddressNotEndingWith(val: string): this { + this.filters.push({ "address": { "$notEndsWith": val } }); + return this; + } + + withAddressSoundingLike(val: string): this { + this.filters.push({ "address": { "$soundLike": val } }); + return this; + } + + withEstablishedDateIs(val: any): this { + this.filters.push({ "establishedDate": { "$eq": val } }); + return this; + } + + withEstablishedDateIsNot(val: any): this { + this.filters.push({ "establishedDate": { "$ne": val } }); + return this; + } + + withEstablishedDateIn(...vals: any[]): this { + this.filters.push({ "establishedDate": { "$in": vals } }); + return this; + } + + withEstablishedDateNotIn(...vals: any[]): this { + this.filters.push({ "establishedDate": { "$notIn": vals } }); + return this; + } + + withEstablishedDateGreaterThan(val: any): this { + this.filters.push({ "establishedDate": { "$gt": val } }); + return this; + } + + withEstablishedDateGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "establishedDate": { "$gte": val } }); + return this; + } + + withEstablishedDateLessThan(val: any): this { + this.filters.push({ "establishedDate": { "$lt": val } }); + return this; + } + + withEstablishedDateLessThanOrEqualTo(val: any): this { + this.filters.push({ "establishedDate": { "$lte": val } }); + return this; + } + + withEstablishedDateBetween(lower: any, upper: any): this { + this.filters.push({ "establishedDate": { "$between": [lower, upper] } }); + return this; + } + + withEstablishedDateIsKnown(): this { + this.filters.push({ "establishedDate": { "$isNull": false } }); + return this; + } + + withEstablishedDateIsUnknown(): this { + this.filters.push({ "establishedDate": { "$isNull": true } }); + return this; + } + + withStudentCapacityIs(val: any): this { + this.filters.push({ "studentCapacity": { "$eq": val } }); + return this; + } + + withStudentCapacityIsNot(val: any): this { + this.filters.push({ "studentCapacity": { "$ne": val } }); + return this; + } + + withStudentCapacityIn(...vals: any[]): this { + this.filters.push({ "studentCapacity": { "$in": vals } }); + return this; + } + + withStudentCapacityNotIn(...vals: any[]): this { + this.filters.push({ "studentCapacity": { "$notIn": vals } }); + return this; + } + + withStudentCapacityGreaterThan(val: any): this { + this.filters.push({ "studentCapacity": { "$gt": val } }); + return this; + } + + withStudentCapacityGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "studentCapacity": { "$gte": val } }); + return this; + } + + withStudentCapacityLessThan(val: any): this { + this.filters.push({ "studentCapacity": { "$lt": val } }); + return this; + } + + withStudentCapacityLessThanOrEqualTo(val: any): this { + this.filters.push({ "studentCapacity": { "$lte": val } }); + return this; + } + + withStudentCapacityBetween(lower: any, upper: any): this { + this.filters.push({ "studentCapacity": { "$between": [lower, upper] } }); + return this; + } + + withStudentCapacityIsKnown(): this { + this.filters.push({ "studentCapacity": { "$isNull": false } }); + return this; + } + + withStudentCapacityIsUnknown(): this { + this.filters.push({ "studentCapacity": { "$isNull": true } }); + return this; + } + + whichAreActive(): this { + this.filters.push({ "active": { "$eq": true } }); + return this; + } + + whichAreNotActive(): this { + this.filters.push({ "active": { "$eq": false } }); + return this; + } + withActiveIsNot(val: any): this { + this.filters.push({ "active": { "$ne": val } }); + return this; + } + + withActiveIn(...vals: any[]): this { + this.filters.push({ "active": { "$in": vals } }); + return this; + } + + withActiveNotIn(...vals: any[]): this { + this.filters.push({ "active": { "$notIn": vals } }); + return this; + } + + withActiveGreaterThan(val: any): this { + this.filters.push({ "active": { "$gt": val } }); + return this; + } + + withActiveGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "active": { "$gte": val } }); + return this; + } + + withActiveLessThan(val: any): this { + this.filters.push({ "active": { "$lt": val } }); + return this; + } + + withActiveLessThanOrEqualTo(val: any): this { + this.filters.push({ "active": { "$lte": val } }); + return this; + } + + withActiveBetween(lower: any, upper: any): this { + this.filters.push({ "active": { "$between": [lower, upper] } }); + return this; + } + + withActiveIsKnown(): this { + this.filters.push({ "active": { "$isNull": false } }); + return this; + } + + withActiveIsUnknown(): this { + this.filters.push({ "active": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: any): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: any): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: any): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: any): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: any): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: any): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByAddressAscending(): this { + this.query.orderBy("address", "asc"); + return this; + } + + orderByAddressDescending(): this { + this.query.orderBy("address", "desc"); + return this; + } + + orderByEstablishedDateAscending(): this { + this.query.orderBy("establishedDate", "asc"); + return this; + } + + orderByEstablishedDateDescending(): this { + this.query.orderBy("establishedDate", "desc"); + return this; + } + + orderByStudentCapacityAscending(): this { + this.query.orderBy("studentCapacity", "asc"); + return this; + } + + orderByStudentCapacityDescending(): this { + this.query.orderBy("studentCapacity", "desc"); + return this; + } + + orderByActiveAscending(): this { + this.query.orderBy("active", "asc"); + return this; + } + + orderByActiveDescending(): this { + this.query.orderBy("active", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minStudentCapacity(): this { + return this.minStudentCapacityAs("minOfStudentCapacity"); + } + + minStudentCapacityAs(retName: string): this { + this.query.aggregate("min", "studentCapacity", retName); + return this; + } + maxStudentCapacity(): this { + return this.maxStudentCapacityAs("maxOfStudentCapacity"); + } + + maxStudentCapacityAs(retName: string): this { + this.query.aggregate("max", "studentCapacity", retName); + return this; + } + sumStudentCapacity(): this { + return this.sumStudentCapacityAs("sumOfStudentCapacity"); + } + + sumStudentCapacityAs(retName: string): this { + this.query.aggregate("sum", "studentCapacity", retName); + return this; + } + avgStudentCapacity(): this { + return this.avgStudentCapacityAs("avgOfStudentCapacity"); + } + + avgStudentCapacityAs(retName: string): this { + this.query.aggregate("avg", "studentCapacity", retName); + return this; + } + standardDeviationStudentCapacity(): this { + return this.standardDeviationStudentCapacityAs("standardDeviationOfStudentCapacity"); + } + + standardDeviationStudentCapacityAs(retName: string): this { + this.query.aggregate("stddev", "studentCapacity", retName); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacity(): this { + return this.squareRootOfPopulationStandardDeviationStudentCapacityAs("squareRootOfPopulationStandardDeviationOfStudentCapacity"); + } + + squareRootOfPopulationStandardDeviationStudentCapacityAs(retName: string): this { + this.query.aggregate("stddev_pop", "studentCapacity", retName); + return this; + } + sampleVarianceStudentCapacity(): this { + return this.sampleVarianceStudentCapacityAs("sampleVarianceOfStudentCapacity"); + } + + sampleVarianceStudentCapacityAs(retName: string): this { + this.query.aggregate("var_samp", "studentCapacity", retName); + return this; + } + samplePopulationVarianceStudentCapacity(): this { + return this.samplePopulationVarianceStudentCapacityAs("samplePopulationVarianceOfStudentCapacity"); + } + + samplePopulationVarianceStudentCapacityAs(retName: string): this { + this.query.aggregate("var_pop", "studentCapacity", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } + + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform"); // In TS we don't alias group by yet natively + return this; + } + groupBySchoolType(): this { + this.query.groupBy("schoolType"); + return this; + } + + groupBySchoolTypeAs(retName: string): this { + this.query.groupBy("schoolType"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByAddress(): this { + this.query.groupBy("address"); + return this; + } + + groupByAddressAs(retName: string): this { + this.query.groupBy("address"); // In TS we don't alias group by yet natively + return this; + } + groupByEstablishedDate(): this { + this.query.groupBy("establishedDate"); + return this; + } + + groupByEstablishedDateAs(retName: string): this { + this.query.groupBy("establishedDate"); // In TS we don't alias group by yet natively + return this; + } + groupByStudentCapacity(): this { + this.query.groupBy("studentCapacity"); + return this; + } + + groupByStudentCapacityAs(retName: string): this { + this.query.groupBy("studentCapacity"); // In TS we don't alias group by yet natively + return this; + } + groupByActive(): this { + this.query.groupBy("active"); + return this; + } + + groupByActiveAs(retName: string): this { + this.query.groupBy("active"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByPlatformAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); + return this; + } + + facetBySchoolTypeAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "schoolType", request, includeAllFacets, + { kind: "facet", method: "facetBySchoolTypeAs", relation: "schoolType", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof School + ? row + : School.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof School + ? row + : School.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof School + ? entity + : School.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableSchoolRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): School { + this.ensureIntent(); + return new School(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d09b5f34a9b4b2aeee292bcfb05406959efef90 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts @@ -0,0 +1,1037 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { SchoolType } from '../models/SchoolType'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class SchoolTypeRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("SchoolType"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableSchoolTypeRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableSchoolTypeRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["platform", "id", "name", "code", "displayOrder", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectCode(): this { + this.query.select(["code"]); + return this; + } + + selectDisplayOrder(): this { + this.query.select(["displayOrder"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + + withPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolList", request.toQuery(), "id", "schoolType", true, + { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); + return this; + } + + haveSchools(): this { + return this.withSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + haveNoSchools(): this { + return this.withoutSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "schoolType", + }, + }, + }); + return this; + } + + withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "schoolType", + }, + }, + }); + return this; + } + + countSchools(): this { + return this.countSchoolsAs("countSchools"); + } + + countSchoolsAs(alias: string): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + this.countSchoolsWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; + return this; + } + + countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "relation-count", method: "countSchoolsWith", relation: "schoolList", alias }); + return this; + } + + minStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.minStudentCapacityOfSchoolsAs( + "minOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "minStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + maxStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.maxStudentCapacityOfSchoolsAs( + "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "maxStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sumStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sumStudentCapacityOfSchoolsAs( + "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sumStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + avgStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.avgStudentCapacityOfSchoolsAs( + "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "avgStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + standardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.standardDeviationStudentCapacityOfSchoolsAs( + "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "standardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sampleVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceStudentCapacityOfSchoolsAs( + "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + samplePopulationVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( + "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withCodeContaining(val: string): this { + this.filters.push({ "code": { "$contains": val } }); + return this; + } + + withCodeIs(val: string): this { + this.filters.push({ "code": { "$eq": val } }); + return this; + } + + withCodeIsNot(val: any): this { + this.filters.push({ "code": { "$ne": val } }); + return this; + } + + withCodeIn(...vals: any[]): this { + this.filters.push({ "code": { "$in": vals } }); + return this; + } + + withCodeNotIn(...vals: any[]): this { + this.filters.push({ "code": { "$notIn": vals } }); + return this; + } + + withCodeGreaterThan(val: any): this { + this.filters.push({ "code": { "$gt": val } }); + return this; + } + + withCodeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "code": { "$gte": val } }); + return this; + } + + withCodeLessThan(val: any): this { + this.filters.push({ "code": { "$lt": val } }); + return this; + } + + withCodeLessThanOrEqualTo(val: any): this { + this.filters.push({ "code": { "$lte": val } }); + return this; + } + + withCodeBetween(lower: any, upper: any): this { + this.filters.push({ "code": { "$between": [lower, upper] } }); + return this; + } + + withCodeIsKnown(): this { + this.filters.push({ "code": { "$isNull": false } }); + return this; + } + + withCodeIsUnknown(): this { + this.filters.push({ "code": { "$isNull": true } }); + return this; + } + withCodeNotContaining(val: string): this { + this.filters.push({ "code": { "$notContains": val } }); + return this; + } + + withCodeStartingWith(val: string): this { + this.filters.push({ "code": { "$startsWith": val } }); + return this; + } + + withCodeNotStartingWith(val: string): this { + this.filters.push({ "code": { "$notStartsWith": val } }); + return this; + } + + withCodeEndingWith(val: string): this { + this.filters.push({ "code": { "$endsWith": val } }); + return this; + } + + withCodeNotEndingWith(val: string): this { + this.filters.push({ "code": { "$notEndsWith": val } }); + return this; + } + + withCodeSoundingLike(val: string): this { + this.filters.push({ "code": { "$soundLike": val } }); + return this; + } + + withDisplayOrderIs(val: any): this { + this.filters.push({ "displayOrder": { "$eq": val } }); + return this; + } + + withDisplayOrderIsNot(val: any): this { + this.filters.push({ "displayOrder": { "$ne": val } }); + return this; + } + + withDisplayOrderIn(...vals: any[]): this { + this.filters.push({ "displayOrder": { "$in": vals } }); + return this; + } + + withDisplayOrderNotIn(...vals: any[]): this { + this.filters.push({ "displayOrder": { "$notIn": vals } }); + return this; + } + + withDisplayOrderGreaterThan(val: any): this { + this.filters.push({ "displayOrder": { "$gt": val } }); + return this; + } + + withDisplayOrderGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$gte": val } }); + return this; + } + + withDisplayOrderLessThan(val: any): this { + this.filters.push({ "displayOrder": { "$lt": val } }); + return this; + } + + withDisplayOrderLessThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$lte": val } }); + return this; + } + + withDisplayOrderBetween(lower: any, upper: any): this { + this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); + return this; + } + + withDisplayOrderIsKnown(): this { + this.filters.push({ "displayOrder": { "$isNull": false } }); + return this; + } + + withDisplayOrderIsUnknown(): this { + this.filters.push({ "displayOrder": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByCodeAscending(): this { + this.query.orderBy("code", "asc"); + return this; + } + + orderByCodeDescending(): this { + this.query.orderBy("code", "desc"); + return this; + } + + orderByDisplayOrderAscending(): this { + this.query.orderBy("displayOrder", "asc"); + return this; + } + + orderByDisplayOrderDescending(): this { + this.query.orderBy("displayOrder", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minDisplayOrder(): this { + return this.minDisplayOrderAs("minOfDisplayOrder"); + } + + minDisplayOrderAs(retName: string): this { + this.query.aggregate("min", "displayOrder", retName); + return this; + } + maxDisplayOrder(): this { + return this.maxDisplayOrderAs("maxOfDisplayOrder"); + } + + maxDisplayOrderAs(retName: string): this { + this.query.aggregate("max", "displayOrder", retName); + return this; + } + sumDisplayOrder(): this { + return this.sumDisplayOrderAs("sumOfDisplayOrder"); + } + + sumDisplayOrderAs(retName: string): this { + this.query.aggregate("sum", "displayOrder", retName); + return this; + } + avgDisplayOrder(): this { + return this.avgDisplayOrderAs("avgOfDisplayOrder"); + } + + avgDisplayOrderAs(retName: string): this { + this.query.aggregate("avg", "displayOrder", retName); + return this; + } + standardDeviationDisplayOrder(): this { + return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder"); + } + + standardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev", "displayOrder", retName); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrder(): this { + return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder"); + } + + squareRootOfPopulationStandardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev_pop", "displayOrder", retName); + return this; + } + sampleVarianceDisplayOrder(): this { + return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder"); + } + + sampleVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_samp", "displayOrder", retName); + return this; + } + samplePopulationVarianceDisplayOrder(): this { + return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder"); + } + + samplePopulationVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_pop", "displayOrder", retName); + return this; + } + + // --- Group By --- + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } + + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform"); // In TS we don't alias group by yet natively + return this; + } + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByCode(): this { + this.query.groupBy("code"); + return this; + } + + groupByCodeAs(retName: string): this { + this.query.groupBy("code"); // In TS we don't alias group by yet natively + return this; + } + groupByDisplayOrder(): this { + this.query.groupBy("displayOrder"); + return this; + } + + groupByDisplayOrderAs(retName: string): this { + this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByPlatformAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof SchoolType + ? row + : SchoolType.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof SchoolType + ? row + : SchoolType.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof SchoolType + ? entity + : SchoolType.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableSchoolTypeRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): SchoolType { + this.ensureIntent(); + return new SchoolType(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/runtime-module.ts b/source/teaql-ts/examples/facet-trace/lib/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e03a4e5cb463203c4cf7323fbb77a4e98d2b952 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/runtime-module.ts @@ -0,0 +1,150 @@ +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-schemas"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Platform": Object.freeze({ + entityType: "Platform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "base_url": Object.freeze({ canonicalName: "base_url", wireName: "baseUrl", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "SchoolType": Object.freeze({ + entityType: "SchoolType", + profile: "camelCase" as const, + fields: Object.freeze({ + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "code": Object.freeze({ canonicalName: "code", wireName: "code", aliases: Object.freeze([] as string[]) }), + "display_order": Object.freeze({ canonicalName: "display_order", wireName: "displayOrder", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "School": Object.freeze({ + entityType: "School", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "school_type": Object.freeze({ canonicalName: "school_type", wireName: "schoolType", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "address": Object.freeze({ canonicalName: "address", wireName: "address", aliases: Object.freeze([] as string[]) }), + "established_date": Object.freeze({ canonicalName: "established_date", wireName: "establishedDate", aliases: Object.freeze([] as string[]) }), + "student_capacity": Object.freeze({ canonicalName: "student_capacity", wireName: "studentCapacity", aliases: Object.freeze([] as string[]) }), + "active": Object.freeze({ canonicalName: "active", wireName: "active", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Platform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["base_url"] === undefined) || mutation.payload["base_url"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("base_url") }); + if (mutation.payload["base_url"] != null && [...String(mutation.payload["base_url"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("base_url"), inputValue: mutation.payload["base_url"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "SchoolType": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["code"] === undefined) || mutation.payload["code"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("code") }); + if (mutation.payload["code"] != null && [...String(mutation.payload["code"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("code"), inputValue: mutation.payload["code"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["display_order"] === undefined) || mutation.payload["display_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("display_order") }); + + + }, + }, + "School": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + if ((mutation.action === "Create" && mutation.payload["school_type"] === undefined) || mutation.payload["school_type"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("school_type") }); + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["address"] === undefined) || mutation.payload["address"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("address") }); + if (mutation.payload["address"] != null && [...String(mutation.payload["address"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("address"), inputValue: mutation.payload["address"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["established_date"] === undefined) || mutation.payload["established_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("established_date") }); + + if ((mutation.action === "Create" && mutation.payload["student_capacity"] === undefined) || mutation.payload["student_capacity"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("student_capacity") }); + + if ((mutation.action === "Create" && mutation.payload["active"] === undefined) || mutation.payload["active"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("active") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Campus Learning Platform", "baseUrl": "https://campus.example.com", "createTime": "createTime()", "updateTime": "updateTime()" } }, + constants: [ + { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary", "code": "PRIMARY", "displayOrder": 1 } }, + { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": 2 } } + ] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/teaql-node-sql.ts b/source/teaql-ts/examples/facet-trace/lib/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..0db809a1f8d42c9bd27a9aa417b6bd1e8ff22274 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/teaql-node-sql.ts @@ -0,0 +1,22 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: ["name"], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "baseUrl": { columnName: "base_url", modelName: "base_url", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"schoolTypeList": { targetEntity: "SchoolType", localKey: "id", foreignKey: "platform", many: true }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "platform", many: true }} +}, +"SchoolType": { + table: "school_type_data", + auditMaskFields: [], + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} +}, +"School": { + table: "school_data", + auditMaskFields: ["name"], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/facet-trace/lib/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/teaql-schemas.ts b/source/teaql-ts/examples/facet-trace/lib/src/teaql-schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..0db809a1f8d42c9bd27a9aa417b6bd1e8ff22274 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/teaql-schemas.ts @@ -0,0 +1,22 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: ["name"], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "baseUrl": { columnName: "base_url", modelName: "base_url", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"schoolTypeList": { targetEntity: "SchoolType", localKey: "id", foreignKey: "platform", many: true }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "platform", many: true }} +}, +"SchoolType": { + table: "school_type_data", + auditMaskFields: [], + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} +}, +"School": { + table: "school_data", + auditMaskFields: ["name"], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/teaql-ts.ts b/source/teaql-ts/examples/facet-trace/lib/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..b54a29ac3c12fb072cf4c292e22bb2e644b56319 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/src/teaql-ts.ts @@ -0,0 +1,308 @@ +import { + CheckException, EntityChecker, RuntimeModule, + SelectQuery as RuntimeSelectQuery, UserContext, + executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + + constructor(private storagePath?: string) { + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + Object.assign(this.checkers, module.checkers); + return this; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + const graph = new GraphMutationSession(intent); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + try { + this.graphSaveActive = true; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.userContext.insertResource("fixTime", new Date()); + this.userContext.beginFixEvidence(); + fixEvidenceStarted = true; + this.userContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + const result = await work(graph); + this.userContext.ensureMutationPolicyGraphComplete(); + this.persist(); + for (const action of this.graphCommitActions) action(); + return result; + } catch (error) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) action(); + throw error; + } finally { + this.graphSaveActive = false; + this.graphCommitActions = []; + this.graphRollbackActions = []; + if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); + this.userContext.removeResource("fixTime"); + if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + mutation = this.checkAndFixMutation(mutation); + this.userContext.recordMutationPolicyPreflight(mutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + if (mutation instanceof MutationRequest) mutation = mutation.mutation; + if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + const checker = this.checkers[String(mutation.entity)]; + if (!checker) return mutation; + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + this.userContext.translateCheckResults(results); + if (results.length) throw new CheckException(results); + return mutation; + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + mutation = this.checkAndFixMutation(mutation); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + this.mutationGovernanceEvents.push(mutationGovernance); + const table = this.data[mutation.entity] ||= {}; + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + this.nextIds[mutation.entity] = Number(id) + 1; + const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; + } + if (mutation.action === "Update") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + } + if (mutation.action === "Delete") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); + if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); + const relatedRows = (await this.executeQuery(relation.query)).filter( + (row: any) => localValues.has(row[relation.foreignKey || "id"])); + for (const row of rows) { + const matches = relatedRows.filter( + (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/teaql-i18n.json b/source/teaql-ts/examples/facet-trace/lib/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..21b3f9b8ad1eea6f6f4d16aedf6863de4c280cf3 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/teaql-i18n.json @@ -0,0 +1,122 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.platform.name": "Name", + "property.platform.createTime": "Create Time", + "property.platform.updateTime": "Update Time", + "property.school.platform": "Platform", + "property.school.id": "Id", + "property.schoolType.version": "Version", + "property.school.establishedDate": "Established Date", + "property.schoolType.code": "Code", + "property.school.studentCapacity": "Student Capacity", + "property.school.active": "Active", + "property.school.schoolType": "School Type", + "entity.platform": "Platform", + "property.platform.id": "Id", + "property.schoolType.displayOrder": "Display Order", + "property.schoolType.id": "Id", + "entity.school": "School", + "property.school.name": "Name", + "property.school.createTime": "Create Time", + "property.school.updateTime": "Update Time", + "entity.schoolType": "School Type", + "property.platform.baseUrl": "Base Url", + "property.platform.version": "Version", + "property.schoolType.platform": "Platform", + "property.school.version": "Version", + "property.school.address": "Address", + "property.schoolType.name": "Name" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/tsconfig.json b/source/teaql-ts/examples/facet-trace/lib/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/model.xml b/source/teaql-ts/examples/facet-trace/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..f114b401fd5cfe12deb530c6d91ee56f0c976a35 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/model.xml @@ -0,0 +1,41 @@ + + + + + + <_value id="1001" name="Primary" code="PRIMARY" display_order="1"/> + <_value id="1002" name="Secondary" code="SECONDARY" display_order="2"/> + + + + diff --git a/source/teaql-ts/examples/facet-trace/package-lock.json b/source/teaql-ts/examples/facet-trace/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..6409164a882a292dd0343d2b27ba84ef81e4d2a5 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/package-lock.json @@ -0,0 +1,623 @@ +{ + "name": "teaql-generated-facet-trace-example", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "teaql-generated-facet-trace-example", + "dependencies": { + "better-sqlite3": "^12.10.0", + "teaql-ts": "file:../.." + }, + "devDependencies": { + "@types/better-sqlite3": "^7.6.12", + "@types/node": "^22.0.0", + "typescript": "5.4.5" + } + }, + "../..": { + "name": "@teaql/teaql", + "version": "0.3.0", + "license": "Apache-2.0", + "dependencies": { + "node-fetch": "^2.7.0" + }, + "devDependencies": { + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "@types/better-sqlite3": "^7.6.12", + "@types/jest": "^29.5.0", + "@types/node-fetch": "^2.6.13", + "@types/pg": "^8.11.0", + "better-sqlite3": "^12.10.0", + "esbuild": "^0.28.2", + "jest": "^29.5.0", + "jest-util": "^29.7.0", + "mysql2": "^3.11.0", + "peggy": "^5.1.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0", + "ts-jest": "^29.1.0", + "typescript": "5.4.5" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "better-sqlite3": "^12.10.0", + "expo-sqlite": "*", + "mysql2": "^3.11.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/api-logs": { + "optional": true + }, + "@opentelemetry/context-async-hooks": { + "optional": true + }, + "@opentelemetry/core": { + "optional": true + }, + "@opentelemetry/exporter-logs-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-metrics-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-http": { + "optional": true + }, + "@opentelemetry/resources": { + "optional": true + }, + "@opentelemetry/sdk-logs": { + "optional": true + }, + "@opentelemetry/sdk-metrics": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "@sqlite.org/sqlite-wasm": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "expo-sqlite": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-query-stream": { + "optional": true + } + } + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "12.11.1", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", + "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/node-abi": { + "version": "3.96.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.96.0.tgz", + "integrity": "sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/teaql-ts": { + "resolved": "../..", + "link": true + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/source/teaql-ts/examples/facet-trace/package.json b/source/teaql-ts/examples/facet-trace/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4dc44eeb8da5cc671c1fee80683ceb2542a65192 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/package.json @@ -0,0 +1,7 @@ +{ + "name": "teaql-generated-facet-trace-example", + "private": true, + "scripts": {"build": "tsc --project tsconfig.json", "start": "node dist/consumer.js"}, + "dependencies": {"teaql-ts": "file:../..", "better-sqlite3": "^12.10.0"}, + "devDependencies": {"typescript": "5.4.5", "@types/node": "^22.0.0", "@types/better-sqlite3": "^7.6.12"} +} diff --git a/source/teaql-ts/examples/facet-trace/tsconfig.json b/source/teaql-ts/examples/facet-trace/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..ce665b33596fc48f475e7ee666a2a0e997381f80 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/tsconfig.json @@ -0,0 +1,3 @@ +{"compilerOptions":{"target":"ES2022","module":"commonjs","strict":true, +"esModuleInterop":true,"skipLibCheck":true,"outDir":"dist","types":["node"]}, +"include":["consumer.ts","lib/src/**/*.ts"]} diff --git a/source/teaql-ts/examples/facet-trace/verify.sh b/source/teaql-ts/examples/facet-trace/verify.sh new file mode 100644 index 0000000000000000000000000000000000000000..6371abe004b861d13afe3a37687491f73df70118 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/verify.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail +example="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo="$(cd "$example/../.." && pwd)" +facet_run_directory="$(mktemp -d -t teaql-ts-facet.XXXXXX)" +export TEAQL_FACET_TRACE_DB="$facet_run_directory/school.db" +unset TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS +fingerprint() { + (cd "$example/lib" && rg --files -g '!**/node_modules/**' -g '!**/dist/**' | LC_ALL=C sort | xargs -d '\n' sha256sum) +} +fingerprint > "$facet_run_directory/library-before.sha256" +# Always rebuild repository runtime outputs before exercising a file: dependency. +(cd "$repo" && npm run build) > "$facet_run_directory/runtime-build.log" 2>&1 +(cd "$example" && npm_config_package_lock=false npm install --prefer-offline --no-audit --no-fund && npm run build) > "$facet_run_directory/compile.log" 2>&1 +(cd "$example" && node -e 'const fs=require("node:fs"), path=require("node:path"); + const actual=fs.realpathSync(require.resolve("teaql-ts")); + if(actual!==path.join(fs.realpathSync("../.."),"dist/index.js")) throw Error("runtime must resolve repository dist"); + console.log(actual);') > "$facet_run_directory/resolution.log" +for round in first second; do + log="$facet_run_directory/$round.log" + if ! (cd "$example" && timeout --kill-after=5s 60s npm start) > "$log" 2>&1; then + tail -50 "$log" >&2 + echo "FAIL: Facet $round; retained evidence $facet_run_directory" >&2 + exit 1 + fi + [[ "$(rg -c '^FACET_OBSERVED ' "$log")" == 48 ]] + rg -Fq 'TypeScript generated Facet acceptance passed: 48 scenarios' "$log" + echo "PASS: Facet $round, 48 scenarios; same database $TEAQL_FACET_TRACE_DB; log $log" +done +fingerprint > "$facet_run_directory/library-after.sha256" +cmp "$facet_run_directory/library-before.sha256" "$facet_run_directory/library-after.sha256" +echo "PASS: generated Facet library unchanged; retained evidence $facet_run_directory" diff --git a/source/teaql-ts/examples/object-storage/README.md b/source/teaql-ts/examples/object-storage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d05aa31fa4134789f63a00a50262ee787d463ab6 --- /dev/null +++ b/source/teaql-ts/examples/object-storage/README.md @@ -0,0 +1,49 @@ +# Context owned object storage + +Tracking: [TypeScript #53](https://github.com/teaql/teaql-ts/issues/53), +[shared contract #122](https://github.com/teaql/teaql-conformance/issues/122). + +Core exports contain portable typed values and asynchronous byte-stream contracts. +The optional server-only `@teaql/teaql/object-storage/s3` entry requires the pinned +`@aws-sdk/client-s3` and `@aws-sdk/s3-request-presigner` peers (3.1151.0), Node 20+, +and filesystem access. It is not imported by the browser core entry point. +SDK credentials, endpoints and buckets are configured at trusted startup. + +```typescript +import {UserContext,ObjectKey,ObjectPutOptions} from '@teaql/teaql'; +import {S3ObjectStorage} from '@teaql/teaql/object-storage/s3'; + +const provider = new S3ObjectStorage(sdkClient, 'attachments'); +const storage = new UserContext().withObjectStorage(provider) + .objectStorage('store payment receipt attachment'); +const key = new ObjectKey('receipts/opaque-reference.pdf'); +await storage.put(key, source, new ObjectPutOptions(contentLength, 'create_only')); +const link = await storage.getReadUrl(key); +// Return link.url to an authorized caller; never log it. +const response = await storage.get(key); +try { for await (const block of response.stream) { /* consume bytes */ } } +finally { await response.close(); } +``` + +Upload iterators are finalized on every exit. The adapter stages to a private +temporary file with bounded buffers and exact length checks, capped at 5 GiB. +It reopens the staged body for at most three transport/service retry attempts; +conditional PUT remains atomic. Downloads stream and must be consumed or closed. +`getBytes(key, maximumBytes)` requires an explicit memory ceiling. Replacement +is explicit; permissions and outages never become false absence. + +Keys are durable; five-minute read URLs are reusable bearer links and can expire +early with credentials/policy. Issuing a URL does not check existence or grant +domain permission. Core inspection/diagnostic events exclude keys, metadata, +body, credentials, URLs and SDK messages. The observer/telemetry resource is +installed on Context (`objectStorageObserver` / `runtimeTelemetry`). S3 writes +remain independent of SQL transactions. + +After installing this checkout's dependencies, set `TEAQL_S3_ENDPOINT`, +`TEAQL_S3_BUCKET`, `TEAQL_S3_ACCESS_KEY`, `TEAQL_S3_SECRET_KEY` to a dedicated +test service and run `bash examples/object-storage/verify.sh` twice. The example +uses a fresh local build, creates its fixture bucket if missing and removes +only its unique keys. The production provider never creates buckets. The gate +qualifies the dedicated fixture; other compatible services require their own +tests. Multipart, list/copy/range, signed upload and browser credentials are +outside this first server adapter. diff --git a/source/teaql-ts/examples/object-storage/main.cjs b/source/teaql-ts/examples/object-storage/main.cjs new file mode 100644 index 0000000000000000000000000000000000000000..639400fa7adfe966ba5673d1cd7ee4927244b2c8 --- /dev/null +++ b/source/teaql-ts/examples/object-storage/main.cjs @@ -0,0 +1,34 @@ +const assert=require('node:assert/strict'); +const crypto=require('node:crypto'); +const {S3Client,HeadBucketCommand,CreateBucketCommand}=require('@aws-sdk/client-s3'); +const {UserContext,ObjectKey,ObjectPutOptions,ObjectReadUrlOptions,StorageError}=require('../../dist'); +const {S3ObjectStorage}=require('../../dist/object-storage/s3'); + +async function expect(code,work){await assert.rejects(work,error=>error instanceof StorageError&&error.code===code);} +async function main(){ + const bucket=process.env.TEAQL_S3_BUCKET; + const client=new S3Client({endpoint:process.env.TEAQL_S3_ENDPOINT,forcePathStyle:true,region:'us-east-1',maxAttempts:1,credentials:{accessKeyId:process.env.TEAQL_S3_ACCESS_KEY,secretAccessKey:process.env.TEAQL_S3_SECRET_KEY}}); + try{await client.send(new HeadBucketCommand({Bucket:bucket}));}catch(error){if(error.$metadata?.httpStatusCode!==404)throw new Error('test bucket setup failed');await client.send(new CreateBucketCommand({Bucket:bucket}));} + const provider=new S3ObjectStorage(client,bucket),events=[]; + const context=new UserContext().insertResource('traceId','storage-example').withObjectStorage(provider).withObjectStorageObserver(event=>events.push(event));const storage=context.objectStorage('verify binary object storage'); + const prefix=`typescript-example/${crypto.randomUUID()}/`,key=new ObjectKey(prefix+'收据 +% binary'),empty=new ObjectKey(prefix+'empty'),race=new ObjectKey(prefix+'race'); + const data=Uint8Array.from({length:256*1024},(_,i)=>i%251); + try{ + assert.equal(await storage.exists(key),false);await expect('NotFound',()=>storage.get(key)); + await storage.putBytes(key,data,new ObjectPutOptions(data.length,'create_only','application/octet-stream',{example:'binary'})); + const metadata=await storage.head(key);assert.equal(metadata.size,data.length);assert.equal(metadata.customMetadata.example,'binary');assert(metadata.etag); + assert.deepEqual(await storage.getBytes(key,data.length),data);await expect('Conflict',()=>storage.putBytes(key,new Uint8Array(),new ObjectPutOptions(0,'create_only')));await expect('TooLarge',()=>storage.getBytes(key,1)); + const url=await storage.getReadUrl(key,new ObjectReadUrlOptions(300,'attachment','receipt.bin'));const response=await fetch(url.url);assert.equal(response.status,200);assert.equal(response.headers.get('content-disposition'),'attachment; filename="receipt.bin"');assert.deepEqual(new Uint8Array(await response.arrayBuffer()),data); + const expired=await storage.getReadUrl(key,new ObjectReadUrlOptions(1));await new Promise(resolve=>setTimeout(resolve,2200));const denied=await fetch(expired.url);assert.equal(denied.status,403);await denied.arrayBuffer(); + await storage.putBytes(empty,new Uint8Array(),new ObjectPutOptions(0,'create_only'));assert.equal((await storage.getBytes(empty,0)).length,0); + await expect('InvalidInput',()=>storage.putBytes(key,new Uint8Array([1,2]),new ObjectPutOptions(1,'replace')));assert.deepEqual(await storage.getBytes(key,data.length),data); + await storage.putBytes(key,new Uint8Array([1,2,3]),new ObjectPutOptions(3,'replace'));assert.deepEqual(await storage.getBytes(key,3),new Uint8Array([1,2,3])); + const other=new UserContext().insertResource('traceId','storage-other').withObjectStorage(provider).withObjectStorageObserver(event=>events.push(event)).objectStorage('verify atomic create'); + const outcomes=await Promise.allSettled([storage,other].map(api=>api.putBytes(race,new Uint8Array([1]),new ObjectPutOptions(1,'create_only'))));assert.equal(outcomes.filter(outcome=>outcome.status==='fulfilled').length,1);assert.equal(outcomes.find(outcome=>outcome.status==='rejected').reason.code,'Conflict'); + const missing=new UserContext().withObjectStorage(new S3ObjectStorage(client,'missing-'+crypto.randomUUID())).objectStorage('verify missing bucket');await expect('Unavailable',()=>missing.exists(key)); + for(const item of [key,empty,race]){await storage.delete(item);await storage.delete(item);assert.equal(await storage.exists(item),false);} + assert.deepEqual(new Set(events.map(e=>e.traceId)),new Set(['storage-example','storage-other']));assert(!JSON.stringify(events).includes(prefix)); + console.log('PASS TypeScript S3: binary, empty, metadata, URL download/expiry, atomic create, replace, bounded reads, missing bucket, repeated delete'); + }finally{for(const item of [key,empty,race])await storage.delete(item);provider.close();} +} +main().catch(error=>{console.error(error instanceof StorageError?error.message:'Object storage example failed');process.exitCode=1;}); diff --git a/source/teaql-ts/examples/object-storage/verify.sh b/source/teaql-ts/examples/object-storage/verify.sh new file mode 100644 index 0000000000000000000000000000000000000000..e9178d1bc6a2d6026e06d5474ae3d46ffd4b0b48 --- /dev/null +++ b/source/teaql-ts/examples/object-storage/verify.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +: "${TEAQL_S3_ENDPOINT:?dedicated local test endpoint required}" +: "${TEAQL_S3_BUCKET:?dedicated test bucket required}" +: "${TEAQL_S3_ACCESS_KEY:?test access key required}" +: "${TEAQL_S3_SECRET_KEY:?test secret key required}" +cd "$repo" +npm run build +npm test -- --runInBand tests/object-storage.test.ts +node examples/object-storage/main.cjs diff --git a/source/teaql-ts/examples/order-management/.gitignore b/source/teaql-ts/examples/order-management/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9ede4eeb483a8fc220e6d4f007974be4a0996290 --- /dev/null +++ b/source/teaql-ts/examples/order-management/.gitignore @@ -0,0 +1,4 @@ +.local/ +**/node_modules/ +**/dist/ + diff --git a/source/teaql-ts/examples/order-management/README.md b/source/teaql-ts/examples/order-management/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a8619e99f2bbbb0ddfd50299f9d5d271868299fa --- /dev/null +++ b/source/teaql-ts/examples/order-management/README.md @@ -0,0 +1,61 @@ +# Order Management — TypeScript + SQLite + +Use Node.js 22. No database server, fixture DB, model input, or generator installation is needed. + +```bash +cd examples/order-management +npm install +npm start +``` + +The first run creates `../.local/order.db`, ensures schema, seeds through generated entities, performs a governed query, and saves an audited preset. The second run demonstrates idempotency. + +Read `typescript-app-console/app.ts` first (handwritten), then `typescript-node-lib-core/src/generated/Q.ts`, `requests/CustomerOrderRequest.ts`, and `models/CustomerOrder.ts` (generated). `purpose(...)` returns the executable request; runtime dependencies come only from the trusted `UserContext`. + +## Verify the first result + +Expect `WEB-2026-001`, `2026-08-12`, and `129.95`. The first run reports four audited mutations and SQL trace entries; the second reports zero mutations. + +## Customize it + +Change `withOrderNumberContaining`, ordering, or a generated relation selection in `app.ts`, then run `npm run build`. Keep trusted context and application policy in `typescript-app-console`; regenerate `typescript-node-lib-core`. The workspace resolves the current TeaQL SQL runtime normally—there is no copied `dist` cache. The shared model is not needed at runtime. +### Materialized-list hard limit + +`executeForList` protects the service by applying a default hard limit of 10,000 rows. A requested page size above that ceiling fails explicitly. Trusted application code can call `hardLimit(...)` to override the outer-query ceiling. **Caution:** most applications should not override it; do so only for a reviewed, exceptional requirement. This setting does not describe streaming execution. + +### Streaming large root queries + +`executeForStream(ctx, chunkSize)` is an `AsyncIterable` of generated entities backed by the SQL driver's cursor: + +```typescript +for await (const order of request.comment('export orders').purpose('reviewed export').executeForStream(ctx, 500)) { + await writeOrder(order); +} +``` + +Breaking the loop destroys/releases the cursor. **Caution:** normally keep the default 1,000. The SQL runtime enhances selected relations a batch at a time. The ordinary TFP client explicitly rejects streaming until a dedicated protocol exists. + +### Optional continuous browsing optimization + +For a browse-only screen ordered by the unique `id`, trusted application code can opt in: + +```typescript +const orders = await Q.customerOrders() + .orderByIdDescending() + .offset(page * pageSize) + .limit(pageSize) + .optimizeForContinuousPageFetchWith('recent-orders', 60) + .purpose('browse recent orders') + .comment('order browser') + .executeForList(ctx); +``` + +The runtime keeps a bounded, expiring cursor in `UserContext`. A matching next page +transparently uses an `id` seek instead of a deep offset; cache misses and unsupported +query shapes retain offset semantics. The plan and cursor ID remain observable. + +**Caution:** this is an explicitly approximate optimization for continuous browsing, not +business logic, reconciliation, export, or a stable snapshot. Browse screens usually do +not need an exact count. Both the option and runtime scope are non-enumerable local state; +the TFP client also rejects malicious continuous-page fields, so federation cannot enable +or modify the optimization. diff --git a/source/teaql-ts/examples/order-management/package-lock.json b/source/teaql-ts/examples/order-management/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..83caacecf28a675e2d7f7581982aeb79d04c808a --- /dev/null +++ b/source/teaql-ts/examples/order-management/package-lock.json @@ -0,0 +1,836 @@ +{ + "name": "teaql-order-management-example", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "teaql-order-management-example", + "workspaces": [ + "typescript-node-lib-core", + "typescript-app-console" + ] + }, + "../..": { + "name": "@teaql/teaql", + "version": "0.3.1", + "license": "Apache-2.0", + "dependencies": { + "node-fetch": "^2.7.0" + }, + "devDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "@types/better-sqlite3": "^7.6.12", + "@types/jest": "^29.5.0", + "@types/node-fetch": "^2.6.13", + "@types/pg": "^8.11.0", + "better-sqlite3": "^12.10.0", + "esbuild": "^0.28.2", + "jest": "^29.5.0", + "jest-util": "^29.7.0", + "mysql2": "^3.11.0", + "peggy": "^5.1.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0", + "ts-jest": "^29.1.0", + "typescript": "5.4.5" + }, + "peerDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "better-sqlite3": "^12.10.0", + "expo-sqlite": "*", + "mysql2": "^3.11.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/s3-request-presigner": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/api-logs": { + "optional": true + }, + "@opentelemetry/context-async-hooks": { + "optional": true + }, + "@opentelemetry/core": { + "optional": true + }, + "@opentelemetry/exporter-logs-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-metrics-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-http": { + "optional": true + }, + "@opentelemetry/otlp-transformer": { + "optional": true + }, + "@opentelemetry/resources": { + "optional": true + }, + "@opentelemetry/sdk-logs": { + "optional": true + }, + "@opentelemetry/sdk-metrics": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "@sqlite.org/sqlite-wasm": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "expo-sqlite": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-query-stream": { + "optional": true + } + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz", + "integrity": "sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ==", + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "license": "MIT" + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "22.20.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz", + "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "11.10.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz", + "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "license": "MIT" + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "license": "ISC" + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/node-abi": { + "version": "3.94.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz", + "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/order-management-example": { + "resolved": "typescript-app-console", + "link": true + }, + "node_modules/order-management-service-lib": { + "resolved": "typescript-node-lib-core", + "link": true + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "typescript-app-console": { + "name": "order-management-example", + "dependencies": { + "better-sqlite3": "^11.7.0", + "order-management-service-lib": "file:../typescript-node-lib-core", + "teaql-ts": "file:../../..", + "ts-node": "^10.9.2", + "typescript": "^5.0.0" + }, + "devDependencies": { + "@types/node": "^22.0.0" + } + }, + "typescript-app-console/node_modules/teaql-ts": { + "resolved": "../..", + "link": true + }, + "typescript-node-lib-core": { + "name": "order-management-service-lib", + "version": "1.0.0", + "dependencies": { + "better-sqlite3": "^11.7.0", + "teaql-ts": "file:../../.." + }, + "devDependencies": { + "@types/better-sqlite3": "^7.6.12", + "@types/node": "^22.0.0", + "ts-node": "^10.9.2", + "typescript": "^5.0.0" + } + }, + "typescript-node-lib-core/node_modules/teaql-ts": { + "resolved": "../..", + "link": true + } + } +} diff --git a/source/teaql-ts/examples/order-management/package.json b/source/teaql-ts/examples/order-management/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8de48ae3d4ea24e1621dd00759d769c4bdc631d3 --- /dev/null +++ b/source/teaql-ts/examples/order-management/package.json @@ -0,0 +1,12 @@ +{ + "name": "teaql-order-management-example", + "private": true, + "workspaces": [ + "typescript-node-lib-core", + "typescript-app-console" + ], + "scripts": { + "build": "npm run build --workspace order-management-example", + "start": "npm start --workspace order-management-example" + } +} diff --git a/source/teaql-ts/examples/order-management/typescript-app-console/app.ts b/source/teaql-ts/examples/order-management/typescript-app-console/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..0cd3600cc75d9289f6fdae378dc9558014ebe917 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-app-console/app.ts @@ -0,0 +1,90 @@ +import fs from "node:fs"; +import path from "node:path"; +import { Q } from "order-management-service-lib/src/generated/Q"; +import { CommercePlatform } from "order-management-service-lib/src/generated/models/CommercePlatform"; +import { Customer } from "order-management-service-lib/src/generated/models/Customer"; +import { CustomerOrder } from "order-management-service-lib/src/generated/models/CustomerOrder"; +import { OrderSearchPreset } from "order-management-service-lib/src/generated/models/OrderSearchPreset"; +import { UserContext } from "teaql-ts"; +import { SQLiteTeaQLClient } from "order-management-service-lib/src/teaql-node-sqlite"; + +async function main(): Promise { + const root = path.resolve(__dirname, ".."); + const database = path.join(root, ".local", "order.db"); + if (!fs.existsSync(database)) { + console.log(`[database] ${database} was not found; TeaQL will create it`); + } + fs.mkdirSync(path.dirname(database), { recursive: true }); + const client = new SQLiteTeaQLClient(database); + client.setAuditSink(event => { + console.log(`[audit] ${event.action} ${event.entity}#${event.id}; reason=${JSON.stringify(event.reason)}`); + }); + const ctx = new UserContext().insertResource("dataService", client); + await ctx.ensureSchema(); + console.log("[schema] ensured 7 generated entity tables"); + + const platforms = await Q.commercePlatforms() + .withNameIs("Northwind Demo") + .comment("Check whether deterministic quick-start data exists") + .purpose("Initialize the local order-management example") + .executeForList(ctx); + let platformId: string; + if (platforms.data.length === 0) { + const platform = new CommercePlatform().updateName("Northwind Demo"); + await platform.auditAs("Create quick-start commerce platform").save(ctx); + platformId = platform.id!; + } else platformId = String(platforms.data[0].id); + + const seeded = await Q.customerOrders() + .withOrderNumberIs("WEB-2026-001") + .comment("Check whether the deterministic order exists") + .purpose("Initialize the local order-management example") + .executeForList(ctx); + if (seeded.data.length === 0) { + const customer = new Customer() + .updateName("Acme Retail") + .updateEmail("masked-in-quick-start") + .updateCommercePlatform(platformId); + await customer.auditAs("Create masked quick-start customer").save(ctx); + const order = new CustomerOrder() + .updateOrderNumber("WEB-2026-001") + .updateOrderDate("2026-08-12") + .updateTotalAmount(129.95) + .updateStatusToPending() + .updateCustomer(customer.id) + .updateCommercePlatform(platformId); + await order.auditAs("Create deterministic quick-start order").save(ctx); + console.log("[seed] inserted deterministic customer and order"); + } else console.log("[seed] deterministic data already exists; no duplicate rows added"); + + const result = await Q.customerOrders() + .withOrderNumberContaining("WEB-") + .orderByIdAscending() + .comment("List WEB orders for the terminal quick start") + .purpose("Show the operator a deterministic order list") + .executeForList(ctx); + console.log(`[query] matched ${result.data.length} order(s)`); + for (const order of result.data) { + console.log(` ${order.orderNumber} ${order.orderDate} ${order.totalAmount}`); + } + + const presets = await Q.orderSearchPresets() + .withRequestIdIs("quick-start-pending-orders") + .comment("Check idempotent quick-start preset") + .purpose("Persist the operator's reusable search") + .executeForList(ctx); + if (presets.data.length === 0) { + const preset = new OrderSearchPreset() + .updateName("Pending web orders") + .updateFilterJson('{"order_number":"WEB-"}') + .updateRequestId("quick-start-pending-orders") + .updateOwnerUserId("quick-start-user") + .updateCommercePlatform(platformId); + await preset.auditAs("Save idempotent quick-start search preset").save(ctx); + console.log(`[mutation] saved preset #${preset.id}`); + } else console.log(`[mutation] preset #${presets.data[0].id} already exists`); + console.log(`[trace] ${client.sqlTrace.length} SQL statements captured; ${client.auditTrace.length} mutations audited`); + await client.close(); +} + +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/order-management/typescript-app-console/package.json b/source/teaql-ts/examples/order-management/typescript-app-console/package.json new file mode 100644 index 0000000000000000000000000000000000000000..42c3113b2955e2142e36954d4d03d9894b56caf5 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-app-console/package.json @@ -0,0 +1,18 @@ +{ + "name": "order-management-example", + "private": true, + "scripts": { + "start": "ts-node app.ts", + "build": "tsc --noEmit" + }, + "dependencies": { + "better-sqlite3": "^11.7.0", + "order-management-service-lib": "file:../typescript-node-lib-core", + "teaql-ts": "file:../../..", + "ts-node": "^10.9.2", + "typescript": "^5.0.0" + }, + "devDependencies": { + "@types/node": "^22.0.0" + } +} diff --git a/source/teaql-ts/examples/order-management/typescript-app-console/tsconfig.json b/source/teaql-ts/examples/order-management/typescript-app-console/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..7e42f053c6e07d8a1ff1b1769547c30f4f35d543 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-app-console/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "moduleResolution": "node", + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true + } +} + diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/package.json b/source/teaql-ts/examples/order-management/typescript-node-lib-core/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3c3b6813698d0e4b6c7383b6b4567057dfa8d0f1 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/package.json @@ -0,0 +1,17 @@ +{ + "name": "order-management-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "file:../../..", + "better-sqlite3": "^11.7.0"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/Q.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6d13901bbbf784ca6a47eb2926f67cac9e7e3ac --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/Q.ts @@ -0,0 +1,32 @@ +import { TeaQLClient } from '../teaql-ts'; +import { CommercePlatformRequest } from './requests/CommercePlatformRequest'; +import { CustomerRequest } from './requests/CustomerRequest'; +import { OrderStatusRequest } from './requests/OrderStatusRequest'; +import { CustomerOrderRequest } from './requests/CustomerOrderRequest'; +import { ProductRequest } from './requests/ProductRequest'; +import { OrderLineRequest } from './requests/OrderLineRequest'; +import { OrderSearchPresetRequest } from './requests/OrderSearchPresetRequest'; + +export class Q { + static commercePlatforms(): CommercePlatformRequest { + return new CommercePlatformRequest(); + } + static customers(): CustomerRequest { + return new CustomerRequest(); + } + static orderStatuses(): OrderStatusRequest { + return new OrderStatusRequest(); + } + static customerOrders(): CustomerOrderRequest { + return new CustomerOrderRequest(); + } + static products(): ProductRequest { + return new ProductRequest(); + } + static orderLines(): OrderLineRequest { + return new OrderLineRequest(); + } + static orderSearchPresets(): OrderSearchPresetRequest { + return new OrderSearchPresetRequest(); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts new file mode 100644 index 0000000000000000000000000000000000000000..a68d8cc2ca9842f459f99553d125f457e4caa3c3 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts @@ -0,0 +1,137 @@ +import { TeaQLDataService, UserContext } from '../../teaql-ts'; + +export class CommercePlatform { + id?: string; + name?: string; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_customerList", { value: [], writable: true, enumerable: false }); + Object.defineProperty(this, "_orderStatusList", { value: [], writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false }); + Object.defineProperty(this, "_productList", { value: [], writable: true, enumerable: false }); + Object.defineProperty(this, "_orderLineList", { value: [], writable: true, enumerable: false }); + Object.defineProperty(this, "_orderSearchPresetList", { value: [], writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + static refer(id: string | number): CommercePlatform { + return new CommercePlatform({ id: String(id) } as Partial); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: UserContext): Promise { + if (!(this as any)._comment) { + throw new Error("Security audit failure: auditAs() must be called before save()"); + } + const mutation = { + entity: "CommercePlatform", + action: (this as any)._action, + payload: this, + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + }; + const service = ctx.requireResource("dataService"); + const result = await service.executeMutation(mutation); + if ((this as any)._action === "Create") { + (this as any).id = result.id; + (this as any)._action = "Update"; + } + if (result.version !== undefined) (this as any).version = result.version; + if (mutation.action !== "Delete") { + for (const child of (this as any)._customerList) { + child.updateCommercePlatform(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + for (const child of (this as any)._orderStatusList) { + child.updateCommercePlatform(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + for (const child of (this as any)._customerOrderList) { + child.updateCommercePlatform(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + for (const child of (this as any)._productList) { + child.updateCommercePlatform(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + for (const child of (this as any)._orderLineList) { + child.updateCommercePlatform(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + for (const child of (this as any)._orderSearchPresetList) { + child.updateCommercePlatform(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + } + return result; + } + + updateId(value: string): this { + this.id = value; + return this; + } + + updateName(value: string): this { + this.name = value; + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + return this; + } + + updateVersion(value: number): this { + this.version = value; + return this; + } + customerList(): any[] { + return (this as any)._customerList; + } + + orderStatusList(): any[] { + return (this as any)._orderStatusList; + } + + customerOrderList(): any[] { + return (this as any)._customerOrderList; + } + + productList(): any[] { + return (this as any)._productList; + } + + orderLineList(): any[] { + return (this as any)._orderLineList; + } + + orderSearchPresetList(): any[] { + return (this as any)._orderSearchPresetList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts new file mode 100644 index 0000000000000000000000000000000000000000..57f36a2ba9bb65a6edb5c6c8f2c3a4bfbe1a4c77 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts @@ -0,0 +1,99 @@ +import { TeaQLDataService, UserContext } from '../../teaql-ts'; + +export class Customer { + id?: string; + name?: string; + email?: string; + commercePlatform?: any; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + static refer(id: string | number): Customer { + return new Customer({ id: String(id) } as Partial); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: UserContext): Promise { + if (!(this as any)._comment) { + throw new Error("Security audit failure: auditAs() must be called before save()"); + } + const mutation = { + entity: "Customer", + action: (this as any)._action, + payload: this, + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + }; + const service = ctx.requireResource("dataService"); + const result = await service.executeMutation(mutation); + if ((this as any)._action === "Create") { + (this as any).id = result.id; + (this as any)._action = "Update"; + } + if (result.version !== undefined) (this as any).version = result.version; + if (mutation.action !== "Delete") { + for (const child of (this as any)._customerOrderList) { + child.updateCustomer(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + } + return result; + } + + updateId(value: string): this { + this.id = value; + return this; + } + + updateName(value: string): this { + this.name = value; + return this; + } + + updateEmail(value: string): this { + this.email = value; + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + return this; + } + + updateVersion(value: number): this { + this.version = value; + return this; + } + updateCommercePlatform(value: any): this { + this.commercePlatform = value?.id ?? value; + return this; + } + + customerOrderList(): any[] { + return (this as any)._customerOrderList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0d2a004146a7a705da8f4001950487302c359fa --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts @@ -0,0 +1,135 @@ +import { TeaQLDataService, UserContext } from '../../teaql-ts'; + +export class CustomerOrder { + id?: string; + orderNumber?: string; + orderDate?: string; + totalAmount?: number; + status?: any; + customer?: any; + commercePlatform?: any; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_orderLineList", { value: [], writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + static refer(id: string | number): CustomerOrder { + return new CustomerOrder({ id: String(id) } as Partial); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: UserContext): Promise { + if (!(this as any)._comment) { + throw new Error("Security audit failure: auditAs() must be called before save()"); + } + const mutation = { + entity: "CustomerOrder", + action: (this as any)._action, + payload: this, + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + }; + const service = ctx.requireResource("dataService"); + const result = await service.executeMutation(mutation); + if ((this as any)._action === "Create") { + (this as any).id = result.id; + (this as any)._action = "Update"; + } + if (result.version !== undefined) (this as any).version = result.version; + if (mutation.action !== "Delete") { + for (const child of (this as any)._orderLineList) { + child.updateCustomerOrder(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + } + return result; + } + + updateId(value: string): this { + this.id = value; + return this; + } + + updateOrderNumber(value: string): this { + this.orderNumber = value; + return this; + } + + updateOrderDate(value: string): this { + this.orderDate = value; + return this; + } + + updateTotalAmount(value: number): this { + this.totalAmount = value; + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + return this; + } + + updateVersion(value: number): this { + this.version = value; + return this; + } + updateStatus(value: any): this { + this.status = value?.id ?? value; + return this; + } + public updateStatusToPending(): CustomerOrder { + this.status = "1001"; + return this; + } + public updateStatusToProcessing(): CustomerOrder { + this.status = "1002"; + return this; + } + public updateStatusToShipped(): CustomerOrder { + this.status = "1003"; + return this; + } + public updateStatusToCompleted(): CustomerOrder { + this.status = "1004"; + return this; + } + + + updateCustomer(value: any): this { + this.customer = value?.id ?? value; + return this; + } + + + updateCommercePlatform(value: any): this { + this.commercePlatform = value?.id ?? value; + return this; + } + + orderLineList(): any[] { + return (this as any)._orderLineList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff730f3ae9e838dd11df076199bb68b602161a95 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts @@ -0,0 +1,104 @@ +import { TeaQLDataService, UserContext } from '../../teaql-ts'; + +export class OrderLine { + id?: string; + customerOrder?: any; + product?: any; + productName?: string; + sku?: string; + quantity?: any; + commercePlatform?: any; + createTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + static refer(id: string | number): OrderLine { + return new OrderLine({ id: String(id) } as Partial); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: UserContext): Promise { + if (!(this as any)._comment) { + throw new Error("Security audit failure: auditAs() must be called before save()"); + } + const mutation = { + entity: "OrderLine", + action: (this as any)._action, + payload: this, + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + }; + const service = ctx.requireResource("dataService"); + const result = await service.executeMutation(mutation); + if ((this as any)._action === "Create") { + (this as any).id = result.id; + (this as any)._action = "Update"; + } + if (result.version !== undefined) (this as any).version = result.version; + if (mutation.action !== "Delete") { + } + return result; + } + + updateId(value: string): this { + this.id = value; + return this; + } + + updateProductName(value: string): this { + this.productName = value; + return this; + } + + updateSku(value: string): this { + this.sku = value; + return this; + } + + updateQuantity(value: any): this { + this.quantity = value; + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + return this; + } + + updateVersion(value: number): this { + this.version = value; + return this; + } + updateCustomerOrder(value: any): this { + this.customerOrder = value?.id ?? value; + return this; + } + + + updateProduct(value: any): this { + this.product = value?.id ?? value; + return this; + } + + + updateCommercePlatform(value: any): this { + this.commercePlatform = value?.id ?? value; + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts new file mode 100644 index 0000000000000000000000000000000000000000..165a6a8ee67e02500f6ef5ce0ce309da2cde16ae --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts @@ -0,0 +1,102 @@ +import { TeaQLDataService, UserContext } from '../../teaql-ts'; + +export class OrderSearchPreset { + id?: string; + name?: string; + filterJson?: string; + requestId?: string; + ownerUserId?: string; + commercePlatform?: any; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + static refer(id: string | number): OrderSearchPreset { + return new OrderSearchPreset({ id: String(id) } as Partial); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: UserContext): Promise { + if (!(this as any)._comment) { + throw new Error("Security audit failure: auditAs() must be called before save()"); + } + const mutation = { + entity: "OrderSearchPreset", + action: (this as any)._action, + payload: this, + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + }; + const service = ctx.requireResource("dataService"); + const result = await service.executeMutation(mutation); + if ((this as any)._action === "Create") { + (this as any).id = result.id; + (this as any)._action = "Update"; + } + if (result.version !== undefined) (this as any).version = result.version; + if (mutation.action !== "Delete") { + } + return result; + } + + updateId(value: string): this { + this.id = value; + return this; + } + + updateName(value: string): this { + this.name = value; + return this; + } + + updateFilterJson(value: string): this { + this.filterJson = value; + return this; + } + + updateRequestId(value: string): this { + this.requestId = value; + return this; + } + + updateOwnerUserId(value: string): this { + this.ownerUserId = value; + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + return this; + } + + updateVersion(value: number): this { + this.version = value; + return this; + } + updateCommercePlatform(value: any): this { + this.commercePlatform = value?.id ?? value; + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts new file mode 100644 index 0000000000000000000000000000000000000000..aecd15c248718ece781534e0151c79c867dc2236 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts @@ -0,0 +1,99 @@ +import { TeaQLDataService, UserContext } from '../../teaql-ts'; + +export class OrderStatus { + id?: string; + name?: string; + code?: string; + color?: string; + displayOrder?: number; + commercePlatform?: any; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + static refer(id: string | number): OrderStatus { + return new OrderStatus({ id: String(id) } as Partial); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: UserContext): Promise { + if (!(this as any)._comment) { + throw new Error("Security audit failure: auditAs() must be called before save()"); + } + const mutation = { + entity: "OrderStatus", + action: (this as any)._action, + payload: this, + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + }; + const service = ctx.requireResource("dataService"); + const result = await service.executeMutation(mutation); + if ((this as any)._action === "Create") { + (this as any).id = result.id; + (this as any)._action = "Update"; + } + if (result.version !== undefined) (this as any).version = result.version; + if (mutation.action !== "Delete") { + for (const child of (this as any)._customerOrderList) { + child.updateStatus(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + } + return result; + } + + updateId(value: string): this { + this.id = value; + return this; + } + + updateName(value: string): this { + this.name = value; + return this; + } + + updateCode(value: string): this { + this.code = value; + return this; + } + + updateColor(value: string): this { + this.color = value; + return this; + } + + updateDisplayOrder(value: number): this { + this.displayOrder = value; + return this; + } + + updateVersion(value: number): this { + this.version = value; + return this; + } + updateCommercePlatform(value: any): this { + this.commercePlatform = value?.id ?? value; + return this; + } + + customerOrderList(): any[] { + return (this as any)._customerOrderList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0de4a9368ab291181025081eccb4ac70eba2661 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts @@ -0,0 +1,105 @@ +import { TeaQLDataService, UserContext } from '../../teaql-ts'; + +export class Product { + id?: string; + name?: string; + sku?: string; + imageUrl?: string; + commercePlatform?: any; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_orderLineList", { value: [], writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + static refer(id: string | number): Product { + return new Product({ id: String(id) } as Partial); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: UserContext): Promise { + if (!(this as any)._comment) { + throw new Error("Security audit failure: auditAs() must be called before save()"); + } + const mutation = { + entity: "Product", + action: (this as any)._action, + payload: this, + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + }; + const service = ctx.requireResource("dataService"); + const result = await service.executeMutation(mutation); + if ((this as any)._action === "Create") { + (this as any).id = result.id; + (this as any)._action = "Update"; + } + if (result.version !== undefined) (this as any).version = result.version; + if (mutation.action !== "Delete") { + for (const child of (this as any)._orderLineList) { + child.updateProduct(this); + child.auditAs((this as any)._comment); + await child.save(ctx); + } + } + return result; + } + + updateId(value: string): this { + this.id = value; + return this; + } + + updateName(value: string): this { + this.name = value; + return this; + } + + updateSku(value: string): this { + this.sku = value; + return this; + } + + updateImageUrl(value: string): this { + this.imageUrl = value; + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + return this; + } + + updateVersion(value: number): this { + this.version = value; + return this; + } + updateCommercePlatform(value: any): this { + this.commercePlatform = value?.id ?? value; + return this; + } + + orderLineList(): any[] { + return (this as any)._orderLineList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..de644cc8972ac0b53a28339cb45db629cce1758a --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts @@ -0,0 +1,328 @@ +import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CommercePlatform } from '../models/CommercePlatform'; + + + +export class CommercePlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + + constructor() { + this.query = new SelectQuery("CommercePlatform"); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + purpose(p: string): ExecutableCommercePlatformRequest { + if (!this._comment || !this._comment.trim()) { + throw new Error("purpose() requires a non-empty comment() set earlier on the request"); + } + this.query.purpose(p); + this._purpose = p; + return new ExecutableCommercePlatformRequest( + (ctx) => this.executeForListInternal(ctx), + () => this.limit(1)); + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + return this.query; + } + + selectCustomerListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("customerList", request.toQuery()); + return this; + } + selectOrderStatusListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("orderStatusList", request.toQuery()); + return this; + } + selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("customerOrderList", request.toQuery()); + return this; + } + selectProductListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("productList", request.toQuery()); + return this; + } + selectOrderLineListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("orderLineList", request.toQuery()); + return this; + } + selectOrderSearchPresetListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("orderSearchPresetList", request.toQuery()); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + + private async executeForListInternal(ctx: UserContext): Promise { + if (!this._purpose || !this._comment) { + throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); + } + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = ctx.requireResource("dataService"); + const data = await service.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (this.filters.length > 0) { + f.query.filter({ "$and": this.filters }); + } + result.facets[f.facetName] = await service.executeQuery(f.query); + } + } + + return result; + } + +} + +export class ExecutableCommercePlatformRequest { + constructor( + private readonly execute: (ctx: UserContext) => Promise, + private readonly limitOne: () => void, + ) {} + + newEntity(ctx: UserContext): CommercePlatform { + return new CommercePlatform(); + } + + executeForList(ctx: UserContext): Promise { + return this.execute(ctx); + } + + async executeForOne(ctx: UserContext): Promise { + this.limitOne(); + const res = await this.executeForList(ctx); + if (res.data && res.data.length > 0) { + return res.data[0]; + } + return null; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..4becbf9a5a1b916d30735cabedd5af0a4d6c7a8c --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts @@ -0,0 +1,525 @@ +import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CustomerOrder } from '../models/CustomerOrder'; + + + +export class CustomerOrderRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + + constructor() { + this.query = new SelectQuery("CustomerOrder"); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + purpose(p: string): ExecutableCustomerOrderRequest { + if (!this._comment || !this._comment.trim()) { + throw new Error("purpose() requires a non-empty comment() set earlier on the request"); + } + this.query.purpose(p); + this._purpose = p; + return new ExecutableCustomerOrderRequest( + (ctx) => this.executeForListInternal(ctx), + () => this.limit(1)); + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + return this.query; + } + + selectOrderLineListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("orderLineList", request.toQuery()); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withOrderNumberContaining(val: string): this { + this.filters.push({ "orderNumber": { "$contains": val } }); + return this; + } + + withOrderNumberIs(val: string): this { + this.filters.push({ "orderNumber": { "$eq": val } }); + return this; + } + + withOrderNumberIn(...vals: string[]): this { + this.filters.push({ "orderNumber": { "$in": vals } }); + return this; + } + + withOrderDateIs(val: any): this { + this.filters.push({ "orderDate": { "$eq": val } }); + return this; + } + + withOrderDateIn(...vals: any[]): this { + this.filters.push({ "orderDate": { "$in": vals } }); + return this; + } + + withOrderDateGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "orderDate": { "$gte": val } }); + return this; + } + + withOrderDateLessThanOrEqualTo(val: any): this { + this.filters.push({ "orderDate": { "$lte": val } }); + return this; + } + + withTotalAmountIs(val: any): this { + this.filters.push({ "totalAmount": { "$eq": val } }); + return this; + } + + withTotalAmountIn(...vals: any[]): this { + this.filters.push({ "totalAmount": { "$in": vals } }); + return this; + } + + withTotalAmountGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "totalAmount": { "$gte": val } }); + return this; + } + + withTotalAmountLessThanOrEqualTo(val: any): this { + this.filters.push({ "totalAmount": { "$lte": val } }); + return this; + } + + filterByStatus(val: any): this { + this.filters.push({ "status": { "$eq": val } }); + return this; + } + + filterByStatusIn(...vals: any[]): this { + this.filters.push({ "status": { "$in": vals } }); + return this; + } + + filterByCustomer(val: any): this { + this.filters.push({ "customer": { "$eq": val } }); + return this; + } + + filterByCustomerIn(...vals: any[]): this { + this.filters.push({ "customer": { "$in": vals } }); + return this; + } + + filterByCommercePlatform(val: any): this { + this.filters.push({ "commercePlatform": { "$eq": val } }); + return this; + } + + filterByCommercePlatformIn(...vals: any[]): this { + this.filters.push({ "commercePlatform": { "$in": vals } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByOrderNumberAscending(): this { + this.query.orderBy("orderNumber", "asc"); + return this; + } + + orderByOrderNumberDescending(): this { + this.query.orderBy("orderNumber", "desc"); + return this; + } + + orderByOrderDateAscending(): this { + this.query.orderBy("orderDate", "asc"); + return this; + } + + orderByOrderDateDescending(): this { + this.query.orderBy("orderDate", "desc"); + return this; + } + + orderByTotalAmountAscending(): this { + this.query.orderBy("totalAmount", "asc"); + return this; + } + + orderByTotalAmountDescending(): this { + this.query.orderBy("totalAmount", "desc"); + return this; + } + + + + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + minTotalAmount(): this { + return this.minTotalAmountAs("minOfTotalAmount"); + } + + minTotalAmountAs(retName: string): this { + this.query.aggregate("min", "totalAmount", retName); + return this; + } + maxTotalAmount(): this { + return this.maxTotalAmountAs("maxOfTotalAmount"); + } + + maxTotalAmountAs(retName: string): this { + this.query.aggregate("max", "totalAmount", retName); + return this; + } + sumTotalAmount(): this { + return this.sumTotalAmountAs("sumOfTotalAmount"); + } + + sumTotalAmountAs(retName: string): this { + this.query.aggregate("sum", "totalAmount", retName); + return this; + } + avgTotalAmount(): this { + return this.avgTotalAmountAs("avgOfTotalAmount"); + } + + avgTotalAmountAs(retName: string): this { + this.query.aggregate("avg", "totalAmount", retName); + return this; + } + standardDeviationTotalAmount(): this { + return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount"); + } + + standardDeviationTotalAmountAs(retName: string): this { + this.query.aggregate("stddev", "totalAmount", retName); + return this; + } + squareRootOfPopulationStandardDeviationTotalAmount(): this { + return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount"); + } + + squareRootOfPopulationStandardDeviationTotalAmountAs(retName: string): this { + this.query.aggregate("stddev_pop", "totalAmount", retName); + return this; + } + sampleVarianceTotalAmount(): this { + return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount"); + } + + sampleVarianceTotalAmountAs(retName: string): this { + this.query.aggregate("var_samp", "totalAmount", retName); + return this; + } + samplePopulationVarianceTotalAmount(): this { + return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount"); + } + + samplePopulationVarianceTotalAmountAs(retName: string): this { + this.query.aggregate("var_pop", "totalAmount", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByOrderNumber(): this { + this.query.groupBy("orderNumber"); + return this; + } + + groupByOrderNumberAs(retName: string): this { + this.query.groupBy("orderNumber"); // In TS we don't alias group by yet natively + return this; + } + groupByOrderDate(): this { + this.query.groupBy("orderDate"); + return this; + } + + groupByOrderDateAs(retName: string): this { + this.query.groupBy("orderDate"); // In TS we don't alias group by yet natively + return this; + } + groupByTotalAmount(): this { + this.query.groupBy("totalAmount"); + return this; + } + + groupByTotalAmountAs(retName: string): this { + this.query.groupBy("totalAmount"); // In TS we don't alias group by yet natively + return this; + } + groupByStatus(): this { + this.query.groupBy("status"); + return this; + } + + groupByStatusAs(retName: string): this { + this.query.groupBy("status"); // In TS we don't alias group by yet natively + return this; + } + groupByCustomer(): this { + this.query.groupBy("customer"); + return this; + } + + groupByCustomerAs(retName: string): this { + this.query.groupBy("customer"); // In TS we don't alias group by yet natively + return this; + } + groupByCommercePlatform(): this { + this.query.groupBy("commercePlatform"); + return this; + } + + groupByCommercePlatformAs(retName: string): this { + this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByStatusAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "STATUS_PROPERTY", request); + return this; + } + + facetByCustomerAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "CUSTOMER_PROPERTY", request); + return this; + } + + facetByCommercePlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + return this; + } + + + private async executeForListInternal(ctx: UserContext): Promise { + if (!this._purpose || !this._comment) { + throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); + } + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = ctx.requireResource("dataService"); + const data = await service.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (this.filters.length > 0) { + f.query.filter({ "$and": this.filters }); + } + result.facets[f.facetName] = await service.executeQuery(f.query); + } + } + + return result; + } + +} + +export class ExecutableCustomerOrderRequest { + constructor( + private readonly execute: (ctx: UserContext) => Promise, + private readonly limitOne: () => void, + ) {} + + newEntity(ctx: UserContext): CustomerOrder { + return new CustomerOrder(); + } + + executeForList(ctx: UserContext): Promise { + return this.execute(ctx); + } + + async executeForOne(ctx: UserContext): Promise { + this.limitOne(); + const res = await this.executeForList(ctx); + if (res.data && res.data.length > 0) { + return res.data[0]; + } + return null; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe04568bf9119f460f93b6da39420aee5ba3c3e1 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts @@ -0,0 +1,367 @@ +import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Customer } from '../models/Customer'; + + + +export class CustomerRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + + constructor() { + this.query = new SelectQuery("Customer"); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + purpose(p: string): ExecutableCustomerRequest { + if (!this._comment || !this._comment.trim()) { + throw new Error("purpose() requires a non-empty comment() set earlier on the request"); + } + this.query.purpose(p); + this._purpose = p; + return new ExecutableCustomerRequest( + (ctx) => this.executeForListInternal(ctx), + () => this.limit(1)); + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + return this.query; + } + + selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("customerOrderList", request.toQuery()); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withEmailContaining(val: string): this { + this.filters.push({ "email": { "$contains": val } }); + return this; + } + + withEmailIs(val: string): this { + this.filters.push({ "email": { "$eq": val } }); + return this; + } + + withEmailIn(...vals: string[]): this { + this.filters.push({ "email": { "$in": vals } }); + return this; + } + + filterByCommercePlatform(val: any): this { + this.filters.push({ "commercePlatform": { "$eq": val } }); + return this; + } + + filterByCommercePlatformIn(...vals: any[]): this { + this.filters.push({ "commercePlatform": { "$in": vals } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByEmailAscending(): this { + this.query.orderBy("email", "asc"); + return this; + } + + orderByEmailDescending(): this { + this.query.orderBy("email", "desc"); + return this; + } + + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByEmail(): this { + this.query.groupBy("email"); + return this; + } + + groupByEmailAs(retName: string): this { + this.query.groupBy("email"); // In TS we don't alias group by yet natively + return this; + } + groupByCommercePlatform(): this { + this.query.groupBy("commercePlatform"); + return this; + } + + groupByCommercePlatformAs(retName: string): this { + this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByCommercePlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + return this; + } + + + private async executeForListInternal(ctx: UserContext): Promise { + if (!this._purpose || !this._comment) { + throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); + } + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = ctx.requireResource("dataService"); + const data = await service.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (this.filters.length > 0) { + f.query.filter({ "$and": this.filters }); + } + result.facets[f.facetName] = await service.executeQuery(f.query); + } + } + + return result; + } + +} + +export class ExecutableCustomerRequest { + constructor( + private readonly execute: (ctx: UserContext) => Promise, + private readonly limitOne: () => void, + ) {} + + newEntity(ctx: UserContext): Customer { + return new Customer(); + } + + executeForList(ctx: UserContext): Promise { + return this.execute(ctx); + } + + async executeForOne(ctx: UserContext): Promise { + this.limitOne(); + const res = await this.executeForList(ctx); + if (res.data && res.data.length > 0) { + return res.data[0]; + } + return null; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..724e9b3fbc95d1484de9bd66ed17c84b96632c19 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts @@ -0,0 +1,477 @@ +import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { OrderLine } from '../models/OrderLine'; + + + +export class OrderLineRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + + constructor() { + this.query = new SelectQuery("OrderLine"); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + purpose(p: string): ExecutableOrderLineRequest { + if (!this._comment || !this._comment.trim()) { + throw new Error("purpose() requires a non-empty comment() set earlier on the request"); + } + this.query.purpose(p); + this._purpose = p; + return new ExecutableOrderLineRequest( + (ctx) => this.executeForListInternal(ctx), + () => this.limit(1)); + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + return this.query; + } + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + filterByCustomerOrder(val: any): this { + this.filters.push({ "customerOrder": { "$eq": val } }); + return this; + } + + filterByCustomerOrderIn(...vals: any[]): this { + this.filters.push({ "customerOrder": { "$in": vals } }); + return this; + } + + filterByProduct(val: any): this { + this.filters.push({ "product": { "$eq": val } }); + return this; + } + + filterByProductIn(...vals: any[]): this { + this.filters.push({ "product": { "$in": vals } }); + return this; + } + + withProductNameContaining(val: string): this { + this.filters.push({ "productName": { "$contains": val } }); + return this; + } + + withProductNameIs(val: string): this { + this.filters.push({ "productName": { "$eq": val } }); + return this; + } + + withProductNameIn(...vals: string[]): this { + this.filters.push({ "productName": { "$in": vals } }); + return this; + } + + withSkuContaining(val: string): this { + this.filters.push({ "sku": { "$contains": val } }); + return this; + } + + withSkuIs(val: string): this { + this.filters.push({ "sku": { "$eq": val } }); + return this; + } + + withSkuIn(...vals: string[]): this { + this.filters.push({ "sku": { "$in": vals } }); + return this; + } + + withQuantityIs(val: any): this { + this.filters.push({ "quantity": { "$eq": val } }); + return this; + } + + withQuantityIn(...vals: any[]): this { + this.filters.push({ "quantity": { "$in": vals } }); + return this; + } + + withQuantityGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "quantity": { "$gte": val } }); + return this; + } + + withQuantityLessThanOrEqualTo(val: any): this { + this.filters.push({ "quantity": { "$lte": val } }); + return this; + } + + filterByCommercePlatform(val: any): this { + this.filters.push({ "commercePlatform": { "$eq": val } }); + return this; + } + + filterByCommercePlatformIn(...vals: any[]): this { + this.filters.push({ "commercePlatform": { "$in": vals } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + + orderByProductNameAscending(): this { + this.query.orderBy("productName", "asc"); + return this; + } + + orderByProductNameDescending(): this { + this.query.orderBy("productName", "desc"); + return this; + } + + orderBySkuAscending(): this { + this.query.orderBy("sku", "asc"); + return this; + } + + orderBySkuDescending(): this { + this.query.orderBy("sku", "desc"); + return this; + } + + orderByQuantityAscending(): this { + this.query.orderBy("quantity", "asc"); + return this; + } + + orderByQuantityDescending(): this { + this.query.orderBy("quantity", "desc"); + return this; + } + + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + minQuantity(): this { + return this.minQuantityAs("minOfQuantity"); + } + + minQuantityAs(retName: string): this { + this.query.aggregate("min", "quantity", retName); + return this; + } + maxQuantity(): this { + return this.maxQuantityAs("maxOfQuantity"); + } + + maxQuantityAs(retName: string): this { + this.query.aggregate("max", "quantity", retName); + return this; + } + sumQuantity(): this { + return this.sumQuantityAs("sumOfQuantity"); + } + + sumQuantityAs(retName: string): this { + this.query.aggregate("sum", "quantity", retName); + return this; + } + avgQuantity(): this { + return this.avgQuantityAs("avgOfQuantity"); + } + + avgQuantityAs(retName: string): this { + this.query.aggregate("avg", "quantity", retName); + return this; + } + standardDeviationQuantity(): this { + return this.standardDeviationQuantityAs("standardDeviationOfQuantity"); + } + + standardDeviationQuantityAs(retName: string): this { + this.query.aggregate("stddev", "quantity", retName); + return this; + } + squareRootOfPopulationStandardDeviationQuantity(): this { + return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity"); + } + + squareRootOfPopulationStandardDeviationQuantityAs(retName: string): this { + this.query.aggregate("stddev_pop", "quantity", retName); + return this; + } + sampleVarianceQuantity(): this { + return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity"); + } + + sampleVarianceQuantityAs(retName: string): this { + this.query.aggregate("var_samp", "quantity", retName); + return this; + } + samplePopulationVarianceQuantity(): this { + return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity"); + } + + samplePopulationVarianceQuantityAs(retName: string): this { + this.query.aggregate("var_pop", "quantity", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByCustomerOrder(): this { + this.query.groupBy("customerOrder"); + return this; + } + + groupByCustomerOrderAs(retName: string): this { + this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively + return this; + } + groupByProduct(): this { + this.query.groupBy("product"); + return this; + } + + groupByProductAs(retName: string): this { + this.query.groupBy("product"); // In TS we don't alias group by yet natively + return this; + } + groupByProductName(): this { + this.query.groupBy("productName"); + return this; + } + + groupByProductNameAs(retName: string): this { + this.query.groupBy("productName"); // In TS we don't alias group by yet natively + return this; + } + groupBySku(): this { + this.query.groupBy("sku"); + return this; + } + + groupBySkuAs(retName: string): this { + this.query.groupBy("sku"); // In TS we don't alias group by yet natively + return this; + } + groupByQuantity(): this { + this.query.groupBy("quantity"); + return this; + } + + groupByQuantityAs(retName: string): this { + this.query.groupBy("quantity"); // In TS we don't alias group by yet natively + return this; + } + groupByCommercePlatform(): this { + this.query.groupBy("commercePlatform"); + return this; + } + + groupByCommercePlatformAs(retName: string): this { + this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByCustomerOrderAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "CUSTOMER_ORDER_PROPERTY", request); + return this; + } + + facetByProductAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "PRODUCT_PROPERTY", request); + return this; + } + + facetByCommercePlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + return this; + } + + + private async executeForListInternal(ctx: UserContext): Promise { + if (!this._purpose || !this._comment) { + throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); + } + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = ctx.requireResource("dataService"); + const data = await service.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (this.filters.length > 0) { + f.query.filter({ "$and": this.filters }); + } + result.facets[f.facetName] = await service.executeQuery(f.query); + } + } + + return result; + } + +} + +export class ExecutableOrderLineRequest { + constructor( + private readonly execute: (ctx: UserContext) => Promise, + private readonly limitOne: () => void, + ) {} + + newEntity(ctx: UserContext): OrderLine { + return new OrderLine(); + } + + executeForList(ctx: UserContext): Promise { + return this.execute(ctx); + } + + async executeForOne(ctx: UserContext): Promise { + this.limitOne(); + const res = await this.executeForList(ctx); + if (res.data && res.data.length > 0) { + return res.data[0]; + } + return null; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa8f517296ca28d183b6c047ed4067438fe3aaf4 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts @@ -0,0 +1,431 @@ +import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { OrderSearchPreset } from '../models/OrderSearchPreset'; + + + +export class OrderSearchPresetRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + + constructor() { + this.query = new SelectQuery("OrderSearchPreset"); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + purpose(p: string): ExecutableOrderSearchPresetRequest { + if (!this._comment || !this._comment.trim()) { + throw new Error("purpose() requires a non-empty comment() set earlier on the request"); + } + this.query.purpose(p); + this._purpose = p; + return new ExecutableOrderSearchPresetRequest( + (ctx) => this.executeForListInternal(ctx), + () => this.limit(1)); + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + return this.query; + } + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withFilterJsonContaining(val: string): this { + this.filters.push({ "filterJson": { "$contains": val } }); + return this; + } + + withFilterJsonIs(val: string): this { + this.filters.push({ "filterJson": { "$eq": val } }); + return this; + } + + withFilterJsonIn(...vals: string[]): this { + this.filters.push({ "filterJson": { "$in": vals } }); + return this; + } + + withRequestIdContaining(val: string): this { + this.filters.push({ "requestId": { "$contains": val } }); + return this; + } + + withRequestIdIs(val: string): this { + this.filters.push({ "requestId": { "$eq": val } }); + return this; + } + + withRequestIdIn(...vals: string[]): this { + this.filters.push({ "requestId": { "$in": vals } }); + return this; + } + + withOwnerUserIdContaining(val: string): this { + this.filters.push({ "ownerUserId": { "$contains": val } }); + return this; + } + + withOwnerUserIdIs(val: string): this { + this.filters.push({ "ownerUserId": { "$eq": val } }); + return this; + } + + withOwnerUserIdIn(...vals: string[]): this { + this.filters.push({ "ownerUserId": { "$in": vals } }); + return this; + } + + filterByCommercePlatform(val: any): this { + this.filters.push({ "commercePlatform": { "$eq": val } }); + return this; + } + + filterByCommercePlatformIn(...vals: any[]): this { + this.filters.push({ "commercePlatform": { "$in": vals } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByFilterJsonAscending(): this { + this.query.orderBy("filterJson", "asc"); + return this; + } + + orderByFilterJsonDescending(): this { + this.query.orderBy("filterJson", "desc"); + return this; + } + + orderByRequestIdAscending(): this { + this.query.orderBy("requestId", "asc"); + return this; + } + + orderByRequestIdDescending(): this { + this.query.orderBy("requestId", "desc"); + return this; + } + + orderByOwnerUserIdAscending(): this { + this.query.orderBy("ownerUserId", "asc"); + return this; + } + + orderByOwnerUserIdDescending(): this { + this.query.orderBy("ownerUserId", "desc"); + return this; + } + + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByFilterJson(): this { + this.query.groupBy("filterJson"); + return this; + } + + groupByFilterJsonAs(retName: string): this { + this.query.groupBy("filterJson"); // In TS we don't alias group by yet natively + return this; + } + groupByRequestId(): this { + this.query.groupBy("requestId"); + return this; + } + + groupByRequestIdAs(retName: string): this { + this.query.groupBy("requestId"); // In TS we don't alias group by yet natively + return this; + } + groupByOwnerUserId(): this { + this.query.groupBy("ownerUserId"); + return this; + } + + groupByOwnerUserIdAs(retName: string): this { + this.query.groupBy("ownerUserId"); // In TS we don't alias group by yet natively + return this; + } + groupByCommercePlatform(): this { + this.query.groupBy("commercePlatform"); + return this; + } + + groupByCommercePlatformAs(retName: string): this { + this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByCommercePlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + return this; + } + + + private async executeForListInternal(ctx: UserContext): Promise { + if (!this._purpose || !this._comment) { + throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); + } + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = ctx.requireResource("dataService"); + const data = await service.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (this.filters.length > 0) { + f.query.filter({ "$and": this.filters }); + } + result.facets[f.facetName] = await service.executeQuery(f.query); + } + } + + return result; + } + +} + +export class ExecutableOrderSearchPresetRequest { + constructor( + private readonly execute: (ctx: UserContext) => Promise, + private readonly limitOne: () => void, + ) {} + + newEntity(ctx: UserContext): OrderSearchPreset { + return new OrderSearchPreset(); + } + + executeForList(ctx: UserContext): Promise { + return this.execute(ctx); + } + + async executeForOne(ctx: UserContext): Promise { + this.limitOne(); + const res = await this.executeForList(ctx); + if (res.data && res.data.length > 0) { + return res.data[0]; + } + return null; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..7061432bf69595836f3390c3172fc968e775ae1a --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts @@ -0,0 +1,426 @@ +import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { OrderStatus } from '../models/OrderStatus'; + + + +export class OrderStatusRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + + constructor() { + this.query = new SelectQuery("OrderStatus"); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + purpose(p: string): ExecutableOrderStatusRequest { + if (!this._comment || !this._comment.trim()) { + throw new Error("purpose() requires a non-empty comment() set earlier on the request"); + } + this.query.purpose(p); + this._purpose = p; + return new ExecutableOrderStatusRequest( + (ctx) => this.executeForListInternal(ctx), + () => this.limit(1)); + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + return this.query; + } + + selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("customerOrderList", request.toQuery()); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withCodeContaining(val: string): this { + this.filters.push({ "code": { "$contains": val } }); + return this; + } + + withCodeIs(val: string): this { + this.filters.push({ "code": { "$eq": val } }); + return this; + } + + withCodeIn(...vals: string[]): this { + this.filters.push({ "code": { "$in": vals } }); + return this; + } + + withColorContaining(val: string): this { + this.filters.push({ "color": { "$contains": val } }); + return this; + } + + withColorIs(val: string): this { + this.filters.push({ "color": { "$eq": val } }); + return this; + } + + withColorIn(...vals: string[]): this { + this.filters.push({ "color": { "$in": vals } }); + return this; + } + + withDisplayOrderIs(val: any): this { + this.filters.push({ "displayOrder": { "$eq": val } }); + return this; + } + + withDisplayOrderIn(...vals: any[]): this { + this.filters.push({ "displayOrder": { "$in": vals } }); + return this; + } + + withDisplayOrderGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$gte": val } }); + return this; + } + + withDisplayOrderLessThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$lte": val } }); + return this; + } + + filterByCommercePlatform(val: any): this { + this.filters.push({ "commercePlatform": { "$eq": val } }); + return this; + } + + filterByCommercePlatformIn(...vals: any[]): this { + this.filters.push({ "commercePlatform": { "$in": vals } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByCodeAscending(): this { + this.query.orderBy("code", "asc"); + return this; + } + + orderByCodeDescending(): this { + this.query.orderBy("code", "desc"); + return this; + } + + orderByColorAscending(): this { + this.query.orderBy("color", "asc"); + return this; + } + + orderByColorDescending(): this { + this.query.orderBy("color", "desc"); + return this; + } + + orderByDisplayOrderAscending(): this { + this.query.orderBy("displayOrder", "asc"); + return this; + } + + orderByDisplayOrderDescending(): this { + this.query.orderBy("displayOrder", "desc"); + return this; + } + + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + minDisplayOrder(): this { + return this.minDisplayOrderAs("minOfDisplayOrder"); + } + + minDisplayOrderAs(retName: string): this { + this.query.aggregate("min", "displayOrder", retName); + return this; + } + maxDisplayOrder(): this { + return this.maxDisplayOrderAs("maxOfDisplayOrder"); + } + + maxDisplayOrderAs(retName: string): this { + this.query.aggregate("max", "displayOrder", retName); + return this; + } + sumDisplayOrder(): this { + return this.sumDisplayOrderAs("sumOfDisplayOrder"); + } + + sumDisplayOrderAs(retName: string): this { + this.query.aggregate("sum", "displayOrder", retName); + return this; + } + avgDisplayOrder(): this { + return this.avgDisplayOrderAs("avgOfDisplayOrder"); + } + + avgDisplayOrderAs(retName: string): this { + this.query.aggregate("avg", "displayOrder", retName); + return this; + } + standardDeviationDisplayOrder(): this { + return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder"); + } + + standardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev", "displayOrder", retName); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrder(): this { + return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder"); + } + + squareRootOfPopulationStandardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev_pop", "displayOrder", retName); + return this; + } + sampleVarianceDisplayOrder(): this { + return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder"); + } + + sampleVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_samp", "displayOrder", retName); + return this; + } + samplePopulationVarianceDisplayOrder(): this { + return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder"); + } + + samplePopulationVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_pop", "displayOrder", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByCode(): this { + this.query.groupBy("code"); + return this; + } + + groupByCodeAs(retName: string): this { + this.query.groupBy("code"); // In TS we don't alias group by yet natively + return this; + } + groupByColor(): this { + this.query.groupBy("color"); + return this; + } + + groupByColorAs(retName: string): this { + this.query.groupBy("color"); // In TS we don't alias group by yet natively + return this; + } + groupByDisplayOrder(): this { + this.query.groupBy("displayOrder"); + return this; + } + + groupByDisplayOrderAs(retName: string): this { + this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + return this; + } + groupByCommercePlatform(): this { + this.query.groupBy("commercePlatform"); + return this; + } + + groupByCommercePlatformAs(retName: string): this { + this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByCommercePlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + return this; + } + + + private async executeForListInternal(ctx: UserContext): Promise { + if (!this._purpose || !this._comment) { + throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); + } + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = ctx.requireResource("dataService"); + const data = await service.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (this.filters.length > 0) { + f.query.filter({ "$and": this.filters }); + } + result.facets[f.facetName] = await service.executeQuery(f.query); + } + } + + return result; + } + +} + +export class ExecutableOrderStatusRequest { + constructor( + private readonly execute: (ctx: UserContext) => Promise, + private readonly limitOne: () => void, + ) {} + + newEntity(ctx: UserContext): OrderStatus { + return new OrderStatus(); + } + + executeForList(ctx: UserContext): Promise { + return this.execute(ctx); + } + + async executeForOne(ctx: UserContext): Promise { + this.limitOne(); + const res = await this.executeForList(ctx); + if (res.data && res.data.length > 0) { + return res.data[0]; + } + return null; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..326c9fa4f9b7d8e26e5162fde4582d670ccabd1d --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts @@ -0,0 +1,401 @@ +import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Product } from '../models/Product'; + + + +export class ProductRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + + constructor() { + this.query = new SelectQuery("Product"); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + purpose(p: string): ExecutableProductRequest { + if (!this._comment || !this._comment.trim()) { + throw new Error("purpose() requires a non-empty comment() set earlier on the request"); + } + this.query.purpose(p); + this._purpose = p; + return new ExecutableProductRequest( + (ctx) => this.executeForListInternal(ctx), + () => this.limit(1)); + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + return this.query; + } + + selectOrderLineListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery("orderLineList", request.toQuery()); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withSkuContaining(val: string): this { + this.filters.push({ "sku": { "$contains": val } }); + return this; + } + + withSkuIs(val: string): this { + this.filters.push({ "sku": { "$eq": val } }); + return this; + } + + withSkuIn(...vals: string[]): this { + this.filters.push({ "sku": { "$in": vals } }); + return this; + } + + withImageUrlContaining(val: string): this { + this.filters.push({ "imageUrl": { "$contains": val } }); + return this; + } + + withImageUrlIs(val: string): this { + this.filters.push({ "imageUrl": { "$eq": val } }); + return this; + } + + withImageUrlIn(...vals: string[]): this { + this.filters.push({ "imageUrl": { "$in": vals } }); + return this; + } + + filterByCommercePlatform(val: any): this { + this.filters.push({ "commercePlatform": { "$eq": val } }); + return this; + } + + filterByCommercePlatformIn(...vals: any[]): this { + this.filters.push({ "commercePlatform": { "$in": vals } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderBySkuAscending(): this { + this.query.orderBy("sku", "asc"); + return this; + } + + orderBySkuDescending(): this { + this.query.orderBy("sku", "desc"); + return this; + } + + orderByImageUrlAscending(): this { + this.query.orderBy("imageUrl", "asc"); + return this; + } + + orderByImageUrlDescending(): this { + this.query.orderBy("imageUrl", "desc"); + return this; + } + + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupBySku(): this { + this.query.groupBy("sku"); + return this; + } + + groupBySkuAs(retName: string): this { + this.query.groupBy("sku"); // In TS we don't alias group by yet natively + return this; + } + groupByImageUrl(): this { + this.query.groupBy("imageUrl"); + return this; + } + + groupByImageUrlAs(retName: string): this { + this.query.groupBy("imageUrl"); // In TS we don't alias group by yet natively + return this; + } + groupByCommercePlatform(): this { + this.query.groupBy("commercePlatform"); + return this; + } + + groupByCommercePlatformAs(retName: string): this { + this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByCommercePlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + return this; + } + + + private async executeForListInternal(ctx: UserContext): Promise { + if (!this._purpose || !this._comment) { + throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); + } + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = ctx.requireResource("dataService"); + const data = await service.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (this.filters.length > 0) { + f.query.filter({ "$and": this.filters }); + } + result.facets[f.facetName] = await service.executeQuery(f.query); + } + } + + return result; + } + +} + +export class ExecutableProductRequest { + constructor( + private readonly execute: (ctx: UserContext) => Promise, + private readonly limitOne: () => void, + ) {} + + newEntity(ctx: UserContext): Product { + return new Product(); + } + + executeForList(ctx: UserContext): Promise { + return this.execute(ctx); + } + + async executeForOne(ctx: UserContext): Promise { + this.limitOne(); + const res = await this.executeForList(ctx); + if (res.data && res.data.length > 0) { + return res.data[0]; + } + return null; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-postgres.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-postgres.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6d4c95d3292302d8d130c2ca4af9d8ff3b981e2 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-postgres.ts @@ -0,0 +1,13 @@ +import { + PostgreSQLDriver, + PostgreSQLTeaQLClient as RuntimePostgreSQLTeaQLClient +} from "teaql-ts/sql/postgres"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; + +export { PostgreSQLDriver } from "teaql-ts/sql/postgres"; + +export class PostgreSQLTeaQLClient extends RuntimePostgreSQLTeaQLClient { + constructor(connectionString: string) { + super(connectionString, ENTITY_SCHEMAS); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..93bac3e368900391fcd74f5db5e08d82a99fbb46 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts @@ -0,0 +1,30 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"CommercePlatform": { + table: "commerce_platform_data", + columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, + relations: {"customerList": { targetEntity: "Customer", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderStatusList": { targetEntity: "OrderStatus", localKey: "id", foreignKey: "commercePlatform", many: true }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "commercePlatform", many: true }, "productList": { targetEntity: "Product", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderSearchPresetList": { targetEntity: "OrderSearchPreset", localKey: "id", foreignKey: "commercePlatform", many: true }}}, +"Customer": { + table: "customer_data", + columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "email": { columnName: "email", logicalType: "text", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, + relations: {"customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "customer", many: true }}}, +"OrderStatus": { + table: "order_status_data", + columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "code": { columnName: "code", logicalType: "text", decode: "native" }, "color": { columnName: "color", logicalType: "text", decode: "native" }, "displayOrder": { columnName: "display_order", logicalType: "decimal", decode: "number" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, + relations: {"customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "status", many: true }}}, +"CustomerOrder": { + table: "customer_order_data", + columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "orderNumber": { columnName: "order_number", logicalType: "text", decode: "native" }, "orderDate": { columnName: "order_date", logicalType: "date", decode: "date" }, "totalAmount": { columnName: "total_amount", logicalType: "decimal", decode: "number" }, "status": { columnName: "status", logicalType: "integer", decode: "string" }, "customer": { columnName: "customer", logicalType: "integer", decode: "string" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, + relations: {"orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "customerOrder", many: true }}}, +"Product": { + table: "product_data", + columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "sku": { columnName: "sku", logicalType: "text", decode: "native" }, "imageUrl": { columnName: "image_url", logicalType: "text", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, + relations: {"orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "product", many: true }}}, +"OrderLine": { + table: "order_line_data", + columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "customerOrder": { columnName: "customer_order", logicalType: "integer", decode: "string" }, "product": { columnName: "product", logicalType: "integer", decode: "string" }, "productName": { columnName: "product_name", logicalType: "text", decode: "native" }, "sku": { columnName: "sku", logicalType: "text", decode: "native" }, "quantity": { columnName: "quantity", logicalType: "integer", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}}, +"OrderSearchPreset": { + table: "order_search_preset_data", + columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "filterJson": { columnName: "filter_json", logicalType: "text", decode: "native" }, "requestId": { columnName: "request_id", logicalType: "text", decode: "native" }, "ownerUserId": { columnName: "owner_user_id", logicalType: "text", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..77936819272592b22e27ec8c3051b032f182004e --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts @@ -0,0 +1,31 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { OrderBy, SelectQuery as RuntimeSelectQuery } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, ENTITY_SCHEMAS); + } + + async executeQuery(query: any): Promise { + if (typeof query?.prepareForList === "function") { + return super.executeQuery(query); + } + const adapted = new RuntimeSelectQuery(query.entity); + adapted.comment(query._comment ?? "legacy generated order example"); + adapted.purpose(query._purpose ?? "verify local runtime compatibility"); + adapted.filterCondition = query._filters?.length ? { $and: query._filters } : null; + adapted.limitValue = query._limit ?? 0; + adapted.offsetValue = query._offset ?? 0; + adapted.orderItems = (query._orderBy ?? []).map((item: any) => + item.d === "desc" ? OrderBy.desc(item.f) : OrderBy.asc(item.f)); + adapted.groupByItems = query._groupBy ?? []; + adapted.aggregateItems = query._aggregates ?? []; + return super.executeQuery(adapted); + } +} diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-ts.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4c22fb6df95a7276e4b258506a80e711da6c210 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-ts.ts @@ -0,0 +1,117 @@ +export class SelectQuery { + entity: string; + _comment?: string; + _purpose?: string; + _limit?: number; + _offset?: number; + _orderBy: any[] = []; + _groupBy: string[] = []; + _aggregates: any[] = []; + _filters: any[] = []; + facets: any[] = []; + relations: Array<{ name: string; query?: SelectQuery }> = []; + + constructor(entity: string) { + this.entity = entity; + } + comment(c: string) { this._comment = c; } + purpose(p: string) { this._purpose = p; } + limit(n: number) { this._limit = n; } + offset(n: number) { this._offset = n; } + orderBy(f: string, d: string) { this._orderBy.push({f, d}); } + groupBy(f: string) { this._groupBy.push(f); } + countField(f: string, n: string) { this._aggregates.push({func: "count", field: f, retName: n}); } + aggregate(func: string, field: string, retName: string) { this._aggregates.push({func, field, retName}); } + andFilter(expr: any) { this._filters.push(expr); } + filter(expr: any) { this._filters.push(expr); } + relationQuery(name: string, query: SelectQuery) { this.relations.push({ name, query }); } + facetBy(facetName: string, field: string, req: any) { + this.facets.push({ facetName, query: req.query }); + } +} + +export interface TeaQLDataService { + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + close?(): Promise; +} + +export class TeaQLClient implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + + constructor(private storagePath?: string) { + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeMutation(mutation: any): Promise { + const table = this.data[mutation.entity] ||= {}; + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + this.nextIds[mutation.entity] = Number(id) + 1; + const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + table[String(id)] = record; + this.persist(); + return { success: true, id: String(id), version: record.version }; + } + if (mutation.action === "Update") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; + this.persist(); + return { success: true, id, version: table[id].version }; + } + if (mutation.action === "Delete") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + delete table[id]; + this.persist(); + return { success: true, id, deleted: true }; + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + async query(ctx: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + return true; + }); + }; + for (const expression of query._filters || []) rows = rows.filter(row => matches(row, expression)); + for (const order of [...(query._orderBy || [])].reverse()) { + rows.sort((a, b) => (a[order.f] === b[order.f] ? 0 : a[order.f] > b[order.f] ? 1 : -1) * (order.d === "desc" ? -1 : 1)); + } + const start = query._offset || 0; + return rows.slice(start, query._limit === undefined ? undefined : start + query._limit); + } +} + +declare const require: any; +export { UserContext } from "teaql-ts"; +import { UserContext } from "teaql-ts"; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/tsconfig.json b/source/teaql-ts/examples/order-management/typescript-node-lib-core/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/.gitignore b/source/teaql-ts/examples/school-management/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6d613716f2421f77517ff8209ab6a04ea3b49d63 --- /dev/null +++ b/source/teaql-ts/examples/school-management/.gitignore @@ -0,0 +1,2 @@ +.local/ +node_modules/ diff --git a/source/teaql-ts/examples/school-management/README.md b/source/teaql-ts/examples/school-management/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d780ba532760318c879711a25c3eb1263e0ccf71 --- /dev/null +++ b/source/teaql-ts/examples/school-management/README.md @@ -0,0 +1,31 @@ +# School Management example + +This retained SQLite example is generated from `model.xml`. It verifies repeated root/constant bootstrap, the post-constant ID floor, generated forward relations, and checker-fixed Update. + +The request-intent probe uses generated Q and audited-save APIs with logging +disabled. Blank comment/purpose must produce the runtime's stable request +errors without reaching SQL compilation. The library is regenerated from the +paired local generator; it is not manually patched. + +Current generated bootstrap uses a mutation-API `ensure` hook. A second retained +generated library in `src/reconciled` changes the model's Primary constant name +to `Primary School`. It runs against the first library's existing SQLite file; +two Ensure Schema calls must yield exactly version 2. No custom replacement +bootstrap or metadata-only override bypasses the managed generated program. + +This demo resets its SQLite test tables at startup. Running it twice is not +evidence of two starts without database cleanup; that stronger graph gate is +tracked separately. + +```bash +mkdir -p .local +npm install +npx ts-node app.ts +``` + +Expected result: + +```text +PASS TypeScript generated School request-intent gates +PASS TypeScript School Management: bootstrap, portable Query parity, relations, and Update +``` diff --git a/source/teaql-ts/examples/school-management/app.ts b/source/teaql-ts/examples/school-management/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..746d401f377edd979bd6d5d871cf554f1629cee8 --- /dev/null +++ b/source/teaql-ts/examples/school-management/app.ts @@ -0,0 +1,175 @@ +import { Q } from "./src/generated/Q"; +import { E } from "./src/generated/E"; +import { Platform } from "./src/generated/models/Platform"; +import { SchoolType } from "./src/generated/models/SchoolType"; +import { UserContext } from "./src/teaql-ts"; +import { normalizeDynamicSearch, SearchModel } from "teaql-ts"; +import { GENERATED_RUNTIME_MODULE } from "./src/runtime-module"; +import { SQLiteDriver, SQLiteTeaQLClient } from "./src/teaql-node-sqlite"; +import { mkdirSync } from "node:fs"; +import { verifyRequestIntent } from './request-intent'; +import { SQLiteTeaQLClient as ReconciledSQLiteTeaQLClient } from './src/reconciled/teaql-node-sqlite'; + +async function main(): Promise { + mkdirSync(".local", { recursive: true }); + const database = ".local/school.sqlite"; + const cleanup = new SQLiteDriver(database); + for (const table of ["school_data", "school_type_data", "platform_data", "teaql_id_space"]) { + await cleanup.query(`DROP TABLE IF EXISTS ${table}`); + } + await cleanup.close(); + + const client = new SQLiteTeaQLClient(database); + client.install(GENERATED_RUNTIME_MODULE); + const context = new UserContext().insertResource("dataService", client); + await context.ensureSchema(); + await context.ensureSchema(); + await verifyRequestIntent(context, client); + + const roots = await Q.platforms().comment("Read repeated root seed") + .purpose("Verify School bootstrap idempotency").executeForList(context); + const types = await Q.schoolTypes().comment("Read repeated constant seeds") + .purpose("Verify School bootstrap idempotency").executeForList(context); + if (roots.length !== 1 || roots[0].id !== "1") throw new Error("Platform(1) bootstrap is not idempotent"); + if (types.length !== 2 || !types.some(value => value.id === "1001") || !types.some(value => value.id === "1002")) { + throw new Error("SchoolType bootstrap is not idempotent"); + } + // Retained second generated library changes only Primary's presentation name. + // Its managed mutation bootstrap reconciles the existing SQLite file. + const changedClient = new ReconciledSQLiteTeaQLClient(database); + const changedContext = new UserContext().insertResource("dataService", changedClient); + await changedContext.ensureSchema(); + await changedContext.ensureSchema(); + const changedPrimary = await Q.schoolTypes().withIdIs("1001") + .comment("Read reconciled Primary constant") + .purpose("Verify versioned constant reconciliation") + .executeForOne(changedContext); + if (changedPrimary?.name !== "Primary School" || changedPrimary.version !== 2) { + throw new Error("Changed SchoolType constant was not reconciled exactly once"); + } + await changedClient.close(); + const extraType = Q.schoolTypes().comment("Create a post-bootstrap school type") + .purpose("Verify bootstrap ID floor").newEntity(context); + extraType.updatePlatform(Platform.refer("1")); + extraType.updateName("Other").updateCode("OTHER").updateDisplayOrder(3); + await extraType.auditAs("Verify SchoolType ID floor").save(context); + if (Number(extraType.id) <= 1002) throw new Error("SchoolType ID floor did not advance beyond 1002"); + + const school = Q.schools().comment("Create the example school") + .purpose("Verify generated TypeScript mutations").newEntity(context); + school.updatePlatform(Platform.refer("1")); + school.updateSchoolTypeToPrimary(); + school.updateName("Riverside Primary School"); + school.updateAddress("12 River Road, Springfield"); + school.updateEstablishedDate("1995-09-01"); + school.updateStudentCapacity(800); + school.updateActive(true); + await school.auditAs("Create Riverside Primary School").save(context); + + await verifyDynamicSearch(context); + const primarySchools = await Q.schools().withSchoolTypeIsPrimary() + .comment("Read schools linked through the PRIMARY helper") + .purpose("Verify constant helper mutation-ledger semantics") + .executeForList(context); + if (primarySchools.length !== 1 || E.school(primarySchools[0]).schoolTypeId().eval() !== "1001") { + throw new Error("PRIMARY helper did not persist and hydrate school_type=1001"); + } + + const loaded = await Q.schools().withIdIs(school.id) + .selectPlatformWith(Q.platformsWithMinimalFields().selectName().selectBaseUrl()) + .selectSchoolTypeWith(Q.schoolTypesWithMinimalFields().selectName().selectCode().selectDisplayOrder()) + .comment("Load a school with its forward relations") + .purpose("Verify generated forward relation metadata") + .executeForOne(context); + if (!loaded) throw new Error("School was not loaded"); + const platform = loaded.platform as Platform; + const schoolType = loaded.schoolType as SchoolType; + if (platform.name !== "Campus Learning Platform") { + throw new Error("Platform forward relation was not hydrated"); + } + if (schoolType.code !== "PRIMARY" || schoolType.displayOrder !== 1) { + throw new Error("SchoolType forward relation was not hydrated"); + } + + const queryCases: Array<[string, any, number]> = [ + ["string equality", Q.schools().withNameIs("Riverside Primary School"), 1], + ["string inequality", Q.schools().withNameIsNot("Another School"), 1], + ["string membership", Q.schools().withNameIn("Riverside Primary School", "Another School"), 1], + ["negative membership", Q.schools().withNameNotIn("Another School"), 1], + ["contains", Q.schools().withNameContaining("Primary"), 1], + ["negative contains", Q.schools().withNameNotContaining("Secondary"), 1], + ["starts with", Q.schools().withNameStartingWith("Riverside"), 1], + ["negative starts with", Q.schools().withNameNotStartingWith("Lakeside"), 1], + ["ends with", Q.schools().withNameEndingWith("School"), 1], + ["negative ends with", Q.schools().withNameNotEndingWith("Academy"), 1], + ["number range", Q.schools().withStudentCapacityBetween(700, 900), 1], + ["strict comparison", Q.schools().withStudentCapacityGreaterThan(799).withStudentCapacityLessThan(801), 1], + ["date range", Q.schools().withEstablishedDateBetween("1995-01-01", "1995-12-31"), 1], + ["known", Q.schools().withAddressIsKnown(), 1], + ["unknown", Q.schools().withAddressIsUnknown(), 0], + ["boolean true", Q.schools().whichAreActive(), 1], + ["boolean false", Q.schools().whichAreNotActive(), 0], + ["constant relation", Q.schools().withSchoolTypeIsPrimary(), 1], + ]; + for (const [label, request, expected] of queryCases) { + const result = await request.comment(`Query parity: ${label}`) + .purpose("Execute the shared School Query conformance case") + .executeForList(context); + if (result.length !== expected) throw new Error(`${label}: expected ${expected}, got ${result.length}`); + } + const projected = await Q.schools().selectName().orderByIdDescending() + .comment("Query parity: projection and ordering") + .purpose("Execute the shared School Query conformance case") + .executeForList(context); + if (projected.length !== 1 || projected[0].name !== "Riverside Primary School") { + throw new Error("projection/order query did not preserve typed School result"); + } + const previousVersion = loaded.version; + if (previousVersion === undefined) throw new Error("Loaded school has no version"); + loaded.updateName("Riverside Primary School — verified"); + await loaded.auditAs("Verify TypeScript update fixes").save(context); + if (loaded.version !== previousVersion + 1) throw new Error("Update did not advance version"); + const updated = await Q.schools().withIdIs(loaded.id) + .comment("Reload the updated school") + .purpose("Verify update_time fix and persisted mutation").executeForOne(context); + if (updated?.name !== "Riverside Primary School — verified") { + throw new Error("Updated school name was not persisted"); + } + console.log("PASS TypeScript School Management: bootstrap, portable Query parity, relations, and Update"); + await client.close(); +} + +async function verifyDynamicSearch(context: UserContext): Promise { + const models: Record = { + School: {fields: {name: "string"}, relations: {platform: "Platform"}}, + Platform: {fields: {name: "string"}, relations: {}}, + }; + const populated = {filter: {name: "Riverside Primary School", "platform.name": "Campus Learning Platform", + removed: "SECRET_VALUE", "platform.removed": "SECRET_VALUE"}, + orderBy: [{field: "removed", direction: "asc"}]}; + for (const authorizedPlatform of ["1", "2"]) { + for (const input of [populated, {}]) { + // Server authorization is independent from optional client search fields. + let request = Q.schools().withNameIs("Riverside Primary School") + .withPlatformMatching(Q.platforms().withIdIs(authorizedPlatform)); + const normalized = normalizeDynamicSearch(input, "School", models, () => {}); + for (const [field, predicate] of Object.entries(normalized.search.filter ?? {})) { + const value = (predicate as {$eq?: unknown}).$eq; + if (typeof value !== "string") throw new Error("Demo binding supports string equality only"); + if (field === "name") request = request.withNameIs(value); + else if (field === "platform.name") request = request.withPlatformMatching(Q.platforms().withNameIs(value)); + else throw new Error("Missing trusted demo binding"); + } + const rows = await request.orderByIdDescending().limit(2) + .comment("what: generated School dynamic search") + .purpose("why: preserve related authorization with stale or absent search fields") + .executeForList(context); + if (rows.length !== (authorizedPlatform === "1" ? 1 : 0)) throw new Error("Dynamic search bypassed scope"); + if (normalized.warnings.length !== (input === populated ? 3 : 0)) throw new Error("Drift warnings mismatch"); + if (JSON.stringify(normalized.warnings).includes("SECRET_VALUE")) throw new Error("Warning value leak"); + } + } + console.log("PASS TypeScript generated School dynamic search: independent related scope and typed Q bindings"); +} + +main().catch(error => { console.error(error); process.exit(1); }); diff --git a/source/teaql-ts/examples/school-management/model-reconciled.xml b/source/teaql-ts/examples/school-management/model-reconciled.xml new file mode 100644 index 0000000000000000000000000000000000000000..4710d8d688d3f22a3b82292d4f66a1bc19a72422 --- /dev/null +++ b/source/teaql-ts/examples/school-management/model-reconciled.xml @@ -0,0 +1,41 @@ + + + + + + <_value id="1001" name="Primary School" code="PRIMARY" display_order="1"/> + <_value id="1002" name="Secondary" code="SECONDARY" display_order="2"/> + + + + diff --git a/source/teaql-ts/examples/school-management/model.xml b/source/teaql-ts/examples/school-management/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..1f62a050cbc107478bebc0a360ab2b15d4fae9e4 --- /dev/null +++ b/source/teaql-ts/examples/school-management/model.xml @@ -0,0 +1,41 @@ + + + + + + <_value id="1001" name="Primary" code="PRIMARY" display_order="1"/> + <_value id="1002" name="Secondary" code="SECONDARY" display_order="2"/> + + + + diff --git a/source/teaql-ts/examples/school-management/package-lock.json b/source/teaql-ts/examples/school-management/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..23c5ae333ccb990be8cd81a64ca0da75d326e13b --- /dev/null +++ b/source/teaql-ts/examples/school-management/package-lock.json @@ -0,0 +1,828 @@ +{ + "name": "school-management-service-lib", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "school-management-service-lib", + "version": "1.0.0", + "dependencies": { + "better-sqlite3": "^12.10.0", + "teaql-ts": "file:../.." + }, + "devDependencies": { + "@types/better-sqlite3": "^7.6.12", + "@types/node": "^22.0.0", + "ts-node": "^10.9.2", + "typescript": "^5.0.0" + } + }, + "../..": { + "name": "@teaql/teaql", + "version": "0.3.1", + "license": "Apache-2.0", + "dependencies": { + "node-fetch": "^2.7.0" + }, + "devDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "@types/better-sqlite3": "^7.6.12", + "@types/jest": "^29.5.0", + "@types/node-fetch": "^2.6.13", + "@types/pg": "^8.11.0", + "better-sqlite3": "^12.10.0", + "esbuild": "^0.28.2", + "jest": "^29.5.0", + "jest-util": "^29.7.0", + "mysql2": "^3.11.0", + "peggy": "^5.1.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0", + "ts-jest": "^29.1.0", + "typescript": "5.4.5" + }, + "peerDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "better-sqlite3": "^12.10.0", + "expo-sqlite": "*", + "mysql2": "^3.11.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/s3-request-presigner": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/api-logs": { + "optional": true + }, + "@opentelemetry/context-async-hooks": { + "optional": true + }, + "@opentelemetry/core": { + "optional": true + }, + "@opentelemetry/exporter-logs-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-metrics-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-http": { + "optional": true + }, + "@opentelemetry/otlp-transformer": { + "optional": true + }, + "@opentelemetry/resources": { + "optional": true + }, + "@opentelemetry/sdk-logs": { + "optional": true + }, + "@opentelemetry/sdk-metrics": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "@sqlite.org/sqlite-wasm": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "expo-sqlite": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-query-stream": { + "optional": true + } + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.13.tgz", + "integrity": "sha512-gcLdvR9HO1ZJBypsOGqaP6TFEzb6vIta0KSTLt9NAQ6pXQO3cRgSVyCN6pzYqI9DlJgY71XKO0dpDhCf08b3pg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "22.20.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz", + "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true, + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "12.11.1", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", + "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/node-abi": { + "version": "3.95.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.95.0.tgz", + "integrity": "sha512-T9iGctuocf0qIWFFOTxPzjT5q0SILqaBYXt272tlBHvTKC5+3JnkMirLxNJNkXHtFyBjU2Jx+NL4Zipr0B/c6Q==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/teaql-ts": { + "resolved": "../..", + "link": true + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + } + } +} diff --git a/source/teaql-ts/examples/school-management/package.json b/source/teaql-ts/examples/school-management/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49bf2e86bd8b3e061035e74719d8df8a6d0b9ea6 --- /dev/null +++ b/source/teaql-ts/examples/school-management/package.json @@ -0,0 +1,17 @@ +{ + "name": "school-management-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "file:../..", + "better-sqlite3": "^12.10.0"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} diff --git a/source/teaql-ts/examples/school-management/request-intent.ts b/source/teaql-ts/examples/school-management/request-intent.ts new file mode 100644 index 0000000000000000000000000000000000000000..18a993e07eaa593e31cf56678c354b83b3214926 --- /dev/null +++ b/source/teaql-ts/examples/school-management/request-intent.ts @@ -0,0 +1,32 @@ +import { Q } from './src/generated/Q'; +import { UserContext } from './src/teaql-ts'; +import { SQLiteTeaQLClient } from './src/teaql-node-sqlite'; +import { RequestIntentError } from 'teaql-ts'; + +/** Application-owned probes; never patch the retained generated library. */ +export async function verifyRequestIntent(context: UserContext, client: SQLiteTeaQLClient): Promise { + client.setQueryLoggingEnabled(false).setMutationLoggingEnabled(false); + const before = client.sqlTrace.length; + const reject = async (execute: () => Promise, kind: 'query' | 'mutation', field: 'comment' | 'purpose') => { + try { await execute(); } + catch (error) { + if (!(error instanceof RequestIntentError) || error.requestKind !== kind || error.field !== field) throw error; + if (error.code !== (field === 'comment' ? 'REQUEST_COMMENT_REQUIRED' : 'QUERY_PURPOSE_REQUIRED')) throw error; + return; + } + throw new Error(`Missing ${kind} ${field} was accepted`); + }; + try { + await reject(() => Q.schools().limit(1).comment('').purpose('verify request gate').executeForList(context), 'query', 'comment'); + await reject(() => Q.schools().limit(1).comment('\u0085').purpose('verify request gate').executeForList(context), 'query', 'comment'); + await reject(() => Q.schools().limit(1).comment('verify request gate').purpose('').executeForList(context), 'query', 'purpose'); + await reject(() => Q.schools().limit(1).comment('verify request gate').purpose('\u0085').executeForList(context), 'query', 'purpose'); + const school = Q.schools().comment('construct rejected school').purpose('verify request gate').newEntity(context); + await reject(() => school.auditAs('').save(context), 'mutation', 'comment'); + await reject(() => school.auditAs('\u0085').save(context), 'mutation', 'comment'); + if (client.sqlTrace.length !== before) throw new Error('Invalid request reached SQL compilation'); + console.log('PASS TypeScript generated School request-intent gates'); + } finally { + client.setQueryLoggingEnabled(true).setMutationLoggingEnabled(true); + } +} diff --git a/source/teaql-ts/examples/school-management/src/generated-bootstrap.ts b/source/teaql-ts/examples/school-management/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3da68070cb03b66985d084711a3d4e417fb6d5a --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated-bootstrap.ts @@ -0,0 +1,48 @@ +import { UserContext } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Platform } from './generated/models/Platform'; +import { SchoolType } from './generated/models/SchoolType'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot.updateName("Campus Learning Platform"); + domainRoot.updateBaseUrl("https://campus.example.com"); + await domainRoot.auditAs('create generated Domain Root Platform').save(context); + } + context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! }); + let constantSchoolType1001 = (await Q.schoolTypes().withIdIs("1001").comment('what: locate generated constant SchoolType(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantSchoolType1001) { + constantSchoolType1001 = SchoolType.teaqlBootstrapNew("1001"); + constantSchoolType1001.updatePlatform(domainRoot); + constantSchoolType1001.updateName("Primary"); + constantSchoolType1001.updateCode("PRIMARY"); + constantSchoolType1001.updateDisplayOrder(1); + await constantSchoolType1001.auditAs('create model constant SchoolType(1001)').save(context); + } else { + let changed = false; + if (String((constantSchoolType1001.platform as any)?.id ?? constantSchoolType1001.platform) !== String(domainRoot.id)) { constantSchoolType1001.updatePlatform(domainRoot); changed = true; } + if (constantSchoolType1001.name !== "Primary") { constantSchoolType1001.updateName("Primary"); changed = true; } + if (constantSchoolType1001.code !== "PRIMARY") { constantSchoolType1001.updateCode("PRIMARY"); changed = true; } + if (constantSchoolType1001.displayOrder !== 1) { constantSchoolType1001.updateDisplayOrder(1); changed = true; } + if (changed) await constantSchoolType1001.auditAs('reconcile model constant SchoolType(1001)').save(context); + } + let constantSchoolType1002 = (await Q.schoolTypes().withIdIs("1002").comment('what: locate generated constant SchoolType(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantSchoolType1002) { + constantSchoolType1002 = SchoolType.teaqlBootstrapNew("1002"); + constantSchoolType1002.updatePlatform(domainRoot); + constantSchoolType1002.updateName("Secondary"); + constantSchoolType1002.updateCode("SECONDARY"); + constantSchoolType1002.updateDisplayOrder(2); + await constantSchoolType1002.auditAs('create model constant SchoolType(1002)').save(context); + } else { + let changed = false; + if (String((constantSchoolType1002.platform as any)?.id ?? constantSchoolType1002.platform) !== String(domainRoot.id)) { constantSchoolType1002.updatePlatform(domainRoot); changed = true; } + if (constantSchoolType1002.name !== "Secondary") { constantSchoolType1002.updateName("Secondary"); changed = true; } + if (constantSchoolType1002.code !== "SECONDARY") { constantSchoolType1002.updateCode("SECONDARY"); changed = true; } + if (constantSchoolType1002.displayOrder !== 2) { constantSchoolType1002.updateDisplayOrder(2); changed = true; } + if (changed) await constantSchoolType1002.auditAs('reconcile model constant SchoolType(1002)').save(context); + } +} diff --git a/source/teaql-ts/examples/school-management/src/generated-search-models.ts b/source/teaql-ts/examples/school-management/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4de27ef5dcdaee56b4e5f5b7b711929c22d1b18 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated-search-models.ts @@ -0,0 +1,100 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Platform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "base_url": "string" as const, + "baseUrl": "string" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "base_url": "baseUrl", + "baseUrl": "baseUrl", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "schoolTypeList": "SchoolType", + "schoolList": "School", + }), + }), + "SchoolType": Object.freeze({ + fields: Object.freeze({ + "platform": "integer" as const, + "id": "integer" as const, + "name": "string" as const, + "code": "string" as const, + "display_order": "decimal" as const, + "displayOrder": "decimal" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "platform": "platform", + "id": "id", + "name": "name", + "code": "code", + "display_order": "displayOrder", + "displayOrder": "displayOrder", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + "schoolList": "School", + }), + }), + "School": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "platform": "integer" as const, + "school_type": "integer" as const, + "schoolType": "integer" as const, + "name": "string" as const, + "address": "string" as const, + "established_date": "date" as const, + "establishedDate": "date" as const, + "student_capacity": "integer" as const, + "studentCapacity": "integer" as const, + "active": "boolean" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "platform": "platform", + "school_type": "schoolType", + "schoolType": "schoolType", + "name": "name", + "address": "address", + "established_date": "establishedDate", + "establishedDate": "establishedDate", + "student_capacity": "studentCapacity", + "studentCapacity": "studentCapacity", + "active": "active", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + "school_type": "SchoolType", + "schoolType": "SchoolType", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/E.ts b/source/teaql-ts/examples/school-management/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..3285a0035cf94d46b353d789edabd6cbe62a8265 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/E.ts @@ -0,0 +1,629 @@ +import { Platform } from './models/Platform'; +import { SchoolType } from './models/SchoolType'; +import { School } from './models/School'; + +export class TeaQLNotLoadedError extends Error { + readonly details: Record; + + constructor( + readonly root: string, + readonly accessPath: string, + readonly breakPoint: string, + ) { + const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; + const details = { + error: 'TeaQLNotLoadedError', + root, + accessPath: accessPath.split('.'), + breakPoint, + missingPreload: [breakPoint], + suggestedFix, + severity: 'error', + humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, + }; + super(JSON.stringify(details)); + this.name = 'TeaQLNotLoadedError'; + this.details = details; + } +} + +function expressionPath(prefix: string, field: string): string { + return prefix ? `${prefix}.${field}` : field; +} + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded; + return this.present; + } + + orElse(fallback: T): T { + const value = this.eval(); + return this.present && value != null ? value : fallback; + } +} + +export class PlatformExpression { + constructor( + private readonly value: Platform | null | undefined, + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Platform | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + baseUrl(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'baseUrl'); + if (!this.value.isLoaded('baseUrl')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'baseUrl'), + ); + } + return new ValueExpression(this.value.baseUrl); + } + + createTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'createTime'); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'createTime'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'updateTime'); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'updateTime'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + schoolTypeList(): SchoolTypeListExpression { + const path = expressionPath(this.path, 'schoolTypeList'); + if (this.notLoaded) { + return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolTypeListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolTypeList')) { + return new SchoolTypeListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolTypeList')); + } + return new SchoolTypeListExpression( + this.value.schoolTypeList(), this.root, path, + ); + } + + schoolList(): SchoolListExpression { + const path = expressionPath(this.path, 'schoolList'); + if (this.notLoaded) { + return new SchoolListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolList')) { + return new SchoolListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolList')); + } + return new SchoolListExpression( + this.value.schoolList(), this.root, path, + ); + } +} + +export class SchoolTypeExpression { + constructor( + private readonly value: SchoolType | null | undefined, + private readonly root = 'SchoolType(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): SchoolType | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + code(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'code'); + if (!this.value.isLoaded('code')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'code'), + ); + } + return new ValueExpression(this.value.code); + } + + displayOrder(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'displayOrder'); + if (!this.value.isLoaded('displayOrder')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'displayOrder'), + ); + } + return new ValueExpression(this.value.displayOrder); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'platform'); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = expressionPath(this.path, 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'platform')); + } + const relation = this.value.platform; + const target = relation == null + ? undefined + : relation instanceof Platform + ? relation + : Platform.fromRecord({ id: relation }); + return new PlatformExpression(target, this.root, path); + } + + schoolList(): SchoolListExpression { + const path = expressionPath(this.path, 'schoolList'); + if (this.notLoaded) { + return new SchoolListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolList')) { + return new SchoolListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolList')); + } + return new SchoolListExpression( + this.value.schoolList(), this.root, path, + ); + } +} + +export class SchoolExpression { + constructor( + private readonly value: School | null | undefined, + private readonly root = 'School(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): School | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + address(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'address'); + if (!this.value.isLoaded('address')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'address'), + ); + } + return new ValueExpression(this.value.address); + } + + establishedDate(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'establishedDate'); + if (!this.value.isLoaded('establishedDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'establishedDate'), + ); + } + return new ValueExpression(this.value.establishedDate); + } + + studentCapacity(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'studentCapacity'); + if (!this.value.isLoaded('studentCapacity')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'studentCapacity'), + ); + } + return new ValueExpression(this.value.studentCapacity); + } + + active(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'active'); + if (!this.value.isLoaded('active')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'active'), + ); + } + return new ValueExpression(this.value.active); + } + + createTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'createTime'); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'createTime'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'updateTime'); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'updateTime'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'platform'); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + schoolTypeId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'schoolType'); + if (!this.value.isLoaded('schoolType')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'schoolType'), + ); + } + const reference = this.value.schoolType; + return new ValueExpression( + reference instanceof SchoolType + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = expressionPath(this.path, 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'platform')); + } + const relation = this.value.platform; + const target = relation == null + ? undefined + : relation instanceof Platform + ? relation + : Platform.fromRecord({ id: relation }); + return new PlatformExpression(target, this.root, path); + } + + schoolType(): SchoolTypeExpression { + const path = expressionPath(this.path, 'schoolType'); + if (this.notLoaded) { + return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new SchoolTypeExpression(undefined, this.root, path); + if (!this.value.isLoaded('schoolType')) { + return new SchoolTypeExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'schoolType')); + } + const relation = this.value.schoolType; + const target = relation == null + ? undefined + : relation instanceof SchoolType + ? relation + : SchoolType.fromRecord({ id: relation }); + return new SchoolTypeExpression(target, this.root, path); + } + +} + +export class PlatformListExpression { + constructor( + private readonly items: readonly Platform[], + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): PlatformListExpression { + return new PlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): PlatformExpression { + return this.get(0); + } + + get(index: number): PlatformExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new PlatformExpression(undefined, this.root, itemPath) + : new PlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class SchoolTypeListExpression { + constructor( + private readonly items: readonly SchoolType[], + private readonly root = 'SchoolType(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): SchoolTypeListExpression { + return new SchoolTypeListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): SchoolTypeExpression { + return this.get(0); + } + + get(index: number): SchoolTypeExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new SchoolTypeExpression(undefined, this.root, itemPath) + : new SchoolTypeExpression(this.items[index], this.root, itemPath); + } +} + +export class SchoolListExpression { + constructor( + private readonly items: readonly School[], + private readonly root = 'School(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): SchoolListExpression { + return new SchoolListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): SchoolExpression { + return this.get(0); + } + + get(index: number): SchoolExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new SchoolExpression(undefined, this.root, itemPath) + : new SchoolExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static platform( + value: Platform | null | undefined, + ): PlatformExpression { + return new PlatformExpression( + value, `Platform(id=${value?.id ?? 'null'})`, + ); + } + + static schoolType( + value: SchoolType | null | undefined, + ): SchoolTypeExpression { + return new SchoolTypeExpression( + value, `SchoolType(id=${value?.id ?? 'null'})`, + ); + } + + static school( + value: School | null | undefined, + ): SchoolExpression { + return new SchoolExpression( + value, `School(id=${value?.id ?? 'null'})`, + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/Q.ts b/source/teaql-ts/examples/school-management/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..14bc3c4d047059343113a1d18f45876936ea2f3f --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/Q.ts @@ -0,0 +1,28 @@ +import { TeaQLClient } from '../teaql-ts'; +import { PlatformRequest } from './requests/PlatformRequest'; +import { SchoolTypeRequest } from './requests/SchoolTypeRequest'; +import { SchoolRequest } from './requests/SchoolRequest'; + +export class Q { + static platforms(): PlatformRequest { + return new PlatformRequest(false); + } + + static platformsWithMinimalFields(): PlatformRequest { + return new PlatformRequest(true); + } + static schoolTypes(): SchoolTypeRequest { + return new SchoolTypeRequest(false); + } + + static schoolTypesWithMinimalFields(): SchoolTypeRequest { + return new SchoolTypeRequest(true); + } + static schools(): SchoolRequest { + return new SchoolRequest(false); + } + + static schoolsWithMinimalFields(): SchoolRequest { + return new SchoolRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/models/Platform.ts b/source/teaql-ts/examples/school-management/src/generated/models/Platform.ts new file mode 100644 index 0000000000000000000000000000000000000000..6290c60e32711869d3b5361d5553bf014d622502 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/models/Platform.ts @@ -0,0 +1,349 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { SchoolType } from './SchoolType'; +import { School } from './School'; + +export class Platform { + private static teaqlTemporaryId = 0; + id?: string; + name?: string; + baseUrl?: string; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolTypeList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["schoolTypeList"]; + delete fields["schoolList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).schoolTypeList)) { + const selected = (init as any).schoolTypeList; + (this as any)._schoolTypeList = new SmartList(selected.map( + (child: unknown) => child instanceof SchoolType + ? child + : SchoolType.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolTypeList"); + } + if (Array.isArray((init as any).schoolList)) { + const selected = (init as any).schoolList; + (this as any)._schoolList = new SmartList(selected.map( + (child: unknown) => child instanceof School + ? child + : School.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Platform { + const entity = new Platform(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Platform { + return new Platform({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Platform { + return new Platform().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Platform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Platform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "base_url": this.baseUrl, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateBaseUrl(value: string): this { + this.baseUrl = value; + this.markLoaded("baseUrl"); + (this as any)._root.set(this.teaqlEntityKey(), "base_url", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + schoolTypeList(): SmartList { + return (this as any)._schoolTypeList; + } + + schoolList(): SmartList { + return (this as any)._schoolList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/models/School.ts b/source/teaql-ts/examples/school-management/src/generated/models/School.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0e0932d518e97acbecdeed78ef3e6749956f366 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/models/School.ts @@ -0,0 +1,302 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; +import { SchoolType } from './SchoolType'; + +export class School { + private static teaqlTemporaryId = 0; + id?: string; + platform?: Platform | string; + schoolType?: SchoolType | string; + name?: string; + address?: string; + establishedDate?: string; + studentCapacity?: number; + active?: boolean; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --School.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if ((init as any).schoolType && typeof (init as any).schoolType === "object") { + this.schoolType = (init as any).schoolType instanceof SchoolType + ? (init as any).schoolType + : SchoolType.fromRecord((init as any).schoolType); + this.markLoaded("schoolType"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "School", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): School { + const entity = new School(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): School { + return new School({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): School { + return new School().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "School", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "School", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "platform": this.platform, + "school_type": this.schoolType, + "name": this.name, + "address": this.address, + "established_date": this.establishedDate, + "student_capacity": this.studentCapacity, + "active": this.active, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateAddress(value: string): this { + this.address = value; + this.markLoaded("address"); + (this as any)._root.set(this.teaqlEntityKey(), "address", value); + return this; + } + + updateEstablishedDate(value: string): this { + this.establishedDate = value; + this.markLoaded("establishedDate"); + (this as any)._root.set(this.teaqlEntityKey(), "established_date", value); + return this; + } + + updateStudentCapacity(value: number): this { + this.studentCapacity = value; + this.markLoaded("studentCapacity"); + (this as any)._root.set(this.teaqlEntityKey(), "student_capacity", value); + return this; + } + + updateActive(value: boolean): this { + this.active = value; + this.markLoaded("active"); + (this as any)._root.set(this.teaqlEntityKey(), "active", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + + updateSchoolType(value: any): this { + this.schoolType = value?.id ?? value; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + public updateSchoolTypeToPrimary(): School { + this.schoolType = "1001"; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + public updateSchoolTypeToSecondary(): School { + this.schoolType = "1002"; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/models/SchoolType.ts b/source/teaql-ts/examples/school-management/src/generated/models/SchoolType.ts new file mode 100644 index 0000000000000000000000000000000000000000..0677cb7d71363977bb4b42d7d44bce7d089cc983 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/models/SchoolType.ts @@ -0,0 +1,296 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; +import { School } from './School'; + +export class SchoolType { + private static teaqlTemporaryId = 0; + platform?: Platform | string; + id?: string; + name?: string; + code?: string; + displayOrder?: number; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --SchoolType.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["schoolList"]; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if (Array.isArray((init as any).schoolList)) { + const selected = (init as any).schoolList; + (this as any)._schoolList = new SmartList(selected.map( + (child: unknown) => child instanceof School + ? child + : School.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "SchoolType", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): SchoolType { + const entity = new SchoolType(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): SchoolType { + return new SchoolType({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): SchoolType { + return new SchoolType().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "SchoolType", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "SchoolType", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "platform": this.platform, + "id": this.id, + "name": this.name, + "code": this.code, + "display_order": this.displayOrder, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateCode(value: string): this { + this.code = value; + this.markLoaded("code"); + (this as any)._root.set(this.teaqlEntityKey(), "code", value); + return this; + } + + updateDisplayOrder(value: number): this { + this.displayOrder = value; + this.markLoaded("displayOrder"); + (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + schoolList(): SmartList { + return (this as any)._schoolList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/school-management/src/generated/requests/PlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..af9cf03a986e08d02115cba30825e5e6b3bbfdf6 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/requests/PlatformRequest.ts @@ -0,0 +1,1161 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Platform } from '../models/Platform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class PlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Platform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutablePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutablePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "baseUrl", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectBaseUrl(): this { + this.query.select(["baseUrl"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectSchoolTypeListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolTypeList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectSchoolTypeListWith", relation: "schoolTypeList" }); + return this; + } + selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); + return this; + } + + haveSchoolTypes(): this { + return this.withSchoolTypeListMatching({ + toQuery: () => new SelectQuery("SchoolType"), + }); + } + + haveNoSchoolTypes(): this { + return this.withoutSchoolTypeListMatching({ + toQuery: () => new SelectQuery("SchoolType"), + }); + } + + withSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + haveSchools(): this { + return this.withSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + haveNoSchools(): this { + return this.withoutSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + countSchoolTypes(): this { + return this.countSchoolTypesAs("countSchoolTypes"); + } + + countSchoolTypesAs(alias: string): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + this.countSchoolTypesWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolTypesAs", relation: "schoolTypeList", alias }; + return this; + } + + countSchoolTypesWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "relation-count", method: "countSchoolTypesWith", relation: "schoolTypeList", alias }); + return this; + } + + minDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.minDisplayOrderOfSchoolTypesAs( + "minOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + minDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "minDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + maxDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.maxDisplayOrderOfSchoolTypesAs( + "maxOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + maxDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "maxDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + sumDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.sumDisplayOrderOfSchoolTypesAs( + "sumOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + sumDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "sumDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + avgDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.avgDisplayOrderOfSchoolTypesAs( + "avgOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + avgDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "avgDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + standardDeviationDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.standardDeviationDisplayOrderOfSchoolTypesAs( + "standardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs( + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + sampleVarianceDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceDisplayOrderOfSchoolTypesAs( + "sampleVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + samplePopulationVarianceDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceDisplayOrderOfSchoolTypesAs( + "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + countSchools(): this { + return this.countSchoolsAs("countSchools"); + } + + countSchoolsAs(alias: string): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + this.countSchoolsWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; + return this; + } + + countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "relation-count", method: "countSchoolsWith", relation: "schoolList", alias }); + return this; + } + + minStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.minStudentCapacityOfSchoolsAs( + "minOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "minStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + maxStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.maxStudentCapacityOfSchoolsAs( + "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "maxStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sumStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sumStudentCapacityOfSchoolsAs( + "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sumStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + avgStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.avgStudentCapacityOfSchoolsAs( + "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "avgStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + standardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.standardDeviationStudentCapacityOfSchoolsAs( + "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "standardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sampleVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceStudentCapacityOfSchoolsAs( + "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + samplePopulationVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( + "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withBaseUrlContaining(val: string): this { + this.filters.push({ "baseUrl": { "$contains": val } }); + return this; + } + + withBaseUrlIs(val: string): this { + this.filters.push({ "baseUrl": { "$eq": val } }); + return this; + } + + withBaseUrlIsNot(val: any): this { + this.filters.push({ "baseUrl": { "$ne": val } }); + return this; + } + + withBaseUrlIn(...vals: any[]): this { + this.filters.push({ "baseUrl": { "$in": vals } }); + return this; + } + + withBaseUrlNotIn(...vals: any[]): this { + this.filters.push({ "baseUrl": { "$notIn": vals } }); + return this; + } + + withBaseUrlGreaterThan(val: any): this { + this.filters.push({ "baseUrl": { "$gt": val } }); + return this; + } + + withBaseUrlGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "baseUrl": { "$gte": val } }); + return this; + } + + withBaseUrlLessThan(val: any): this { + this.filters.push({ "baseUrl": { "$lt": val } }); + return this; + } + + withBaseUrlLessThanOrEqualTo(val: any): this { + this.filters.push({ "baseUrl": { "$lte": val } }); + return this; + } + + withBaseUrlBetween(lower: any, upper: any): this { + this.filters.push({ "baseUrl": { "$between": [lower, upper] } }); + return this; + } + + withBaseUrlIsKnown(): this { + this.filters.push({ "baseUrl": { "$isNull": false } }); + return this; + } + + withBaseUrlIsUnknown(): this { + this.filters.push({ "baseUrl": { "$isNull": true } }); + return this; + } + withBaseUrlNotContaining(val: string): this { + this.filters.push({ "baseUrl": { "$notContains": val } }); + return this; + } + + withBaseUrlStartingWith(val: string): this { + this.filters.push({ "baseUrl": { "$startsWith": val } }); + return this; + } + + withBaseUrlNotStartingWith(val: string): this { + this.filters.push({ "baseUrl": { "$notStartsWith": val } }); + return this; + } + + withBaseUrlEndingWith(val: string): this { + this.filters.push({ "baseUrl": { "$endsWith": val } }); + return this; + } + + withBaseUrlNotEndingWith(val: string): this { + this.filters.push({ "baseUrl": { "$notEndsWith": val } }); + return this; + } + + withBaseUrlSoundingLike(val: string): this { + this.filters.push({ "baseUrl": { "$soundLike": val } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: any): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: any): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: any): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: any): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: any): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: any): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByBaseUrlAscending(): this { + this.query.orderBy("baseUrl", "asc"); + return this; + } + + orderByBaseUrlDescending(): this { + this.query.orderBy("baseUrl", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByBaseUrl(): this { + this.query.groupBy("baseUrl"); + return this; + } + + groupByBaseUrlAs(retName: string): this { + this.query.groupBy("baseUrl"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Platform + ? entity + : Platform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutablePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Platform { + this.ensureIntent(); + return new Platform(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/requests/SchoolRequest.ts b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..394ab2a4fb412ab2b2e47194914185b0857cf66b --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolRequest.ts @@ -0,0 +1,1260 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { School } from '../models/School'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class SchoolRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("School"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableSchoolRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableSchoolRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "platform", "schoolType", "name", "address", "establishedDate", "studentCapacity", "active", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectAddress(): this { + this.query.select(["address"]); + return this; + } + + selectEstablishedDate(): this { + this.query.select(["establishedDate"]); + return this; + } + + selectStudentCapacity(): this { + this.query.select(["studentCapacity"]); + return this; + } + + selectActive(): this { + this.query.select(["active"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + selectSchoolTypeWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["schoolType"]); + this.query.relationQuery( + "schoolType", request.toQuery(), "schoolType", "id", false, + { kind: "relation-select", method: "selectSchoolTypeWith", relation: "schoolType" }); + return this; + } + + withPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "schoolType": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "schoolType": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + filterBySchoolType(val: any): this { + this.filters.push({ "schoolType": { "$eq": val } }); + return this; + } + + filterBySchoolTypeIn(...vals: any[]): this { + this.filters.push({ "schoolType": { "$in": vals } }); + return this; + } + + withSchoolTypeIsKnown(): this { + this.filters.push({ "schoolType": { "$isNull": false } }); + return this; + } + + withSchoolTypeIsUnknown(): this { + this.filters.push({ "schoolType": { "$isNull": true } }); + return this; + } + withSchoolTypeIsPrimary(): this { + this.filters.push({ "schoolType": { "$eq": "1001" } }); + return this; + } + withSchoolTypeIsSecondary(): this { + this.filters.push({ "schoolType": { "$eq": "1002" } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withAddressContaining(val: string): this { + this.filters.push({ "address": { "$contains": val } }); + return this; + } + + withAddressIs(val: string): this { + this.filters.push({ "address": { "$eq": val } }); + return this; + } + + withAddressIsNot(val: any): this { + this.filters.push({ "address": { "$ne": val } }); + return this; + } + + withAddressIn(...vals: any[]): this { + this.filters.push({ "address": { "$in": vals } }); + return this; + } + + withAddressNotIn(...vals: any[]): this { + this.filters.push({ "address": { "$notIn": vals } }); + return this; + } + + withAddressGreaterThan(val: any): this { + this.filters.push({ "address": { "$gt": val } }); + return this; + } + + withAddressGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "address": { "$gte": val } }); + return this; + } + + withAddressLessThan(val: any): this { + this.filters.push({ "address": { "$lt": val } }); + return this; + } + + withAddressLessThanOrEqualTo(val: any): this { + this.filters.push({ "address": { "$lte": val } }); + return this; + } + + withAddressBetween(lower: any, upper: any): this { + this.filters.push({ "address": { "$between": [lower, upper] } }); + return this; + } + + withAddressIsKnown(): this { + this.filters.push({ "address": { "$isNull": false } }); + return this; + } + + withAddressIsUnknown(): this { + this.filters.push({ "address": { "$isNull": true } }); + return this; + } + withAddressNotContaining(val: string): this { + this.filters.push({ "address": { "$notContains": val } }); + return this; + } + + withAddressStartingWith(val: string): this { + this.filters.push({ "address": { "$startsWith": val } }); + return this; + } + + withAddressNotStartingWith(val: string): this { + this.filters.push({ "address": { "$notStartsWith": val } }); + return this; + } + + withAddressEndingWith(val: string): this { + this.filters.push({ "address": { "$endsWith": val } }); + return this; + } + + withAddressNotEndingWith(val: string): this { + this.filters.push({ "address": { "$notEndsWith": val } }); + return this; + } + + withAddressSoundingLike(val: string): this { + this.filters.push({ "address": { "$soundLike": val } }); + return this; + } + + withEstablishedDateIs(val: any): this { + this.filters.push({ "establishedDate": { "$eq": val } }); + return this; + } + + withEstablishedDateIsNot(val: any): this { + this.filters.push({ "establishedDate": { "$ne": val } }); + return this; + } + + withEstablishedDateIn(...vals: any[]): this { + this.filters.push({ "establishedDate": { "$in": vals } }); + return this; + } + + withEstablishedDateNotIn(...vals: any[]): this { + this.filters.push({ "establishedDate": { "$notIn": vals } }); + return this; + } + + withEstablishedDateGreaterThan(val: any): this { + this.filters.push({ "establishedDate": { "$gt": val } }); + return this; + } + + withEstablishedDateGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "establishedDate": { "$gte": val } }); + return this; + } + + withEstablishedDateLessThan(val: any): this { + this.filters.push({ "establishedDate": { "$lt": val } }); + return this; + } + + withEstablishedDateLessThanOrEqualTo(val: any): this { + this.filters.push({ "establishedDate": { "$lte": val } }); + return this; + } + + withEstablishedDateBetween(lower: any, upper: any): this { + this.filters.push({ "establishedDate": { "$between": [lower, upper] } }); + return this; + } + + withEstablishedDateIsKnown(): this { + this.filters.push({ "establishedDate": { "$isNull": false } }); + return this; + } + + withEstablishedDateIsUnknown(): this { + this.filters.push({ "establishedDate": { "$isNull": true } }); + return this; + } + + withStudentCapacityIs(val: any): this { + this.filters.push({ "studentCapacity": { "$eq": val } }); + return this; + } + + withStudentCapacityIsNot(val: any): this { + this.filters.push({ "studentCapacity": { "$ne": val } }); + return this; + } + + withStudentCapacityIn(...vals: any[]): this { + this.filters.push({ "studentCapacity": { "$in": vals } }); + return this; + } + + withStudentCapacityNotIn(...vals: any[]): this { + this.filters.push({ "studentCapacity": { "$notIn": vals } }); + return this; + } + + withStudentCapacityGreaterThan(val: any): this { + this.filters.push({ "studentCapacity": { "$gt": val } }); + return this; + } + + withStudentCapacityGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "studentCapacity": { "$gte": val } }); + return this; + } + + withStudentCapacityLessThan(val: any): this { + this.filters.push({ "studentCapacity": { "$lt": val } }); + return this; + } + + withStudentCapacityLessThanOrEqualTo(val: any): this { + this.filters.push({ "studentCapacity": { "$lte": val } }); + return this; + } + + withStudentCapacityBetween(lower: any, upper: any): this { + this.filters.push({ "studentCapacity": { "$between": [lower, upper] } }); + return this; + } + + withStudentCapacityIsKnown(): this { + this.filters.push({ "studentCapacity": { "$isNull": false } }); + return this; + } + + withStudentCapacityIsUnknown(): this { + this.filters.push({ "studentCapacity": { "$isNull": true } }); + return this; + } + + whichAreActive(): this { + this.filters.push({ "active": { "$eq": true } }); + return this; + } + + whichAreNotActive(): this { + this.filters.push({ "active": { "$eq": false } }); + return this; + } + withActiveIsNot(val: any): this { + this.filters.push({ "active": { "$ne": val } }); + return this; + } + + withActiveIn(...vals: any[]): this { + this.filters.push({ "active": { "$in": vals } }); + return this; + } + + withActiveNotIn(...vals: any[]): this { + this.filters.push({ "active": { "$notIn": vals } }); + return this; + } + + withActiveGreaterThan(val: any): this { + this.filters.push({ "active": { "$gt": val } }); + return this; + } + + withActiveGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "active": { "$gte": val } }); + return this; + } + + withActiveLessThan(val: any): this { + this.filters.push({ "active": { "$lt": val } }); + return this; + } + + withActiveLessThanOrEqualTo(val: any): this { + this.filters.push({ "active": { "$lte": val } }); + return this; + } + + withActiveBetween(lower: any, upper: any): this { + this.filters.push({ "active": { "$between": [lower, upper] } }); + return this; + } + + withActiveIsKnown(): this { + this.filters.push({ "active": { "$isNull": false } }); + return this; + } + + withActiveIsUnknown(): this { + this.filters.push({ "active": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: any): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: any): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: any): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: any): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: any): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: any): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByAddressAscending(): this { + this.query.orderBy("address", "asc"); + return this; + } + + orderByAddressDescending(): this { + this.query.orderBy("address", "desc"); + return this; + } + + orderByEstablishedDateAscending(): this { + this.query.orderBy("establishedDate", "asc"); + return this; + } + + orderByEstablishedDateDescending(): this { + this.query.orderBy("establishedDate", "desc"); + return this; + } + + orderByStudentCapacityAscending(): this { + this.query.orderBy("studentCapacity", "asc"); + return this; + } + + orderByStudentCapacityDescending(): this { + this.query.orderBy("studentCapacity", "desc"); + return this; + } + + orderByActiveAscending(): this { + this.query.orderBy("active", "asc"); + return this; + } + + orderByActiveDescending(): this { + this.query.orderBy("active", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minStudentCapacity(): this { + return this.minStudentCapacityAs("minOfStudentCapacity"); + } + + minStudentCapacityAs(retName: string): this { + this.query.aggregate("min", "studentCapacity", retName); + return this; + } + maxStudentCapacity(): this { + return this.maxStudentCapacityAs("maxOfStudentCapacity"); + } + + maxStudentCapacityAs(retName: string): this { + this.query.aggregate("max", "studentCapacity", retName); + return this; + } + sumStudentCapacity(): this { + return this.sumStudentCapacityAs("sumOfStudentCapacity"); + } + + sumStudentCapacityAs(retName: string): this { + this.query.aggregate("sum", "studentCapacity", retName); + return this; + } + avgStudentCapacity(): this { + return this.avgStudentCapacityAs("avgOfStudentCapacity"); + } + + avgStudentCapacityAs(retName: string): this { + this.query.aggregate("avg", "studentCapacity", retName); + return this; + } + standardDeviationStudentCapacity(): this { + return this.standardDeviationStudentCapacityAs("standardDeviationOfStudentCapacity"); + } + + standardDeviationStudentCapacityAs(retName: string): this { + this.query.aggregate("stddev", "studentCapacity", retName); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacity(): this { + return this.squareRootOfPopulationStandardDeviationStudentCapacityAs("squareRootOfPopulationStandardDeviationOfStudentCapacity"); + } + + squareRootOfPopulationStandardDeviationStudentCapacityAs(retName: string): this { + this.query.aggregate("stddev_pop", "studentCapacity", retName); + return this; + } + sampleVarianceStudentCapacity(): this { + return this.sampleVarianceStudentCapacityAs("sampleVarianceOfStudentCapacity"); + } + + sampleVarianceStudentCapacityAs(retName: string): this { + this.query.aggregate("var_samp", "studentCapacity", retName); + return this; + } + samplePopulationVarianceStudentCapacity(): this { + return this.samplePopulationVarianceStudentCapacityAs("samplePopulationVarianceOfStudentCapacity"); + } + + samplePopulationVarianceStudentCapacityAs(retName: string): this { + this.query.aggregate("var_pop", "studentCapacity", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } + + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform"); // In TS we don't alias group by yet natively + return this; + } + groupBySchoolType(): this { + this.query.groupBy("schoolType"); + return this; + } + + groupBySchoolTypeAs(retName: string): this { + this.query.groupBy("schoolType"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByAddress(): this { + this.query.groupBy("address"); + return this; + } + + groupByAddressAs(retName: string): this { + this.query.groupBy("address"); // In TS we don't alias group by yet natively + return this; + } + groupByEstablishedDate(): this { + this.query.groupBy("establishedDate"); + return this; + } + + groupByEstablishedDateAs(retName: string): this { + this.query.groupBy("establishedDate"); // In TS we don't alias group by yet natively + return this; + } + groupByStudentCapacity(): this { + this.query.groupBy("studentCapacity"); + return this; + } + + groupByStudentCapacityAs(retName: string): this { + this.query.groupBy("studentCapacity"); // In TS we don't alias group by yet natively + return this; + } + groupByActive(): this { + this.query.groupBy("active"); + return this; + } + + groupByActiveAs(retName: string): this { + this.query.groupBy("active"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByPlatformAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); + return this; + } + + facetBySchoolTypeAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "schoolType", request, includeAllFacets, + { kind: "facet", method: "facetBySchoolTypeAs", relation: "schoolType", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof School + ? row + : School.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof School + ? row + : School.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof School + ? entity + : School.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableSchoolRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): School { + this.ensureIntent(); + return new School(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/requests/SchoolTypeRequest.ts b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolTypeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d09b5f34a9b4b2aeee292bcfb05406959efef90 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolTypeRequest.ts @@ -0,0 +1,1037 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { SchoolType } from '../models/SchoolType'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class SchoolTypeRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("SchoolType"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableSchoolTypeRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableSchoolTypeRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["platform", "id", "name", "code", "displayOrder", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectCode(): this { + this.query.select(["code"]); + return this; + } + + selectDisplayOrder(): this { + this.query.select(["displayOrder"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + + withPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolList", request.toQuery(), "id", "schoolType", true, + { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); + return this; + } + + haveSchools(): this { + return this.withSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + haveNoSchools(): this { + return this.withoutSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "schoolType", + }, + }, + }); + return this; + } + + withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "schoolType", + }, + }, + }); + return this; + } + + countSchools(): this { + return this.countSchoolsAs("countSchools"); + } + + countSchoolsAs(alias: string): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + this.countSchoolsWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; + return this; + } + + countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "relation-count", method: "countSchoolsWith", relation: "schoolList", alias }); + return this; + } + + minStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.minStudentCapacityOfSchoolsAs( + "minOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "minStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + maxStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.maxStudentCapacityOfSchoolsAs( + "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "maxStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sumStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sumStudentCapacityOfSchoolsAs( + "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sumStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + avgStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.avgStudentCapacityOfSchoolsAs( + "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "avgStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + standardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.standardDeviationStudentCapacityOfSchoolsAs( + "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "standardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sampleVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceStudentCapacityOfSchoolsAs( + "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + samplePopulationVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( + "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withCodeContaining(val: string): this { + this.filters.push({ "code": { "$contains": val } }); + return this; + } + + withCodeIs(val: string): this { + this.filters.push({ "code": { "$eq": val } }); + return this; + } + + withCodeIsNot(val: any): this { + this.filters.push({ "code": { "$ne": val } }); + return this; + } + + withCodeIn(...vals: any[]): this { + this.filters.push({ "code": { "$in": vals } }); + return this; + } + + withCodeNotIn(...vals: any[]): this { + this.filters.push({ "code": { "$notIn": vals } }); + return this; + } + + withCodeGreaterThan(val: any): this { + this.filters.push({ "code": { "$gt": val } }); + return this; + } + + withCodeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "code": { "$gte": val } }); + return this; + } + + withCodeLessThan(val: any): this { + this.filters.push({ "code": { "$lt": val } }); + return this; + } + + withCodeLessThanOrEqualTo(val: any): this { + this.filters.push({ "code": { "$lte": val } }); + return this; + } + + withCodeBetween(lower: any, upper: any): this { + this.filters.push({ "code": { "$between": [lower, upper] } }); + return this; + } + + withCodeIsKnown(): this { + this.filters.push({ "code": { "$isNull": false } }); + return this; + } + + withCodeIsUnknown(): this { + this.filters.push({ "code": { "$isNull": true } }); + return this; + } + withCodeNotContaining(val: string): this { + this.filters.push({ "code": { "$notContains": val } }); + return this; + } + + withCodeStartingWith(val: string): this { + this.filters.push({ "code": { "$startsWith": val } }); + return this; + } + + withCodeNotStartingWith(val: string): this { + this.filters.push({ "code": { "$notStartsWith": val } }); + return this; + } + + withCodeEndingWith(val: string): this { + this.filters.push({ "code": { "$endsWith": val } }); + return this; + } + + withCodeNotEndingWith(val: string): this { + this.filters.push({ "code": { "$notEndsWith": val } }); + return this; + } + + withCodeSoundingLike(val: string): this { + this.filters.push({ "code": { "$soundLike": val } }); + return this; + } + + withDisplayOrderIs(val: any): this { + this.filters.push({ "displayOrder": { "$eq": val } }); + return this; + } + + withDisplayOrderIsNot(val: any): this { + this.filters.push({ "displayOrder": { "$ne": val } }); + return this; + } + + withDisplayOrderIn(...vals: any[]): this { + this.filters.push({ "displayOrder": { "$in": vals } }); + return this; + } + + withDisplayOrderNotIn(...vals: any[]): this { + this.filters.push({ "displayOrder": { "$notIn": vals } }); + return this; + } + + withDisplayOrderGreaterThan(val: any): this { + this.filters.push({ "displayOrder": { "$gt": val } }); + return this; + } + + withDisplayOrderGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$gte": val } }); + return this; + } + + withDisplayOrderLessThan(val: any): this { + this.filters.push({ "displayOrder": { "$lt": val } }); + return this; + } + + withDisplayOrderLessThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$lte": val } }); + return this; + } + + withDisplayOrderBetween(lower: any, upper: any): this { + this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); + return this; + } + + withDisplayOrderIsKnown(): this { + this.filters.push({ "displayOrder": { "$isNull": false } }); + return this; + } + + withDisplayOrderIsUnknown(): this { + this.filters.push({ "displayOrder": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByCodeAscending(): this { + this.query.orderBy("code", "asc"); + return this; + } + + orderByCodeDescending(): this { + this.query.orderBy("code", "desc"); + return this; + } + + orderByDisplayOrderAscending(): this { + this.query.orderBy("displayOrder", "asc"); + return this; + } + + orderByDisplayOrderDescending(): this { + this.query.orderBy("displayOrder", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minDisplayOrder(): this { + return this.minDisplayOrderAs("minOfDisplayOrder"); + } + + minDisplayOrderAs(retName: string): this { + this.query.aggregate("min", "displayOrder", retName); + return this; + } + maxDisplayOrder(): this { + return this.maxDisplayOrderAs("maxOfDisplayOrder"); + } + + maxDisplayOrderAs(retName: string): this { + this.query.aggregate("max", "displayOrder", retName); + return this; + } + sumDisplayOrder(): this { + return this.sumDisplayOrderAs("sumOfDisplayOrder"); + } + + sumDisplayOrderAs(retName: string): this { + this.query.aggregate("sum", "displayOrder", retName); + return this; + } + avgDisplayOrder(): this { + return this.avgDisplayOrderAs("avgOfDisplayOrder"); + } + + avgDisplayOrderAs(retName: string): this { + this.query.aggregate("avg", "displayOrder", retName); + return this; + } + standardDeviationDisplayOrder(): this { + return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder"); + } + + standardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev", "displayOrder", retName); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrder(): this { + return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder"); + } + + squareRootOfPopulationStandardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev_pop", "displayOrder", retName); + return this; + } + sampleVarianceDisplayOrder(): this { + return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder"); + } + + sampleVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_samp", "displayOrder", retName); + return this; + } + samplePopulationVarianceDisplayOrder(): this { + return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder"); + } + + samplePopulationVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_pop", "displayOrder", retName); + return this; + } + + // --- Group By --- + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } + + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform"); // In TS we don't alias group by yet natively + return this; + } + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByCode(): this { + this.query.groupBy("code"); + return this; + } + + groupByCodeAs(retName: string): this { + this.query.groupBy("code"); // In TS we don't alias group by yet natively + return this; + } + groupByDisplayOrder(): this { + this.query.groupBy("displayOrder"); + return this; + } + + groupByDisplayOrderAs(retName: string): this { + this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByPlatformAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof SchoolType + ? row + : SchoolType.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof SchoolType + ? row + : SchoolType.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof SchoolType + ? entity + : SchoolType.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableSchoolTypeRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): SchoolType { + this.ensureIntent(); + return new SchoolType(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated-bootstrap.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..238fab8253ff2d3df49ec3b3a1b77922e2b3b07f --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated-bootstrap.ts @@ -0,0 +1,48 @@ +import { UserContext } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Platform } from './generated/models/Platform'; +import { SchoolType } from './generated/models/SchoolType'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot.updateName("Campus Learning Platform"); + domainRoot.updateBaseUrl("https://campus.example.com"); + await domainRoot.auditAs('create generated Domain Root Platform').save(context); + } + context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! }); + let constantSchoolType1001 = (await Q.schoolTypes().withIdIs("1001").comment('what: locate generated constant SchoolType(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantSchoolType1001) { + constantSchoolType1001 = SchoolType.teaqlBootstrapNew("1001"); + constantSchoolType1001.updatePlatform(domainRoot); + constantSchoolType1001.updateName("Primary School"); + constantSchoolType1001.updateCode("PRIMARY"); + constantSchoolType1001.updateDisplayOrder(1); + await constantSchoolType1001.auditAs('create model constant SchoolType(1001)').save(context); + } else { + let changed = false; + if (String((constantSchoolType1001.platform as any)?.id ?? constantSchoolType1001.platform) !== String(domainRoot.id)) { constantSchoolType1001.updatePlatform(domainRoot); changed = true; } + if (constantSchoolType1001.name !== "Primary School") { constantSchoolType1001.updateName("Primary School"); changed = true; } + if (constantSchoolType1001.code !== "PRIMARY") { constantSchoolType1001.updateCode("PRIMARY"); changed = true; } + if (constantSchoolType1001.displayOrder !== 1) { constantSchoolType1001.updateDisplayOrder(1); changed = true; } + if (changed) await constantSchoolType1001.auditAs('reconcile model constant SchoolType(1001)').save(context); + } + let constantSchoolType1002 = (await Q.schoolTypes().withIdIs("1002").comment('what: locate generated constant SchoolType(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantSchoolType1002) { + constantSchoolType1002 = SchoolType.teaqlBootstrapNew("1002"); + constantSchoolType1002.updatePlatform(domainRoot); + constantSchoolType1002.updateName("Secondary"); + constantSchoolType1002.updateCode("SECONDARY"); + constantSchoolType1002.updateDisplayOrder(2); + await constantSchoolType1002.auditAs('create model constant SchoolType(1002)').save(context); + } else { + let changed = false; + if (String((constantSchoolType1002.platform as any)?.id ?? constantSchoolType1002.platform) !== String(domainRoot.id)) { constantSchoolType1002.updatePlatform(domainRoot); changed = true; } + if (constantSchoolType1002.name !== "Secondary") { constantSchoolType1002.updateName("Secondary"); changed = true; } + if (constantSchoolType1002.code !== "SECONDARY") { constantSchoolType1002.updateCode("SECONDARY"); changed = true; } + if (constantSchoolType1002.displayOrder !== 2) { constantSchoolType1002.updateDisplayOrder(2); changed = true; } + if (changed) await constantSchoolType1002.auditAs('reconcile model constant SchoolType(1002)').save(context); + } +} diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated-search-models.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4de27ef5dcdaee56b4e5f5b7b711929c22d1b18 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated-search-models.ts @@ -0,0 +1,100 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Platform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "base_url": "string" as const, + "baseUrl": "string" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "base_url": "baseUrl", + "baseUrl": "baseUrl", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "schoolTypeList": "SchoolType", + "schoolList": "School", + }), + }), + "SchoolType": Object.freeze({ + fields: Object.freeze({ + "platform": "integer" as const, + "id": "integer" as const, + "name": "string" as const, + "code": "string" as const, + "display_order": "decimal" as const, + "displayOrder": "decimal" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "platform": "platform", + "id": "id", + "name": "name", + "code": "code", + "display_order": "displayOrder", + "displayOrder": "displayOrder", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + "schoolList": "School", + }), + }), + "School": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "platform": "integer" as const, + "school_type": "integer" as const, + "schoolType": "integer" as const, + "name": "string" as const, + "address": "string" as const, + "established_date": "date" as const, + "establishedDate": "date" as const, + "student_capacity": "integer" as const, + "studentCapacity": "integer" as const, + "active": "boolean" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "platform": "platform", + "school_type": "schoolType", + "schoolType": "schoolType", + "name": "name", + "address": "address", + "established_date": "establishedDate", + "establishedDate": "establishedDate", + "student_capacity": "studentCapacity", + "studentCapacity": "studentCapacity", + "active": "active", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + "school_type": "SchoolType", + "schoolType": "SchoolType", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/E.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..3285a0035cf94d46b353d789edabd6cbe62a8265 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/E.ts @@ -0,0 +1,629 @@ +import { Platform } from './models/Platform'; +import { SchoolType } from './models/SchoolType'; +import { School } from './models/School'; + +export class TeaQLNotLoadedError extends Error { + readonly details: Record; + + constructor( + readonly root: string, + readonly accessPath: string, + readonly breakPoint: string, + ) { + const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; + const details = { + error: 'TeaQLNotLoadedError', + root, + accessPath: accessPath.split('.'), + breakPoint, + missingPreload: [breakPoint], + suggestedFix, + severity: 'error', + humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, + }; + super(JSON.stringify(details)); + this.name = 'TeaQLNotLoadedError'; + this.details = details; + } +} + +function expressionPath(prefix: string, field: string): string { + return prefix ? `${prefix}.${field}` : field; +} + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded; + return this.present; + } + + orElse(fallback: T): T { + const value = this.eval(); + return this.present && value != null ? value : fallback; + } +} + +export class PlatformExpression { + constructor( + private readonly value: Platform | null | undefined, + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Platform | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + baseUrl(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'baseUrl'); + if (!this.value.isLoaded('baseUrl')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'baseUrl'), + ); + } + return new ValueExpression(this.value.baseUrl); + } + + createTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'createTime'); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'createTime'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'updateTime'); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'updateTime'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + schoolTypeList(): SchoolTypeListExpression { + const path = expressionPath(this.path, 'schoolTypeList'); + if (this.notLoaded) { + return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolTypeListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolTypeList')) { + return new SchoolTypeListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolTypeList')); + } + return new SchoolTypeListExpression( + this.value.schoolTypeList(), this.root, path, + ); + } + + schoolList(): SchoolListExpression { + const path = expressionPath(this.path, 'schoolList'); + if (this.notLoaded) { + return new SchoolListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolList')) { + return new SchoolListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolList')); + } + return new SchoolListExpression( + this.value.schoolList(), this.root, path, + ); + } +} + +export class SchoolTypeExpression { + constructor( + private readonly value: SchoolType | null | undefined, + private readonly root = 'SchoolType(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): SchoolType | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + code(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'code'); + if (!this.value.isLoaded('code')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'code'), + ); + } + return new ValueExpression(this.value.code); + } + + displayOrder(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'displayOrder'); + if (!this.value.isLoaded('displayOrder')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'displayOrder'), + ); + } + return new ValueExpression(this.value.displayOrder); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'platform'); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = expressionPath(this.path, 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'platform')); + } + const relation = this.value.platform; + const target = relation == null + ? undefined + : relation instanceof Platform + ? relation + : Platform.fromRecord({ id: relation }); + return new PlatformExpression(target, this.root, path); + } + + schoolList(): SchoolListExpression { + const path = expressionPath(this.path, 'schoolList'); + if (this.notLoaded) { + return new SchoolListExpression([], this.root, path, false, this.notLoaded); + } + if (!this.value) return SchoolListExpression.missing(this.root, path); + if (!this.value.isLoaded('schoolList')) { + return new SchoolListExpression([], this.root, path, false, + new TeaQLNotLoadedError(this.root, path, 'schoolList')); + } + return new SchoolListExpression( + this.value.schoolList(), this.root, path, + ); + } +} + +export class SchoolExpression { + constructor( + private readonly value: School | null | undefined, + private readonly root = 'School(null)', + private readonly path = '', + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): School | null | undefined { + if (this.notLoaded) throw this.notLoaded; + return this.value; + } + + id(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'id'); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'name'); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + address(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'address'); + if (!this.value.isLoaded('address')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'address'), + ); + } + return new ValueExpression(this.value.address); + } + + establishedDate(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'establishedDate'); + if (!this.value.isLoaded('establishedDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'establishedDate'), + ); + } + return new ValueExpression(this.value.establishedDate); + } + + studentCapacity(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'studentCapacity'); + if (!this.value.isLoaded('studentCapacity')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'studentCapacity'), + ); + } + return new ValueExpression(this.value.studentCapacity); + } + + active(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'active'); + if (!this.value.isLoaded('active')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'active'), + ); + } + return new ValueExpression(this.value.active); + } + + createTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'createTime'); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'createTime'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'updateTime'); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'updateTime'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'version'); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'platform'); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + schoolTypeId(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (!this.value) return ValueExpression.missing(); + const path = expressionPath(this.path, 'schoolType'); + if (!this.value.isLoaded('schoolType')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(this.root, path, 'schoolType'), + ); + } + const reference = this.value.schoolType; + return new ValueExpression( + reference instanceof SchoolType + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = expressionPath(this.path, 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'platform')); + } + const relation = this.value.platform; + const target = relation == null + ? undefined + : relation instanceof Platform + ? relation + : Platform.fromRecord({ id: relation }); + return new PlatformExpression(target, this.root, path); + } + + schoolType(): SchoolTypeExpression { + const path = expressionPath(this.path, 'schoolType'); + if (this.notLoaded) { + return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded); + } + if (!this.value) return new SchoolTypeExpression(undefined, this.root, path); + if (!this.value.isLoaded('schoolType')) { + return new SchoolTypeExpression(undefined, this.root, path, + new TeaQLNotLoadedError(this.root, path, 'schoolType')); + } + const relation = this.value.schoolType; + const target = relation == null + ? undefined + : relation instanceof SchoolType + ? relation + : SchoolType.fromRecord({ id: relation }); + return new SchoolTypeExpression(target, this.root, path); + } + +} + +export class PlatformListExpression { + constructor( + private readonly items: readonly Platform[], + private readonly root = 'Platform(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): PlatformListExpression { + return new PlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): PlatformExpression { + return this.get(0); + } + + get(index: number): PlatformExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new PlatformExpression(undefined, this.root, itemPath) + : new PlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class SchoolTypeListExpression { + constructor( + private readonly items: readonly SchoolType[], + private readonly root = 'SchoolType(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): SchoolTypeListExpression { + return new SchoolTypeListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): SchoolTypeExpression { + return this.get(0); + } + + get(index: number): SchoolTypeExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new SchoolTypeExpression(undefined, this.root, itemPath) + : new SchoolTypeExpression(this.items[index], this.root, itemPath); + } +} + +export class SchoolListExpression { + constructor( + private readonly items: readonly School[], + private readonly root = 'School(null)', + private readonly path = '', + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ''): SchoolListExpression { + return new SchoolListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): SchoolExpression { + return this.get(0); + } + + get(index: number): SchoolExpression { + const itemPath = expressionPath(this.path, `get(${index})`); + if (this.notLoaded) { + return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded); + } + return !this.present || index < 0 || index >= this.items.length + ? new SchoolExpression(undefined, this.root, itemPath) + : new SchoolExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static platform( + value: Platform | null | undefined, + ): PlatformExpression { + return new PlatformExpression( + value, `Platform(id=${value?.id ?? 'null'})`, + ); + } + + static schoolType( + value: SchoolType | null | undefined, + ): SchoolTypeExpression { + return new SchoolTypeExpression( + value, `SchoolType(id=${value?.id ?? 'null'})`, + ); + } + + static school( + value: School | null | undefined, + ): SchoolExpression { + return new SchoolExpression( + value, `School(id=${value?.id ?? 'null'})`, + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/Q.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..14bc3c4d047059343113a1d18f45876936ea2f3f --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/Q.ts @@ -0,0 +1,28 @@ +import { TeaQLClient } from '../teaql-ts'; +import { PlatformRequest } from './requests/PlatformRequest'; +import { SchoolTypeRequest } from './requests/SchoolTypeRequest'; +import { SchoolRequest } from './requests/SchoolRequest'; + +export class Q { + static platforms(): PlatformRequest { + return new PlatformRequest(false); + } + + static platformsWithMinimalFields(): PlatformRequest { + return new PlatformRequest(true); + } + static schoolTypes(): SchoolTypeRequest { + return new SchoolTypeRequest(false); + } + + static schoolTypesWithMinimalFields(): SchoolTypeRequest { + return new SchoolTypeRequest(true); + } + static schools(): SchoolRequest { + return new SchoolRequest(false); + } + + static schoolsWithMinimalFields(): SchoolRequest { + return new SchoolRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/Platform.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/Platform.ts new file mode 100644 index 0000000000000000000000000000000000000000..6290c60e32711869d3b5361d5553bf014d622502 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/Platform.ts @@ -0,0 +1,349 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { SchoolType } from './SchoolType'; +import { School } from './School'; + +export class Platform { + private static teaqlTemporaryId = 0; + id?: string; + name?: string; + baseUrl?: string; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolTypeList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["schoolTypeList"]; + delete fields["schoolList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).schoolTypeList)) { + const selected = (init as any).schoolTypeList; + (this as any)._schoolTypeList = new SmartList(selected.map( + (child: unknown) => child instanceof SchoolType + ? child + : SchoolType.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolTypeList"); + } + if (Array.isArray((init as any).schoolList)) { + const selected = (init as any).schoolList; + (this as any)._schoolList = new SmartList(selected.map( + (child: unknown) => child instanceof School + ? child + : School.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Platform { + const entity = new Platform(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Platform { + return new Platform({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Platform { + return new Platform().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Platform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Platform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "base_url": this.baseUrl, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateBaseUrl(value: string): this { + this.baseUrl = value; + this.markLoaded("baseUrl"); + (this as any)._root.set(this.teaqlEntityKey(), "base_url", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + schoolTypeList(): SmartList { + return (this as any)._schoolTypeList; + } + + schoolList(): SmartList { + return (this as any)._schoolList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/School.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/School.ts new file mode 100644 index 0000000000000000000000000000000000000000..97ad757e263a8d123a8ab8c98088257003058861 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/School.ts @@ -0,0 +1,302 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; +import { SchoolType } from './SchoolType'; + +export class School { + private static teaqlTemporaryId = 0; + id?: string; + platform?: Platform | string; + schoolType?: SchoolType | string; + name?: string; + address?: string; + establishedDate?: string; + studentCapacity?: number; + active?: boolean; + createTime?: string; + updateTime?: string; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --School.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if ((init as any).schoolType && typeof (init as any).schoolType === "object") { + this.schoolType = (init as any).schoolType instanceof SchoolType + ? (init as any).schoolType + : SchoolType.fromRecord((init as any).schoolType); + this.markLoaded("schoolType"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "School", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): School { + const entity = new School(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): School { + return new School({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): School { + return new School().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "School", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "School", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "platform": this.platform, + "school_type": this.schoolType, + "name": this.name, + "address": this.address, + "established_date": this.establishedDate, + "student_capacity": this.studentCapacity, + "active": this.active, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateAddress(value: string): this { + this.address = value; + this.markLoaded("address"); + (this as any)._root.set(this.teaqlEntityKey(), "address", value); + return this; + } + + updateEstablishedDate(value: string): this { + this.establishedDate = value; + this.markLoaded("establishedDate"); + (this as any)._root.set(this.teaqlEntityKey(), "established_date", value); + return this; + } + + updateStudentCapacity(value: number): this { + this.studentCapacity = value; + this.markLoaded("studentCapacity"); + (this as any)._root.set(this.teaqlEntityKey(), "student_capacity", value); + return this; + } + + updateActive(value: boolean): this { + this.active = value; + this.markLoaded("active"); + (this as any)._root.set(this.teaqlEntityKey(), "active", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + + updateSchoolType(value: any): this { + this.schoolType = value?.id ?? value; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + public updateSchoolTypeToPrimarySchool(): School { + this.schoolType = "1001"; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + public updateSchoolTypeToSecondary(): School { + this.schoolType = "1002"; + this.markLoaded("schoolType"); + (this as any)._root.set(this.teaqlEntityKey(), "school_type", this.schoolType); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/SchoolType.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/SchoolType.ts new file mode 100644 index 0000000000000000000000000000000000000000..0677cb7d71363977bb4b42d7d44bce7d089cc983 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/SchoolType.ts @@ -0,0 +1,296 @@ +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; +import { School } from './School'; + +export class SchoolType { + private static teaqlTemporaryId = 0; + platform?: Platform | string; + id?: string; + name?: string; + code?: string; + displayOrder?: number; + version?: number; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --SchoolType.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["schoolList"]; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if (Array.isArray((init as any).schoolList)) { + const selected = (init as any).schoolList; + (this as any)._schoolList = new SmartList(selected.map( + (child: unknown) => child instanceof School + ? child + : School.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("schoolList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + } + + private teaqlEntityKey(): EntityKey { return { entity: "SchoolType", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): SchoolType { + const entity = new SchoolType(record as Partial); + return root ? entity.teaqlAttachRoot(root) : entity; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): SchoolType { + return new SchoolType({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): SchoolType { + return new SchoolType().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + new MutationIntent(comment); + (this as any)._comment = comment; + return this; + } + + async save(context: UserContext): Promise { + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); + }); + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "SchoolType", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, version: (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "SchoolType", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + return this; + } + const result = await service.executeMutation(request); + for (const [field, value] of Object.entries(mutation.payload as Record)) { + if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); + } + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + payload: this.teaqlMutationPayload(), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + service.afterGraphRollback(() => { + Object.assign(this, rollbackState.payload); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._schoolList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + }))); + } + } + service.afterGraphCommit(() => { + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "platform": this.platform, + "id": this.id, + "name": this.name, + "code": this.code, + "display_order": this.displayOrder, + "version": this.version + }; + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateCode(value: string): this { + this.code = value; + this.markLoaded("code"); + (this as any)._root.set(this.teaqlEntityKey(), "code", value); + return this; + } + + updateDisplayOrder(value: number): this { + this.displayOrder = value; + this.markLoaded("displayOrder"); + (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); + return this; + } + + updateVersion(value: number): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + schoolList(): SmartList { + return (this as any)._schoolList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..af9cf03a986e08d02115cba30825e5e6b3bbfdf6 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts @@ -0,0 +1,1161 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Platform } from '../models/Platform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class PlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Platform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutablePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutablePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "baseUrl", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectBaseUrl(): this { + this.query.select(["baseUrl"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectSchoolTypeListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolTypeList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectSchoolTypeListWith", relation: "schoolTypeList" }); + return this; + } + selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); + return this; + } + + haveSchoolTypes(): this { + return this.withSchoolTypeListMatching({ + toQuery: () => new SelectQuery("SchoolType"), + }); + } + + haveNoSchoolTypes(): this { + return this.withoutSchoolTypeListMatching({ + toQuery: () => new SelectQuery("SchoolType"), + }); + } + + withSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + haveSchools(): this { + return this.withSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + haveNoSchools(): this { + return this.withoutSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + countSchoolTypes(): this { + return this.countSchoolTypesAs("countSchoolTypes"); + } + + countSchoolTypesAs(alias: string): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + this.countSchoolTypesWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolTypesAs", relation: "schoolTypeList", alias }; + return this; + } + + countSchoolTypesWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "relation-count", method: "countSchoolTypesWith", relation: "schoolTypeList", alias }); + return this; + } + + minDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.minDisplayOrderOfSchoolTypesAs( + "minOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + minDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "minDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + maxDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.maxDisplayOrderOfSchoolTypesAs( + "maxOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + maxDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "maxDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + sumDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.sumDisplayOrderOfSchoolTypesAs( + "sumOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + sumDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "sumDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + avgDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.avgDisplayOrderOfSchoolTypesAs( + "avgOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + avgDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "avgDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + standardDeviationDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.standardDeviationDisplayOrderOfSchoolTypesAs( + "standardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs( + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + sampleVarianceDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceDisplayOrderOfSchoolTypesAs( + "sampleVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + samplePopulationVarianceDisplayOrderOfSchoolTypes(): this { + const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceDisplayOrderOfSchoolTypesAs( + "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + } + + samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "displayOrder", alias); + this.query.relationAggregate("schoolTypeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceDisplayOrderOfSchoolTypesAs", relation: "schoolTypeList", alias }); + return this; + } + countSchools(): this { + return this.countSchoolsAs("countSchools"); + } + + countSchoolsAs(alias: string): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + this.countSchoolsWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; + return this; + } + + countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "relation-count", method: "countSchoolsWith", relation: "schoolList", alias }); + return this; + } + + minStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.minStudentCapacityOfSchoolsAs( + "minOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "minStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + maxStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.maxStudentCapacityOfSchoolsAs( + "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "maxStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sumStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sumStudentCapacityOfSchoolsAs( + "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sumStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + avgStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.avgStudentCapacityOfSchoolsAs( + "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "avgStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + standardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.standardDeviationStudentCapacityOfSchoolsAs( + "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "standardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sampleVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceStudentCapacityOfSchoolsAs( + "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + samplePopulationVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( + "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withBaseUrlContaining(val: string): this { + this.filters.push({ "baseUrl": { "$contains": val } }); + return this; + } + + withBaseUrlIs(val: string): this { + this.filters.push({ "baseUrl": { "$eq": val } }); + return this; + } + + withBaseUrlIsNot(val: any): this { + this.filters.push({ "baseUrl": { "$ne": val } }); + return this; + } + + withBaseUrlIn(...vals: any[]): this { + this.filters.push({ "baseUrl": { "$in": vals } }); + return this; + } + + withBaseUrlNotIn(...vals: any[]): this { + this.filters.push({ "baseUrl": { "$notIn": vals } }); + return this; + } + + withBaseUrlGreaterThan(val: any): this { + this.filters.push({ "baseUrl": { "$gt": val } }); + return this; + } + + withBaseUrlGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "baseUrl": { "$gte": val } }); + return this; + } + + withBaseUrlLessThan(val: any): this { + this.filters.push({ "baseUrl": { "$lt": val } }); + return this; + } + + withBaseUrlLessThanOrEqualTo(val: any): this { + this.filters.push({ "baseUrl": { "$lte": val } }); + return this; + } + + withBaseUrlBetween(lower: any, upper: any): this { + this.filters.push({ "baseUrl": { "$between": [lower, upper] } }); + return this; + } + + withBaseUrlIsKnown(): this { + this.filters.push({ "baseUrl": { "$isNull": false } }); + return this; + } + + withBaseUrlIsUnknown(): this { + this.filters.push({ "baseUrl": { "$isNull": true } }); + return this; + } + withBaseUrlNotContaining(val: string): this { + this.filters.push({ "baseUrl": { "$notContains": val } }); + return this; + } + + withBaseUrlStartingWith(val: string): this { + this.filters.push({ "baseUrl": { "$startsWith": val } }); + return this; + } + + withBaseUrlNotStartingWith(val: string): this { + this.filters.push({ "baseUrl": { "$notStartsWith": val } }); + return this; + } + + withBaseUrlEndingWith(val: string): this { + this.filters.push({ "baseUrl": { "$endsWith": val } }); + return this; + } + + withBaseUrlNotEndingWith(val: string): this { + this.filters.push({ "baseUrl": { "$notEndsWith": val } }); + return this; + } + + withBaseUrlSoundingLike(val: string): this { + this.filters.push({ "baseUrl": { "$soundLike": val } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: any): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: any): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: any): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: any): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: any): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: any): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByBaseUrlAscending(): this { + this.query.orderBy("baseUrl", "asc"); + return this; + } + + orderByBaseUrlDescending(): this { + this.query.orderBy("baseUrl", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByBaseUrl(): this { + this.query.groupBy("baseUrl"); + return this; + } + + groupByBaseUrlAs(retName: string): this { + this.query.groupBy("baseUrl"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Platform + ? entity + : Platform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutablePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Platform { + this.ensureIntent(); + return new Platform(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1d1f11cae603fc771ec91ab1a91723a69b72a0e --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts @@ -0,0 +1,1260 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { School } from '../models/School'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class SchoolRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("School"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableSchoolRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableSchoolRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "platform", "schoolType", "name", "address", "establishedDate", "studentCapacity", "active", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectAddress(): this { + this.query.select(["address"]); + return this; + } + + selectEstablishedDate(): this { + this.query.select(["establishedDate"]); + return this; + } + + selectStudentCapacity(): this { + this.query.select(["studentCapacity"]); + return this; + } + + selectActive(): this { + this.query.select(["active"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + selectSchoolTypeWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["schoolType"]); + this.query.relationQuery( + "schoolType", request.toQuery(), "schoolType", "id", false, + { kind: "relation-select", method: "selectSchoolTypeWith", relation: "schoolType" }); + return this; + } + + withPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "schoolType": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "schoolType": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + filterBySchoolType(val: any): this { + this.filters.push({ "schoolType": { "$eq": val } }); + return this; + } + + filterBySchoolTypeIn(...vals: any[]): this { + this.filters.push({ "schoolType": { "$in": vals } }); + return this; + } + + withSchoolTypeIsKnown(): this { + this.filters.push({ "schoolType": { "$isNull": false } }); + return this; + } + + withSchoolTypeIsUnknown(): this { + this.filters.push({ "schoolType": { "$isNull": true } }); + return this; + } + withSchoolTypeIsPrimarySchool(): this { + this.filters.push({ "schoolType": { "$eq": "1001" } }); + return this; + } + withSchoolTypeIsSecondary(): this { + this.filters.push({ "schoolType": { "$eq": "1002" } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withAddressContaining(val: string): this { + this.filters.push({ "address": { "$contains": val } }); + return this; + } + + withAddressIs(val: string): this { + this.filters.push({ "address": { "$eq": val } }); + return this; + } + + withAddressIsNot(val: any): this { + this.filters.push({ "address": { "$ne": val } }); + return this; + } + + withAddressIn(...vals: any[]): this { + this.filters.push({ "address": { "$in": vals } }); + return this; + } + + withAddressNotIn(...vals: any[]): this { + this.filters.push({ "address": { "$notIn": vals } }); + return this; + } + + withAddressGreaterThan(val: any): this { + this.filters.push({ "address": { "$gt": val } }); + return this; + } + + withAddressGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "address": { "$gte": val } }); + return this; + } + + withAddressLessThan(val: any): this { + this.filters.push({ "address": { "$lt": val } }); + return this; + } + + withAddressLessThanOrEqualTo(val: any): this { + this.filters.push({ "address": { "$lte": val } }); + return this; + } + + withAddressBetween(lower: any, upper: any): this { + this.filters.push({ "address": { "$between": [lower, upper] } }); + return this; + } + + withAddressIsKnown(): this { + this.filters.push({ "address": { "$isNull": false } }); + return this; + } + + withAddressIsUnknown(): this { + this.filters.push({ "address": { "$isNull": true } }); + return this; + } + withAddressNotContaining(val: string): this { + this.filters.push({ "address": { "$notContains": val } }); + return this; + } + + withAddressStartingWith(val: string): this { + this.filters.push({ "address": { "$startsWith": val } }); + return this; + } + + withAddressNotStartingWith(val: string): this { + this.filters.push({ "address": { "$notStartsWith": val } }); + return this; + } + + withAddressEndingWith(val: string): this { + this.filters.push({ "address": { "$endsWith": val } }); + return this; + } + + withAddressNotEndingWith(val: string): this { + this.filters.push({ "address": { "$notEndsWith": val } }); + return this; + } + + withAddressSoundingLike(val: string): this { + this.filters.push({ "address": { "$soundLike": val } }); + return this; + } + + withEstablishedDateIs(val: any): this { + this.filters.push({ "establishedDate": { "$eq": val } }); + return this; + } + + withEstablishedDateIsNot(val: any): this { + this.filters.push({ "establishedDate": { "$ne": val } }); + return this; + } + + withEstablishedDateIn(...vals: any[]): this { + this.filters.push({ "establishedDate": { "$in": vals } }); + return this; + } + + withEstablishedDateNotIn(...vals: any[]): this { + this.filters.push({ "establishedDate": { "$notIn": vals } }); + return this; + } + + withEstablishedDateGreaterThan(val: any): this { + this.filters.push({ "establishedDate": { "$gt": val } }); + return this; + } + + withEstablishedDateGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "establishedDate": { "$gte": val } }); + return this; + } + + withEstablishedDateLessThan(val: any): this { + this.filters.push({ "establishedDate": { "$lt": val } }); + return this; + } + + withEstablishedDateLessThanOrEqualTo(val: any): this { + this.filters.push({ "establishedDate": { "$lte": val } }); + return this; + } + + withEstablishedDateBetween(lower: any, upper: any): this { + this.filters.push({ "establishedDate": { "$between": [lower, upper] } }); + return this; + } + + withEstablishedDateIsKnown(): this { + this.filters.push({ "establishedDate": { "$isNull": false } }); + return this; + } + + withEstablishedDateIsUnknown(): this { + this.filters.push({ "establishedDate": { "$isNull": true } }); + return this; + } + + withStudentCapacityIs(val: any): this { + this.filters.push({ "studentCapacity": { "$eq": val } }); + return this; + } + + withStudentCapacityIsNot(val: any): this { + this.filters.push({ "studentCapacity": { "$ne": val } }); + return this; + } + + withStudentCapacityIn(...vals: any[]): this { + this.filters.push({ "studentCapacity": { "$in": vals } }); + return this; + } + + withStudentCapacityNotIn(...vals: any[]): this { + this.filters.push({ "studentCapacity": { "$notIn": vals } }); + return this; + } + + withStudentCapacityGreaterThan(val: any): this { + this.filters.push({ "studentCapacity": { "$gt": val } }); + return this; + } + + withStudentCapacityGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "studentCapacity": { "$gte": val } }); + return this; + } + + withStudentCapacityLessThan(val: any): this { + this.filters.push({ "studentCapacity": { "$lt": val } }); + return this; + } + + withStudentCapacityLessThanOrEqualTo(val: any): this { + this.filters.push({ "studentCapacity": { "$lte": val } }); + return this; + } + + withStudentCapacityBetween(lower: any, upper: any): this { + this.filters.push({ "studentCapacity": { "$between": [lower, upper] } }); + return this; + } + + withStudentCapacityIsKnown(): this { + this.filters.push({ "studentCapacity": { "$isNull": false } }); + return this; + } + + withStudentCapacityIsUnknown(): this { + this.filters.push({ "studentCapacity": { "$isNull": true } }); + return this; + } + + whichAreActive(): this { + this.filters.push({ "active": { "$eq": true } }); + return this; + } + + whichAreNotActive(): this { + this.filters.push({ "active": { "$eq": false } }); + return this; + } + withActiveIsNot(val: any): this { + this.filters.push({ "active": { "$ne": val } }); + return this; + } + + withActiveIn(...vals: any[]): this { + this.filters.push({ "active": { "$in": vals } }); + return this; + } + + withActiveNotIn(...vals: any[]): this { + this.filters.push({ "active": { "$notIn": vals } }); + return this; + } + + withActiveGreaterThan(val: any): this { + this.filters.push({ "active": { "$gt": val } }); + return this; + } + + withActiveGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "active": { "$gte": val } }); + return this; + } + + withActiveLessThan(val: any): this { + this.filters.push({ "active": { "$lt": val } }); + return this; + } + + withActiveLessThanOrEqualTo(val: any): this { + this.filters.push({ "active": { "$lte": val } }); + return this; + } + + withActiveBetween(lower: any, upper: any): this { + this.filters.push({ "active": { "$between": [lower, upper] } }); + return this; + } + + withActiveIsKnown(): this { + this.filters.push({ "active": { "$isNull": false } }); + return this; + } + + withActiveIsUnknown(): this { + this.filters.push({ "active": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: any): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: any): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: any[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: any): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: any): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: any): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: any): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: any[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: any): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: any): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: any): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: any, upper: any): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByAddressAscending(): this { + this.query.orderBy("address", "asc"); + return this; + } + + orderByAddressDescending(): this { + this.query.orderBy("address", "desc"); + return this; + } + + orderByEstablishedDateAscending(): this { + this.query.orderBy("establishedDate", "asc"); + return this; + } + + orderByEstablishedDateDescending(): this { + this.query.orderBy("establishedDate", "desc"); + return this; + } + + orderByStudentCapacityAscending(): this { + this.query.orderBy("studentCapacity", "asc"); + return this; + } + + orderByStudentCapacityDescending(): this { + this.query.orderBy("studentCapacity", "desc"); + return this; + } + + orderByActiveAscending(): this { + this.query.orderBy("active", "asc"); + return this; + } + + orderByActiveDescending(): this { + this.query.orderBy("active", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minStudentCapacity(): this { + return this.minStudentCapacityAs("minOfStudentCapacity"); + } + + minStudentCapacityAs(retName: string): this { + this.query.aggregate("min", "studentCapacity", retName); + return this; + } + maxStudentCapacity(): this { + return this.maxStudentCapacityAs("maxOfStudentCapacity"); + } + + maxStudentCapacityAs(retName: string): this { + this.query.aggregate("max", "studentCapacity", retName); + return this; + } + sumStudentCapacity(): this { + return this.sumStudentCapacityAs("sumOfStudentCapacity"); + } + + sumStudentCapacityAs(retName: string): this { + this.query.aggregate("sum", "studentCapacity", retName); + return this; + } + avgStudentCapacity(): this { + return this.avgStudentCapacityAs("avgOfStudentCapacity"); + } + + avgStudentCapacityAs(retName: string): this { + this.query.aggregate("avg", "studentCapacity", retName); + return this; + } + standardDeviationStudentCapacity(): this { + return this.standardDeviationStudentCapacityAs("standardDeviationOfStudentCapacity"); + } + + standardDeviationStudentCapacityAs(retName: string): this { + this.query.aggregate("stddev", "studentCapacity", retName); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacity(): this { + return this.squareRootOfPopulationStandardDeviationStudentCapacityAs("squareRootOfPopulationStandardDeviationOfStudentCapacity"); + } + + squareRootOfPopulationStandardDeviationStudentCapacityAs(retName: string): this { + this.query.aggregate("stddev_pop", "studentCapacity", retName); + return this; + } + sampleVarianceStudentCapacity(): this { + return this.sampleVarianceStudentCapacityAs("sampleVarianceOfStudentCapacity"); + } + + sampleVarianceStudentCapacityAs(retName: string): this { + this.query.aggregate("var_samp", "studentCapacity", retName); + return this; + } + samplePopulationVarianceStudentCapacity(): this { + return this.samplePopulationVarianceStudentCapacityAs("samplePopulationVarianceOfStudentCapacity"); + } + + samplePopulationVarianceStudentCapacityAs(retName: string): this { + this.query.aggregate("var_pop", "studentCapacity", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } + + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform"); // In TS we don't alias group by yet natively + return this; + } + groupBySchoolType(): this { + this.query.groupBy("schoolType"); + return this; + } + + groupBySchoolTypeAs(retName: string): this { + this.query.groupBy("schoolType"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByAddress(): this { + this.query.groupBy("address"); + return this; + } + + groupByAddressAs(retName: string): this { + this.query.groupBy("address"); // In TS we don't alias group by yet natively + return this; + } + groupByEstablishedDate(): this { + this.query.groupBy("establishedDate"); + return this; + } + + groupByEstablishedDateAs(retName: string): this { + this.query.groupBy("establishedDate"); // In TS we don't alias group by yet natively + return this; + } + groupByStudentCapacity(): this { + this.query.groupBy("studentCapacity"); + return this; + } + + groupByStudentCapacityAs(retName: string): this { + this.query.groupBy("studentCapacity"); // In TS we don't alias group by yet natively + return this; + } + groupByActive(): this { + this.query.groupBy("active"); + return this; + } + + groupByActiveAs(retName: string): this { + this.query.groupBy("active"); // In TS we don't alias group by yet natively + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByPlatformAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); + return this; + } + + facetBySchoolTypeAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "schoolType", request, includeAllFacets, + { kind: "facet", method: "facetBySchoolTypeAs", relation: "schoolType", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof School + ? row + : School.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof School + ? row + : School.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof School + ? entity + : School.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableSchoolRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): School { + this.ensureIntent(); + return new School(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d09b5f34a9b4b2aeee292bcfb05406959efef90 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts @@ -0,0 +1,1037 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { SchoolType } from '../models/SchoolType'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class SchoolTypeRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("SchoolType"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableSchoolTypeRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableSchoolTypeRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["platform", "id", "name", "code", "displayOrder", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectCode(): this { + this.query.select(["code"]); + return this; + } + + selectDisplayOrder(): this { + this.query.select(["displayOrder"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + + withPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "schoolList", request.toQuery(), "id", "schoolType", true, + { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); + return this; + } + + haveSchools(): this { + return this.withSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + haveNoSchools(): this { + return this.withoutSchoolListMatching({ + toQuery: () => new SelectQuery("School"), + }); + } + + withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "schoolType", + }, + }, + }); + return this; + } + + withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "schoolType", + }, + }, + }); + return this; + } + + countSchools(): this { + return this.countSchoolsAs("countSchools"); + } + + countSchoolsAs(alias: string): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + this.countSchoolsWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; + return this; + } + + countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "relation-count", method: "countSchoolsWith", relation: "schoolList", alias }); + return this; + } + + minStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.minStudentCapacityOfSchoolsAs( + "minOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "minStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + maxStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.maxStudentCapacityOfSchoolsAs( + "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "maxStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sumStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sumStudentCapacityOfSchoolsAs( + "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sumStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + avgStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.avgStudentCapacityOfSchoolsAs( + "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "avgStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + standardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.standardDeviationStudentCapacityOfSchoolsAs( + "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "standardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + sampleVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceStudentCapacityOfSchoolsAs( + "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + samplePopulationVarianceStudentCapacityOfSchools(): this { + const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( + "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + } + + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "studentCapacity", alias); + this.query.relationAggregate("schoolList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceStudentCapacityOfSchoolsAs", relation: "schoolList", alias }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withCodeContaining(val: string): this { + this.filters.push({ "code": { "$contains": val } }); + return this; + } + + withCodeIs(val: string): this { + this.filters.push({ "code": { "$eq": val } }); + return this; + } + + withCodeIsNot(val: any): this { + this.filters.push({ "code": { "$ne": val } }); + return this; + } + + withCodeIn(...vals: any[]): this { + this.filters.push({ "code": { "$in": vals } }); + return this; + } + + withCodeNotIn(...vals: any[]): this { + this.filters.push({ "code": { "$notIn": vals } }); + return this; + } + + withCodeGreaterThan(val: any): this { + this.filters.push({ "code": { "$gt": val } }); + return this; + } + + withCodeGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "code": { "$gte": val } }); + return this; + } + + withCodeLessThan(val: any): this { + this.filters.push({ "code": { "$lt": val } }); + return this; + } + + withCodeLessThanOrEqualTo(val: any): this { + this.filters.push({ "code": { "$lte": val } }); + return this; + } + + withCodeBetween(lower: any, upper: any): this { + this.filters.push({ "code": { "$between": [lower, upper] } }); + return this; + } + + withCodeIsKnown(): this { + this.filters.push({ "code": { "$isNull": false } }); + return this; + } + + withCodeIsUnknown(): this { + this.filters.push({ "code": { "$isNull": true } }); + return this; + } + withCodeNotContaining(val: string): this { + this.filters.push({ "code": { "$notContains": val } }); + return this; + } + + withCodeStartingWith(val: string): this { + this.filters.push({ "code": { "$startsWith": val } }); + return this; + } + + withCodeNotStartingWith(val: string): this { + this.filters.push({ "code": { "$notStartsWith": val } }); + return this; + } + + withCodeEndingWith(val: string): this { + this.filters.push({ "code": { "$endsWith": val } }); + return this; + } + + withCodeNotEndingWith(val: string): this { + this.filters.push({ "code": { "$notEndsWith": val } }); + return this; + } + + withCodeSoundingLike(val: string): this { + this.filters.push({ "code": { "$soundLike": val } }); + return this; + } + + withDisplayOrderIs(val: any): this { + this.filters.push({ "displayOrder": { "$eq": val } }); + return this; + } + + withDisplayOrderIsNot(val: any): this { + this.filters.push({ "displayOrder": { "$ne": val } }); + return this; + } + + withDisplayOrderIn(...vals: any[]): this { + this.filters.push({ "displayOrder": { "$in": vals } }); + return this; + } + + withDisplayOrderNotIn(...vals: any[]): this { + this.filters.push({ "displayOrder": { "$notIn": vals } }); + return this; + } + + withDisplayOrderGreaterThan(val: any): this { + this.filters.push({ "displayOrder": { "$gt": val } }); + return this; + } + + withDisplayOrderGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$gte": val } }); + return this; + } + + withDisplayOrderLessThan(val: any): this { + this.filters.push({ "displayOrder": { "$lt": val } }); + return this; + } + + withDisplayOrderLessThanOrEqualTo(val: any): this { + this.filters.push({ "displayOrder": { "$lte": val } }); + return this; + } + + withDisplayOrderBetween(lower: any, upper: any): this { + this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); + return this; + } + + withDisplayOrderIsKnown(): this { + this.filters.push({ "displayOrder": { "$isNull": false } }); + return this; + } + + withDisplayOrderIsUnknown(): this { + this.filters.push({ "displayOrder": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByCodeAscending(): this { + this.query.orderBy("code", "asc"); + return this; + } + + orderByCodeDescending(): this { + this.query.orderBy("code", "desc"); + return this; + } + + orderByDisplayOrderAscending(): this { + this.query.orderBy("displayOrder", "asc"); + return this; + } + + orderByDisplayOrderDescending(): this { + this.query.orderBy("displayOrder", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minDisplayOrder(): this { + return this.minDisplayOrderAs("minOfDisplayOrder"); + } + + minDisplayOrderAs(retName: string): this { + this.query.aggregate("min", "displayOrder", retName); + return this; + } + maxDisplayOrder(): this { + return this.maxDisplayOrderAs("maxOfDisplayOrder"); + } + + maxDisplayOrderAs(retName: string): this { + this.query.aggregate("max", "displayOrder", retName); + return this; + } + sumDisplayOrder(): this { + return this.sumDisplayOrderAs("sumOfDisplayOrder"); + } + + sumDisplayOrderAs(retName: string): this { + this.query.aggregate("sum", "displayOrder", retName); + return this; + } + avgDisplayOrder(): this { + return this.avgDisplayOrderAs("avgOfDisplayOrder"); + } + + avgDisplayOrderAs(retName: string): this { + this.query.aggregate("avg", "displayOrder", retName); + return this; + } + standardDeviationDisplayOrder(): this { + return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder"); + } + + standardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev", "displayOrder", retName); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrder(): this { + return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder"); + } + + squareRootOfPopulationStandardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("stddev_pop", "displayOrder", retName); + return this; + } + sampleVarianceDisplayOrder(): this { + return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder"); + } + + sampleVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_samp", "displayOrder", retName); + return this; + } + samplePopulationVarianceDisplayOrder(): this { + return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder"); + } + + samplePopulationVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("var_pop", "displayOrder", retName); + return this; + } + + // --- Group By --- + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } + + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform"); // In TS we don't alias group by yet natively + return this; + } + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByCode(): this { + this.query.groupBy("code"); + return this; + } + + groupByCodeAs(retName: string): this { + this.query.groupBy("code"); // In TS we don't alias group by yet natively + return this; + } + groupByDisplayOrder(): this { + this.query.groupBy("displayOrder"); + return this; + } + + groupByDisplayOrderAs(retName: string): this { + this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByPlatformAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof SchoolType + ? row + : SchoolType.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof SchoolType + ? row + : SchoolType.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof SchoolType + ? entity + : SchoolType.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableSchoolTypeRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): SchoolType { + this.ensureIntent(); + return new SchoolType(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/runtime-module.ts b/source/teaql-ts/examples/school-management/src/reconciled/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f85334eadcd8cf4c401500f53cdb51ca806f9b5 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/runtime-module.ts @@ -0,0 +1,150 @@ +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-schemas"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Platform": Object.freeze({ + entityType: "Platform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "base_url": Object.freeze({ canonicalName: "base_url", wireName: "baseUrl", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "SchoolType": Object.freeze({ + entityType: "SchoolType", + profile: "camelCase" as const, + fields: Object.freeze({ + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "code": Object.freeze({ canonicalName: "code", wireName: "code", aliases: Object.freeze([] as string[]) }), + "display_order": Object.freeze({ canonicalName: "display_order", wireName: "displayOrder", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "School": Object.freeze({ + entityType: "School", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "school_type": Object.freeze({ canonicalName: "school_type", wireName: "schoolType", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "address": Object.freeze({ canonicalName: "address", wireName: "address", aliases: Object.freeze([] as string[]) }), + "established_date": Object.freeze({ canonicalName: "established_date", wireName: "establishedDate", aliases: Object.freeze([] as string[]) }), + "student_capacity": Object.freeze({ canonicalName: "student_capacity", wireName: "studentCapacity", aliases: Object.freeze([] as string[]) }), + "active": Object.freeze({ canonicalName: "active", wireName: "active", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Platform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["base_url"] === undefined) || mutation.payload["base_url"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("base_url") }); + if (mutation.payload["base_url"] != null && [...String(mutation.payload["base_url"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("base_url"), inputValue: mutation.payload["base_url"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "SchoolType": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["code"] === undefined) || mutation.payload["code"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("code") }); + if (mutation.payload["code"] != null && [...String(mutation.payload["code"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("code"), inputValue: mutation.payload["code"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["display_order"] === undefined) || mutation.payload["display_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("display_order") }); + + + }, + }, + "School": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + if ((mutation.action === "Create" && mutation.payload["school_type"] === undefined) || mutation.payload["school_type"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("school_type") }); + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["address"] === undefined) || mutation.payload["address"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("address") }); + if (mutation.payload["address"] != null && [...String(mutation.payload["address"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("address"), inputValue: mutation.payload["address"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["established_date"] === undefined) || mutation.payload["established_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("established_date") }); + + if ((mutation.action === "Create" && mutation.payload["student_capacity"] === undefined) || mutation.payload["student_capacity"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("student_capacity") }); + + if ((mutation.action === "Create" && mutation.payload["active"] === undefined) || mutation.payload["active"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("active") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Campus Learning Platform", "baseUrl": "https://campus.example.com", "createTime": "createTime()", "updateTime": "updateTime()" } }, + constants: [ + { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary School", "code": "PRIMARY", "displayOrder": 1 } }, + { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": 2 } } + ] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/teaql-node-sql.ts b/source/teaql-ts/examples/school-management/src/reconciled/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c4af67824ab9c6712d12cb9c231db91c4731e3f --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/teaql-node-sql.ts @@ -0,0 +1,22 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "baseUrl": { columnName: "base_url", modelName: "base_url", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"schoolTypeList": { targetEntity: "SchoolType", localKey: "id", foreignKey: "platform", many: true }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "platform", many: true }} +}, +"SchoolType": { + table: "school_type_data", + auditMaskFields: [], + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} +}, +"School": { + table: "school_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/teaql-node-sqlite.ts b/source/teaql-ts/examples/school-management/src/reconciled/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/teaql-schemas.ts b/source/teaql-ts/examples/school-management/src/reconciled/teaql-schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c4af67824ab9c6712d12cb9c231db91c4731e3f --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/teaql-schemas.ts @@ -0,0 +1,22 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "baseUrl": { columnName: "base_url", modelName: "base_url", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"schoolTypeList": { targetEntity: "SchoolType", localKey: "id", foreignKey: "platform", many: true }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "platform", many: true }} +}, +"SchoolType": { + table: "school_type_data", + auditMaskFields: [], + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} +}, +"School": { + table: "school_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/teaql-ts.ts b/source/teaql-ts/examples/school-management/src/reconciled/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..b54a29ac3c12fb072cf4c292e22bb2e644b56319 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/teaql-ts.ts @@ -0,0 +1,308 @@ +import { + CheckException, EntityChecker, RuntimeModule, + SelectQuery as RuntimeSelectQuery, UserContext, + executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + + constructor(private storagePath?: string) { + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + Object.assign(this.checkers, module.checkers); + return this; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + const graph = new GraphMutationSession(intent); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + try { + this.graphSaveActive = true; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.userContext.insertResource("fixTime", new Date()); + this.userContext.beginFixEvidence(); + fixEvidenceStarted = true; + this.userContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + const result = await work(graph); + this.userContext.ensureMutationPolicyGraphComplete(); + this.persist(); + for (const action of this.graphCommitActions) action(); + return result; + } catch (error) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) action(); + throw error; + } finally { + this.graphSaveActive = false; + this.graphCommitActions = []; + this.graphRollbackActions = []; + if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); + this.userContext.removeResource("fixTime"); + if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + mutation = this.checkAndFixMutation(mutation); + this.userContext.recordMutationPolicyPreflight(mutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + if (mutation instanceof MutationRequest) mutation = mutation.mutation; + if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + const checker = this.checkers[String(mutation.entity)]; + if (!checker) return mutation; + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + this.userContext.translateCheckResults(results); + if (results.length) throw new CheckException(results); + return mutation; + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + mutation = this.checkAndFixMutation(mutation); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + this.mutationGovernanceEvents.push(mutationGovernance); + const table = this.data[mutation.entity] ||= {}; + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + this.nextIds[mutation.entity] = Number(id) + 1; + const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; + } + if (mutation.action === "Update") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + } + if (mutation.action === "Delete") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); + if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); + const relatedRows = (await this.executeQuery(relation.query)).filter( + (row: any) => localValues.has(row[relation.foreignKey || "id"])); + for (const row of rows) { + const matches = relatedRows.filter( + (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/runtime-module.ts b/source/teaql-ts/examples/school-management/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e03a4e5cb463203c4cf7323fbb77a4e98d2b952 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/runtime-module.ts @@ -0,0 +1,150 @@ +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-schemas"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Platform": Object.freeze({ + entityType: "Platform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "base_url": Object.freeze({ canonicalName: "base_url", wireName: "baseUrl", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "SchoolType": Object.freeze({ + entityType: "SchoolType", + profile: "camelCase" as const, + fields: Object.freeze({ + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "code": Object.freeze({ canonicalName: "code", wireName: "code", aliases: Object.freeze([] as string[]) }), + "display_order": Object.freeze({ canonicalName: "display_order", wireName: "displayOrder", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "School": Object.freeze({ + entityType: "School", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "school_type": Object.freeze({ canonicalName: "school_type", wireName: "schoolType", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "address": Object.freeze({ canonicalName: "address", wireName: "address", aliases: Object.freeze([] as string[]) }), + "established_date": Object.freeze({ canonicalName: "established_date", wireName: "establishedDate", aliases: Object.freeze([] as string[]) }), + "student_capacity": Object.freeze({ canonicalName: "student_capacity", wireName: "studentCapacity", aliases: Object.freeze([] as string[]) }), + "active": Object.freeze({ canonicalName: "active", wireName: "active", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Platform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["base_url"] === undefined) || mutation.payload["base_url"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("base_url") }); + if (mutation.payload["base_url"] != null && [...String(mutation.payload["base_url"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("base_url"), inputValue: mutation.payload["base_url"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "SchoolType": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["code"] === undefined) || mutation.payload["code"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("code") }); + if (mutation.payload["code"] != null && [...String(mutation.payload["code"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("code"), inputValue: mutation.payload["code"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["display_order"] === undefined) || mutation.payload["display_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("display_order") }); + + + }, + }, + "School": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "School", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + if ((mutation.action === "Create" && mutation.payload["school_type"] === undefined) || mutation.payload["school_type"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("school_type") }); + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["address"] === undefined) || mutation.payload["address"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("address") }); + if (mutation.payload["address"] != null && [...String(mutation.payload["address"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("address"), inputValue: mutation.payload["address"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["established_date"] === undefined) || mutation.payload["established_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("established_date") }); + + if ((mutation.action === "Create" && mutation.payload["student_capacity"] === undefined) || mutation.payload["student_capacity"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("student_capacity") }); + + if ((mutation.action === "Create" && mutation.payload["active"] === undefined) || mutation.payload["active"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("active") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Campus Learning Platform", "baseUrl": "https://campus.example.com", "createTime": "createTime()", "updateTime": "updateTime()" } }, + constants: [ + { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary", "code": "PRIMARY", "displayOrder": 1 } }, + { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": 2 } } + ] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/teaql-node-sql.ts b/source/teaql-ts/examples/school-management/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c4af67824ab9c6712d12cb9c231db91c4731e3f --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/teaql-node-sql.ts @@ -0,0 +1,22 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "baseUrl": { columnName: "base_url", modelName: "base_url", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"schoolTypeList": { targetEntity: "SchoolType", localKey: "id", foreignKey: "platform", many: true }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "platform", many: true }} +}, +"SchoolType": { + table: "school_type_data", + auditMaskFields: [], + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} +}, +"School": { + table: "school_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/school-management/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/teaql-schemas.ts b/source/teaql-ts/examples/school-management/src/teaql-schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c4af67824ab9c6712d12cb9c231db91c4731e3f --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/teaql-schemas.ts @@ -0,0 +1,22 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "baseUrl": { columnName: "base_url", modelName: "base_url", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"schoolTypeList": { targetEntity: "SchoolType", localKey: "id", foreignKey: "platform", many: true }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "platform", many: true }} +}, +"SchoolType": { + table: "school_type_data", + auditMaskFields: [], + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} +}, +"School": { + table: "school_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/teaql-ts.ts b/source/teaql-ts/examples/school-management/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..b54a29ac3c12fb072cf4c292e22bb2e644b56319 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/teaql-ts.ts @@ -0,0 +1,308 @@ +import { + CheckException, EntityChecker, RuntimeModule, + SelectQuery as RuntimeSelectQuery, UserContext, + executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + + constructor(private storagePath?: string) { + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + Object.assign(this.checkers, module.checkers); + return this; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + const graph = new GraphMutationSession(intent); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + try { + this.graphSaveActive = true; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.userContext.insertResource("fixTime", new Date()); + this.userContext.beginFixEvidence(); + fixEvidenceStarted = true; + this.userContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + const result = await work(graph); + this.userContext.ensureMutationPolicyGraphComplete(); + this.persist(); + for (const action of this.graphCommitActions) action(); + return result; + } catch (error) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) action(); + throw error; + } finally { + this.graphSaveActive = false; + this.graphCommitActions = []; + this.graphRollbackActions = []; + if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); + this.userContext.removeResource("fixTime"); + if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + mutation = this.checkAndFixMutation(mutation); + this.userContext.recordMutationPolicyPreflight(mutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + if (mutation instanceof MutationRequest) mutation = mutation.mutation; + if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + const checker = this.checkers[String(mutation.entity)]; + if (!checker) return mutation; + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + this.userContext.translateCheckResults(results); + if (results.length) throw new CheckException(results); + return mutation; + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + mutation = this.checkAndFixMutation(mutation); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + this.mutationGovernanceEvents.push(mutationGovernance); + const table = this.data[mutation.entity] ||= {}; + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + this.nextIds[mutation.entity] = Number(id) + 1; + const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; + } + if (mutation.action === "Update") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + } + if (mutation.action === "Delete") { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = Number(mutation.version); + const currentVersion = Number(table[id].version || 0); + if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + if (!this.graphSaveActive) this.persist(); + return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); + if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); + if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); + const relatedRows = (await this.executeQuery(relation.query)).filter( + (row: any) => localValues.has(row[relation.foreignKey || "id"])); + for (const row of rows) { + const matches = relatedRows.filter( + (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/teaql-i18n.json b/source/teaql-ts/examples/school-management/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..21b3f9b8ad1eea6f6f4d16aedf6863de4c280cf3 --- /dev/null +++ b/source/teaql-ts/examples/school-management/teaql-i18n.json @@ -0,0 +1,122 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.platform.name": "Name", + "property.platform.createTime": "Create Time", + "property.platform.updateTime": "Update Time", + "property.school.platform": "Platform", + "property.school.id": "Id", + "property.schoolType.version": "Version", + "property.school.establishedDate": "Established Date", + "property.schoolType.code": "Code", + "property.school.studentCapacity": "Student Capacity", + "property.school.active": "Active", + "property.school.schoolType": "School Type", + "entity.platform": "Platform", + "property.platform.id": "Id", + "property.schoolType.displayOrder": "Display Order", + "property.schoolType.id": "Id", + "entity.school": "School", + "property.school.name": "Name", + "property.school.createTime": "Create Time", + "property.school.updateTime": "Update Time", + "entity.schoolType": "School Type", + "property.platform.baseUrl": "Base Url", + "property.platform.version": "Version", + "property.schoolType.platform": "Platform", + "property.school.version": "Version", + "property.school.address": "Address", + "property.schoolType.name": "Name" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/tsconfig.json b/source/teaql-ts/examples/school-management/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/school-management/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/app-dynamic/src/main.ts b/source/teaql-ts/examples/task-board/app-dynamic/src/main.ts new file mode 100644 index 0000000000000000000000000000000000000000..9842d593458074c4269cfef76e420b898a556062 --- /dev/null +++ b/source/teaql-ts/examples/task-board/app-dynamic/src/main.ts @@ -0,0 +1,40 @@ +import fetch from 'node-fetch'; +import { TeaQLClient, QueryParser } from '../../../../src'; +import { Q } from '../../ts-lib-core/src/generated/Q'; + +// 1. Initialize TFP Client, pointing to the Rust backend +const client = new TeaQLClient({ + baseUrl: 'http://127.0.0.1:3001', + fetch: fetch as any +}); + +// 2. Prepare request context +const ctx = { client }; + +async function runDynamicExamples() { + try { + console.log("=== Dynamic String Query Examples ==="); + + // Example A: Dynamic filtering query + const filterQuery = 'Q.tasks().withNameContaining("bug")'; + console.log(`[Execution]: ${filterQuery}`); + + // Parse the string DSL into AST and execute (pass entry object Q) + const filterRequest = QueryParser.parse(filterQuery, Q); + const filterResult = await filterRequest.executeForList(ctx); + console.log("Result:", filterResult); + + // Example B: Dynamic aggregation and grouping + const userQueryStr = 'Q.tasks().withNameContaining("bug").facetByStatusAs("statusFacet", Q.taskStatuses().count())'; + console.log(`\n[Execution]: ${userQueryStr}`); + + const aggRequest = QueryParser.parse(userQueryStr, Q); + const aggResult = await aggRequest.executeForList(ctx); + console.log("Result:", aggResult); + + } catch (err) { + console.error("Query execution failed:", err); + } +} + +runDynamicExamples(); diff --git a/source/teaql-ts/examples/task-board/app-native/src/main.ts b/source/teaql-ts/examples/task-board/app-native/src/main.ts new file mode 100644 index 0000000000000000000000000000000000000000..36a1a74b3684e677efa8ef3f5ef654aa1ae22077 --- /dev/null +++ b/source/teaql-ts/examples/task-board/app-native/src/main.ts @@ -0,0 +1,75 @@ +import fetch from 'node-fetch'; +import { TeaQLClient } from '../../../../src'; +import { Q } from '../../ts-lib-core/src/generated/Q'; +import { Task } from '../../ts-lib-core/src/generated/models/Task'; + +// 1. Initialize TFP Client, pointing to the Rust backend +const client = new TeaQLClient({ + baseUrl: 'http://127.0.0.1:3001', + fetch: fetch as any +}); + +// 2. Prepare request context +const ctx = { client }; + +async function runNativeExamples() { + try { + console.log("=== Native TypeScript Query Examples ==="); + + // Example A: Strongly-typed chained calls (Conditional filtering) + console.log("[Execution]: Q.tasks().withNameContaining('bug').purpose('find bugs')"); + const filterResult = await Q.tasks() + .withNameContaining("bug") + .purpose("find bugs") + .executeForList(ctx); + + console.log("Result:", filterResult); + + // Example B: Strongly-typed chained calls (Aggregation and Grouping) + console.log("\n[Execution]: Q.taskStatuses().groupByDisplayOrder().avgProgress().purpose('calc average')"); + const aggResult = await Q.taskStatuses() + .groupByDisplayOrder() + .avgProgress() + .purpose("calc average") + .executeForList(ctx); + + console.log("Result:", aggResult); + + // Example C: Strongly-typed chained calls (Nested Facet panel aggregation) + console.log("\n[Execution]: Q.tasks().facetByStatusAs('statusFacet', Q.taskStatuses().count()).purpose('dashboard render')"); + const facetResult = await Q.tasks() + .facetByStatusAs("statusFacet", Q.taskStatuses().count()) + .purpose("dashboard render") + .executeForList(ctx); + + console.log("Main data (Tasks):", facetResult.data); + console.log("Statistics panel (Facets):", facetResult.facets); + + // Example D: Data Mutations + console.log("\n[Execution]: Create Task"); + const task = new Task({ name: 'New Bug Task', status: 1001 }); + const saveResult = await task.auditAs("Create a new bug").save(ctx); + console.log("Create Result:", JSON.stringify(saveResult, null, 2)); + + const newId = saveResult.data[0].saved_data.id; + const newVersion = saveResult.data[0].saved_data.version; + console.log(`Retrieved newly created Task ID: ${newId}, Version: ${newVersion}`); + + console.log(`\n[Execution]: Update Task (ID: ${newId})`); + const updateTask = new Task({ id: newId, name: 'New Bug Task (Fixed)', status: 1004, version: newVersion }); + const updateResult = await updateTask.auditAs("Fix the bug").save(ctx); + console.log("Update Result:", JSON.stringify(updateResult, null, 2)); + + const updatedVersion = updateResult.data[0].saved_data.version; + + console.log(`\n[Execution]: Delete Task (ID: ${newId})`); + const taskToDelete = new Task({ id: newId, version: updatedVersion }); + const deleteResult = await taskToDelete.markForDeletion().auditAs("Clean up the bug").save(ctx); + console.log("Delete Result:", JSON.stringify(deleteResult, null, 2)); + + } catch (err) { + console.error("Query execution failed:", err); + } +} + +runNativeExamples(); diff --git a/source/teaql-ts/examples/task-board/package-lock.json b/source/teaql-ts/examples/task-board/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..bf1ee72b08dc772376e37a83552a4ce9c081a204 --- /dev/null +++ b/source/teaql-ts/examples/task-board/package-lock.json @@ -0,0 +1,490 @@ +{ + "name": "teaql-task-board-federation-examples", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "teaql-task-board-federation-examples", + "dependencies": { + "node-fetch": "^2.7.0", + "teaql-ts": "file:../.." + }, + "devDependencies": { + "@types/node-fetch": "^2.6.12", + "typescript": "^5.0.0" + } + }, + "../..": { + "name": "@teaql/teaql", + "version": "0.3.1", + "license": "Apache-2.0", + "dependencies": { + "node-fetch": "^2.7.0" + }, + "devDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "@types/better-sqlite3": "^7.6.12", + "@types/jest": "^29.5.0", + "@types/node-fetch": "^2.6.13", + "@types/pg": "^8.11.0", + "better-sqlite3": "^12.10.0", + "esbuild": "^0.28.2", + "jest": "^29.5.0", + "jest-util": "^29.7.0", + "mysql2": "^3.11.0", + "peggy": "^5.1.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0", + "ts-jest": "^29.1.0", + "typescript": "5.4.5" + }, + "peerDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.221.0", + "@opentelemetry/context-async-hooks": "^2.10.0", + "@opentelemetry/core": "^2.10.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "^2.10.0", + "@opentelemetry/sdk-logs": "^0.221.0", + "@opentelemetry/sdk-metrics": "^2.10.0", + "@opentelemetry/sdk-trace-base": "^2.10.0", + "@sqlite.org/sqlite-wasm": "3.53.0-build1", + "better-sqlite3": "^12.10.0", + "expo-sqlite": "*", + "mysql2": "^3.11.0", + "pg": "^8.12.0", + "pg-query-stream": "^4.7.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/s3-request-presigner": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/api-logs": { + "optional": true + }, + "@opentelemetry/context-async-hooks": { + "optional": true + }, + "@opentelemetry/core": { + "optional": true + }, + "@opentelemetry/exporter-logs-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-metrics-otlp-http": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-http": { + "optional": true + }, + "@opentelemetry/otlp-transformer": { + "optional": true + }, + "@opentelemetry/resources": { + "optional": true + }, + "@opentelemetry/sdk-logs": { + "optional": true + }, + "@opentelemetry/sdk-metrics": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "@sqlite.org/sqlite-wasm": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "expo-sqlite": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-query-stream": { + "optional": true + } + } + }, + "node_modules/@types/node": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.3.0.tgz", + "integrity": "sha512-L3fgrnchriRC2ExBflb8j4uZZURHZfQsmQeyVzhjcHW4kkwVyo8/0h1B2MVzMTrYUJYu6G7EWs14hW/L9putqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.3.0" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/teaql-ts": { + "resolved": "../..", + "link": true + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", + "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + } + } +} diff --git a/source/teaql-ts/examples/task-board/package.json b/source/teaql-ts/examples/task-board/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bc3dcfe4a262a6ec0a5b5053d57959630519678f --- /dev/null +++ b/source/teaql-ts/examples/task-board/package.json @@ -0,0 +1,15 @@ +{ + "name": "teaql-task-board-federation-examples", + "private": true, + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "node-fetch": "^2.7.0", + "teaql-ts": "file:../.." + }, + "devDependencies": { + "@types/node-fetch": "^2.6.12", + "typescript": "^5.0.0" + } +} diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/Q.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea7decc08f8bfe4dc767a8e217b6a99855c35e3c --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../../../../../src'; +import { PlatformRequest } from './requests/PlatformRequest'; +import { TaskStatusRequest } from './requests/TaskStatusRequest'; +import { TaskRequest } from './requests/TaskRequest'; +import { TaskExecutionLogRequest } from './requests/TaskExecutionLogRequest'; + +export class Q { + static platforms(): PlatformRequest { + return new PlatformRequest(); + } + static taskStatuses(): TaskStatusRequest { + return new TaskStatusRequest(); + } + static tasks(): TaskRequest { + return new TaskRequest(); + } + static taskExecutionLogs(): TaskExecutionLogRequest { + return new TaskExecutionLogRequest(); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Platform.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Platform.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cd84985c1d6959bedefbbe6d0d06952b2bfaee4 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Platform.ts @@ -0,0 +1,34 @@ +export class Platform { + id?: any; + name?: string; + founded?: any; + userEmail?: string; + version?: any; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: any): Promise { + const mutation = { + entity: "Platform", + action: (this as any)._action, + payload: this, + id: this.id, + comment: (this as any)._comment + }; + return ctx.client.executeMutation(mutation); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Task.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Task.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd6fb960c914641676ae4ecda2ce485e61fde41c --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Task.ts @@ -0,0 +1,34 @@ +export class Task { + id?: any; + name?: string; + status?: any; + platform?: any; + version?: any; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: any): Promise { + const mutation = { + entity: "Task", + action: (this as any)._action, + payload: this, + id: this.id, + comment: (this as any)._comment + }; + return ctx.client.executeMutation(mutation); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts new file mode 100644 index 0000000000000000000000000000000000000000..09ef85dc9a9169a900af58be3c0a99a6f66ce366 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts @@ -0,0 +1,34 @@ +export class TaskExecutionLog { + id?: any; + task?: any; + action?: string; + detail?: string; + version?: any; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: any): Promise { + const mutation = { + entity: "TaskExecutionLog", + action: (this as any)._action, + payload: this, + id: this.id, + comment: (this as any)._comment + }; + return ctx.client.executeMutation(mutation); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts new file mode 100644 index 0000000000000000000000000000000000000000..8faed124dc20814aebb72093192a6c0a197b75c2 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts @@ -0,0 +1,37 @@ +export class TaskStatus { + id?: any; + name?: string; + code?: string; + color?: string; + displayOrder?: number; + progress?: number; + platform?: any; + version?: any; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + if (init) Object.assign(this, init); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = comment; + return this; + } + + async save(ctx: any): Promise { + const mutation = { + entity: "TaskStatus", + action: (this as any)._action, + payload: this, + id: this.id, + comment: (this as any)._comment + }; + return ctx.client.executeMutation(mutation); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..a09405179972b70ca71f72f7c21d5f142836dde4 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts @@ -0,0 +1,145 @@ +import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { Platform } from '../models/Platform'; + +export class PlatformRequest { + private query: SelectQuery; + private filters: any = {}; + + constructor() { + this.query = new SelectQuery("Platform"); + } + + comment(c: string): this { + this.query.comment(c); + return this; + } + + purpose(p: string): this { + this.query.purpose(p); + return this; + } + + withIdIs(val: any): this { + this.filters["id"] = { "$eq": val }; + return this; + } + + withNameContaining(val: string): this { + this.filters["name"] = { "$contains": val }; + return this; + } + + withNameIs(val: string): this { + this.filters["name"] = { "$eq": val }; + return this; + } + + withFoundedIs(val: any): this { + this.filters["founded"] = { "$eq": val }; + return this; + } + + withUserEmailContaining(val: string): this { + this.filters["userEmail"] = { "$contains": val }; + return this; + } + + withUserEmailIs(val: string): this { + this.filters["userEmail"] = { "$eq": val }; + return this; + } + + withVersionIs(val: any): this { + this.filters["version"] = { "$eq": val }; + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + + groupByFounded(): this { + this.query.groupBy("founded"); + return this; + } + + groupByFoundedAs(retName: string): this { + this.query.groupBy("founded"); // In TS we don't alias group by yet natively + return this; + } + + groupByUserEmail(): this { + this.query.groupBy("user_email"); + return this; + } + + groupByUserEmailAs(retName: string): this { + this.query.groupBy("user_email"); // In TS we don't alias group by yet natively + return this; + } + + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + + // --- Facets --- + + async executeForList(ctx: any): Promise { + if (Object.keys(this.filters).length > 0) { + this.query.filter(this.filters); + } + + const data = await ctx.client.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (Object.keys(this.filters).length > 0) { + f.query.filter(this.filters); // Inherit outer filters + } + result.facets[f.facetName] = await ctx.client.executeQuery(f.query); + } + } + + return result; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b7604b1c491dafdaeb160db28729b1e6dccb319 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts @@ -0,0 +1,137 @@ +import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { TaskExecutionLog } from '../models/TaskExecutionLog'; + +export class TaskExecutionLogRequest { + private query: SelectQuery; + private filters: any = {}; + + constructor() { + this.query = new SelectQuery("TaskExecutionLog"); + } + + comment(c: string): this { + this.query.comment(c); + return this; + } + + purpose(p: string): this { + this.query.purpose(p); + return this; + } + + withIdIs(val: any): this { + this.filters["id"] = { "$eq": val }; + return this; + } + + + withActionContaining(val: string): this { + this.filters["action"] = { "$contains": val }; + return this; + } + + withActionIs(val: string): this { + this.filters["action"] = { "$eq": val }; + return this; + } + + withDetailContaining(val: string): this { + this.filters["detail"] = { "$contains": val }; + return this; + } + + withDetailIs(val: string): this { + this.filters["detail"] = { "$eq": val }; + return this; + } + + withVersionIs(val: any): this { + this.filters["version"] = { "$eq": val }; + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + + + groupByAction(): this { + this.query.groupBy("action"); + return this; + } + + groupByActionAs(retName: string): this { + this.query.groupBy("action"); // In TS we don't alias group by yet natively + return this; + } + + groupByDetail(): this { + this.query.groupBy("detail"); + return this; + } + + groupByDetailAs(retName: string): this { + this.query.groupBy("detail"); // In TS we don't alias group by yet natively + return this; + } + + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + + // --- Facets --- + facetByTaskAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "TASK_PROPERTY", request); + return this; + } + + + async executeForList(ctx: any): Promise { + if (Object.keys(this.filters).length > 0) { + this.query.filter(this.filters); + } + + const data = await ctx.client.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (Object.keys(this.filters).length > 0) { + f.query.filter(this.filters); // Inherit outer filters + } + result.facets[f.facetName] = await ctx.client.executeQuery(f.query); + } + } + + return result; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d9b782ead34ad7aaa1fc8e83433f4b1f1ff6565 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts @@ -0,0 +1,124 @@ +import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { Task } from '../models/Task'; + +export class TaskRequest { + private query: SelectQuery; + private filters: any = {}; + + constructor() { + this.query = new SelectQuery("Task"); + } + + comment(c: string): this { + this.query.comment(c); + return this; + } + + purpose(p: string): this { + this.query.purpose(p); + return this; + } + + withIdIs(val: any): this { + this.filters["id"] = { "$eq": val }; + return this; + } + + withNameContaining(val: string): this { + this.filters["name"] = { "$contains": val }; + return this; + } + + withNameIs(val: string): this { + this.filters["name"] = { "$eq": val }; + return this; + } + + + + withVersionIs(val: any): this { + this.filters["version"] = { "$eq": val }; + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + + + + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + + // --- Facets --- + facetByStatusAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "STATUS_PROPERTY", request); + return this; + } + + facetByPlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "PLATFORM_PROPERTY", request); + return this; + } + + + async executeForList(ctx: any): Promise { + if (Object.keys(this.filters).length > 0) { + this.query.filter(this.filters); + } + + const data = await ctx.client.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (Object.keys(this.filters).length > 0) { + f.query.filter(this.filters); // Inherit outer filters + } + result.facets[f.facetName] = await ctx.client.executeQuery(f.query); + } + } + + return result; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..75e2dd816f9eba544263d0001716c7f02aa4b370 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts @@ -0,0 +1,315 @@ +import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { TaskStatus } from '../models/TaskStatus'; + +export class TaskStatusRequest { + private query: SelectQuery; + private filters: any = {}; + + constructor() { + this.query = new SelectQuery("TaskStatus"); + } + + comment(c: string): this { + this.query.comment(c); + return this; + } + + purpose(p: string): this { + this.query.purpose(p); + return this; + } + + withIdIs(val: any): this { + this.filters["id"] = { "$eq": val }; + return this; + } + + withNameContaining(val: string): this { + this.filters["name"] = { "$contains": val }; + return this; + } + + withNameIs(val: string): this { + this.filters["name"] = { "$eq": val }; + return this; + } + + withCodeContaining(val: string): this { + this.filters["code"] = { "$contains": val }; + return this; + } + + withCodeIs(val: string): this { + this.filters["code"] = { "$eq": val }; + return this; + } + + withColorContaining(val: string): this { + this.filters["color"] = { "$contains": val }; + return this; + } + + withColorIs(val: string): this { + this.filters["color"] = { "$eq": val }; + return this; + } + + withDisplayOrderIs(val: any): this { + this.filters["displayOrder"] = { "$eq": val }; + return this; + } + + withProgressIs(val: any): this { + this.filters["progress"] = { "$eq": val }; + return this; + } + + + withVersionIs(val: any): this { + this.filters["version"] = { "$eq": val }; + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + return this; + } + + minDisplayOrder(): this { + return this.minDisplayOrderAs("minOfDisplayOrder"); + } + + minDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + maxDisplayOrder(): this { + return this.maxDisplayOrderAs("maxOfDisplayOrder"); + } + + maxDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + sumDisplayOrder(): this { + return this.sumDisplayOrderAs("sumOfDisplayOrder"); + } + + sumDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + avgDisplayOrder(): this { + return this.avgDisplayOrderAs("avgOfDisplayOrder"); + } + + avgDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + standardDeviationDisplayOrder(): this { + return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder"); + } + + standardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrder(): this { + return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder"); + } + + squareRootOfPopulationStandardDeviationDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + sampleVarianceDisplayOrder(): this { + return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder"); + } + + sampleVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + samplePopulationVarianceDisplayOrder(): this { + return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder"); + } + + samplePopulationVarianceDisplayOrderAs(retName: string): this { + this.query.aggregate("", "display_order", retName); + return this; + } + minProgress(): this { + return this.minProgressAs("minOfProgress"); + } + + minProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + maxProgress(): this { + return this.maxProgressAs("maxOfProgress"); + } + + maxProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + sumProgress(): this { + return this.sumProgressAs("sumOfProgress"); + } + + sumProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + avgProgress(): this { + return this.avgProgressAs("avgOfProgress"); + } + + avgProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + standardDeviationProgress(): this { + return this.standardDeviationProgressAs("standardDeviationOfProgress"); + } + + standardDeviationProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + squareRootOfPopulationStandardDeviationProgress(): this { + return this.squareRootOfPopulationStandardDeviationProgressAs("squareRootOfPopulationStandardDeviationOfProgress"); + } + + squareRootOfPopulationStandardDeviationProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + sampleVarianceProgress(): this { + return this.sampleVarianceProgressAs("sampleVarianceOfProgress"); + } + + sampleVarianceProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + samplePopulationVarianceProgress(): this { + return this.samplePopulationVarianceProgressAs("samplePopulationVarianceOfProgress"); + } + + samplePopulationVarianceProgressAs(retName: string): this { + this.query.aggregate("", "progress", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + + groupByCode(): this { + this.query.groupBy("code"); + return this; + } + + groupByCodeAs(retName: string): this { + this.query.groupBy("code"); // In TS we don't alias group by yet natively + return this; + } + + groupByColor(): this { + this.query.groupBy("color"); + return this; + } + + groupByColorAs(retName: string): this { + this.query.groupBy("color"); // In TS we don't alias group by yet natively + return this; + } + + groupByDisplayOrder(): this { + this.query.groupBy("display_order"); + return this; + } + + groupByDisplayOrderAs(retName: string): this { + this.query.groupBy("display_order"); // In TS we don't alias group by yet natively + return this; + } + + groupByProgress(): this { + this.query.groupBy("progress"); + return this; + } + + groupByProgressAs(retName: string): this { + this.query.groupBy("progress"); // In TS we don't alias group by yet natively + return this; + } + + + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + + // --- Facets --- + facetByPlatformAs(facetName: string, request: any): this { + this.query.facetBy(facetName, "PLATFORM_PROPERTY", request); + return this; + } + + + async executeForList(ctx: any): Promise { + if (Object.keys(this.filters).length > 0) { + this.query.filter(this.filters); + } + + const data = await ctx.client.executeQuery(this.query); + const result: any = { data }; + + if (this.query.facets && this.query.facets.length > 0) { + result.facets = {}; + for (const f of this.query.facets) { + if (Object.keys(this.filters).length > 0) { + f.query.filter(this.filters); // Inherit outer filters + } + result.facets[f.facetName] = await ctx.client.executeQuery(f.query); + } + } + + return result; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/tsconfig.json b/source/teaql-ts/examples/task-board/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..19471f1c3e4afdbf43fbefb7c212ccb6be72fe72 --- /dev/null +++ b/source/teaql-ts/examples/task-board/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true + }, + "include": ["app-dynamic/src/**/*.ts", "app-native/src/**/*.ts", "ts-lib-core/src/**/*.ts"] +} diff --git a/source/teaql-ts/examples/trace-chain/.gitignore b/source/teaql-ts/examples/trace-chain/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6d613716f2421f77517ff8209ab6a04ea3b49d63 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/.gitignore @@ -0,0 +1,2 @@ +.local/ +node_modules/ diff --git a/source/teaql-ts/examples/trace-chain/AGENTS.md b/source/teaql-ts/examples/trace-chain/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..2d845155e5603211c785283520d51a4b74afdc1f --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/AGENTS.md @@ -0,0 +1,20 @@ +# TeaQL TypeScript application rules + +This workspace implements `trace-chain-service`. Work in application-owned code; +the generated domain library is read-only. + +- Use current `typescript-assist-[action]/[entity]` and required field-level + `typescript-assist-query/[entity].[field]` for exact APIs. Do not read or search + generated domain-library source for API discovery. Report `MISSING_ASSIST` + if current Assist cannot provide an operation; never guess a method name. +- Every query is bounded and has a non-blank comment and purpose. Set projection, + filter and relation selection before the executable purpose stage. +- Public query execution and save accept only the trusted `UserContext`. +- Only the root graph requires `auditAs(...)`. A child without a local reason + inherits the root. A child with `auditAs(...)` keeps its additional reason. +- Keep deleted children in the composed graph using `markForDeletion()`, then + save the root. Do not invent direct delete or low-level graph execution APIs. +- Inject the installed local data service into context. Schema/bootstrap runs + through `context.ensureSchema()`; reuse the default Domain Root. +- Compile and test application changes. Repair the smallest diagnosed block; + never rewrite or patch generated source to make a test pass. \ No newline at end of file diff --git a/source/teaql-ts/examples/trace-chain/README.md b/source/teaql-ts/examples/trace-chain/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a15cf2cf45de4d0fa2a4740a07f28389a2345475 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/README.md @@ -0,0 +1,197 @@ +# Generated TypeScript Trace Chain example + +This local-source example exercises request-owned intent, SQL paths and +committed audit lineage through generated Q, E and Mutation APIs. It is not a +released-package or complete-provider conformance claim. + +From the runtime checkout: + +```bash +npm run build +cd examples/trace-chain +npm install +npm run build +npm start +npm start +npm run test:shared-reference +npm run test:shared-reference +npm run test:page +npm run test:page +npm run test:stream-capture +npm run test:stream-capture +npm run test:relation-aggregate +npm run test:relation-aggregate +npm run test:checker-overlap +npm run test:checker-overlap +``` + +Both starts use `.local/trace-chain.sqlite` without resetting or deleting it. +Each run uses distinct business values and ensures schema/bootstrap twice. +Set `TEAQL_TRACE_CHAIN_DB` to select another dedicated SQLite file. +The ownership suite uses a separate `.local/shared-reference.sqlite`; set +`TEAQL_TRACE_CHAIN_SHARED_DB` to override it. Do not mix these databases: the +normative fixture intentionally compares per-type IDs, whereas the ownership +suite creates a different number of records per type. Neither suite deletes its +database between runs. + +The normative fixture explicitly reserves unused IDs and raises CustomerOrder +and Payment sequence floors through the runtime allocator before each run. +This creates a repeatable same-numeric-ID case even when historical counters +differ; it never rewrites business rows or guesses a generated ID setter. +Only this test setup creates intentional sequence gaps. Business records are +still created/updated/deleted through generated APIs. + +The page suite uses `.local/paging.sqlite` (override with +`TEAQL_TRACE_CHAIN_PAGE_DB`). It tests a nonzero-offset page, a page scoped by +an application Context, a list and a chunked stream. Each selected root and its +child form one independently saveable graph. Updating both graphs and saving +only one must leave the other graph's persisted values and versions untouched. +COUNT and page rows share the Context-prepared request. List/stream do not run +COUNT. SQLite executes one root query and two per-parent child probes; pages +add one COUNT. Safe SQL metadata masks a marked child value even when the root +comment/purpose includes it. No diagnostic-source query is executed. + +The delayed stream suite uses `.local/stream-capture.sqlite` (override with +`TEAQL_TRACE_CHAIN_STREAM_DB`). Two streams capture their generated predicates, +nested selections, comment/purpose and Context-applied scope before first poll. +The caller then changes its builder and Context before concurrent consumption. +The results and SQL evidence must retain the two original requests. Cancellation +after one row records exactly one delivered row; a never-polled stream emits no +SQL. Native tests additionally preserve an invalid request's captured rejection +even if the caller repairs its builder before polling. Validation failure stays +asynchronous at the low-level streaming API; the generated intent gate remains +synchronous. No cursor opens during capture. + +Native SQLite regression `tests/trace-chain-sql.test.ts` additionally checks +relation aggregates in full/tail stream chunks, early cancellation and SQL +failure. Lists and streams compute aggregates before forward-relation hydration +can replace scalar membership keys with objects. This covers loading and counting +the same relation, nested aggregate ancestry and inherited private intent. +The generated relation-aggregate suite uses `.local/relation-aggregate.sqlite` +(override with `TEAQL_TRACE_CHAIN_AGGREGATE_DB`). It combines generated related +counts with loaded child lists, at the root and inside a loaded forward relation. +Twelve combinations cover lists, full/trailing stream chunks and SQL logging +on/off. Generated E verifies modeled identity and child membership; dynamic count +aliases are narrowed from unknown as documented by field Assist. The suite also +saves an aggregate-loaded graph, checks the count is not mutation data, and +verifies aggregate failure prevents incomplete stream delivery. No generated +library source is edited or inspected; each execution fingerprints it. + +Run `bash scripts/verify-current-aggregate.sh` from the runtime checkout for the +deeper aggregate-membership gate. It rebuilds local runtime output, compiles the +application, runs numeric-partition and scalar-membership native tests twice, +then runs 24 generated combinations twice on the same dedicated SQLite database +without cleanup. Set `TEAQL_TS_AGGREGATE_EVIDENCE` to retain logs at a chosen path. +Generated Q related counts, loaded child lists and explicitly filtered/unfiltered +forward targets combine root/nested owners, list/full/tail streams and logging +off/on. Count remains 1 while membership remains 2; filtered targets retain their +actual FK identity but not loaded details. Independent full reads cannot widen +those old views. The runtime-generated safe path is checked against each actual +driver statement; streams report root completion after the child statements. +Raw driver SQL/bindings are test evidence, not an invented raw metadata API. +Telemetry still supplies safe metadata when ordinary SQL logging is disabled; +the diagnostic sink then receives nothing. Query probes produce no mutation +commands or committed audits. The generated library remains unchanged. This +local-source gate is not a private Registry or complete TC-SQL-10 claim. + +The seven checks cover: + +1. Idempotent generated schema/bootstrap and bounded Q/E access to the root. +2. Six creates with assigned IDs, inherited reasons and independent branches. +3. Six updates/deletion intents followed by one root save, with matching + per-entity request, SQL and committed-audit lineages. +4. A bounded three-level relation query and loaded E traversal, including the + normalized ID of a preloaded relation. +5. Two overlapping independent graph saves using the same UserContext. +6. Provider failure and write-success/readback-failure: retained SQL evidence, + atomic rollback and no committed audit. +7. Loaded private old values, committed refresh, rollback/retry and isolation + of the next independent request. + +Create, update/delete and both concurrent graphs compare exactly six distinct +`(entity type, ID)` pairs at the command, actual physical-write and committed +audit boundaries. Canonical SQL paths do not contain target IDs: each write is +bound to its actual observed command/result in order, with successful outcome, +one affected row, the correct entity frame and matching action. Audit identity +comes from the event's independent `entity` and `id`, not an inherited reason. +The Order and Payment deliberately have equal numeric IDs. Guard controls reject +duplicates, a missing identity and collapse across entity types. IDs are checked +as decimal strings without converting them through an imprecise JavaScript +number. `GRAPH IDENTITY EVIDENCE` prints the actual normative update observations. + +Each successful generated mutation also returns physical write/readback metadata. +Six graph changes produce twelve ordered SQL facts, while committed audit still +contains six events. Readbacks use the originating root's query/request path, +keep branch-local lineage and have the explicit purpose `verify persisted +mutation result`. The same checks cover creates, updates, soft deletion and +overlapping graph saves; failed graphs retain earlier successful SELECTs without +emitting committed audits. Generated Q/E observations remain ordinary queries, +distinct from mutation readback SQL. + +The four ownership checks additionally execute: + +1. Two overlapping public saves share a genuinely identical, immutable + provider-loaded Platform record but retain independent generated wrappers + and ledgers. Different original root versions are used; unchanged children + and the read-only Platform receive no UPDATE or audit event. +2. Attaching a changed child imports only that reached key. The foreign root + and unselected child changes remain pending in the original ledger. +3. A clean ancestor contributes its audit reason while only the changed child + is written; the parent's optimistic version remains unchanged. +4. Composing two loaded versions of the same typed entity rejects before any + business mutation or committed audit and retains both graphs' pending state. + +The application prints actual request, SQL-metadata and committed-audit +observations. Saves overlap at the public boundary; the provider serializes +their transactions. This is not simultaneous SQLite writer or Checker proof. + +The Checker overlap suite uses the real installed generated Checker, not a +simulated failure. Four cases combine SQL logging on/off and both invocation +orders: a valid graph updates its root and child; a second graph omits a new +child's required name. Both share an immutable provider-loaded Platform snapshot +but keep separate generated wrappers and ledgers. The rejected graph rolls back +its transaction before any business SQL, ID allocation, mutation command or +committed audit. It does start a transaction; Checker callbacks are serialized +by the runtime gate. Q/E readback proves only the valid graph changed, and a +following independent save has its own lineage and no residual Fix state. +The read-only Platform receives no write or audit. + +Run `bash scripts/verify-checker-overlap.sh` from the runtime checkout for a +bounded build and two consecutive runs against one retained SQLite database. +It never installs packages or cleans data, unsets the plaintext-log opt-in for +the safe subprocesses, and retains logs and generated-file fingerprints. Set +`TEAQL_TRACE_CHAIN_CHECKER_EVIDENCE` and `TEAQL_TRACE_CHAIN_CHECKER_DB` to choose +the evidence directory and database. Direct npm runs default to +`.local/checker-overlap.sqlite` and `.local/checker-overlap-evidence`. + +The generated model names the logical order `customer_order` to avoid a +reserved word. Payment and CustomerOrder intentionally share numeric IDs, +without sharing ledger identity. A child `auditAs(...)` is a local reason; +missing child reasons inherit rather than duplicate the parent chain. + +`lib/` comes from the upstream generator and is not hand-edited. The application +checks every generated file's hash before and after execution and writes its +manifest outside the library. Evaluation, current object/field Assist and the +generated application rules are retained in `evidence/` and `AGENTS.md`. + +Upstream generation is tested with the explicit local runtime path: + +```bash +mvn -pl generator -am \ + -Dteaql.ts.dir=/path/to/teaql-ts \ + -Dtest=TypeScriptTraceChainExampleGenerationTest \ + -Dsurefire.failIfNoSpecifiedTests=false test +``` + +Prepared same-type batch lineage, complete privacy/entry-point coverage, +arbitrary mutable reference composition, +file-backed/Expo graph acceptance and internal Registry replay are separate +remaining gates. The full examples script also includes a task-board +compilation-only group and a School demo that resets data; neither is evidence +for this example's no-cleanup gate. + +The local runtime's package label is `0.3.0`; these unreleased source +changes require regenerated models. The old generated post-commit hook cannot +use hydration to overwrite an existing loaded version. The producer now calls +the explicit runtime post-commit version hook instead. This example does not +prove adoption by an immutable Registry package. diff --git a/source/teaql-ts/examples/trace-chain/aggregate-membership.ts b/source/teaql-ts/examples/trace-chain/aggregate-membership.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5a5a6a04e075c094bd29db00312316141e61598 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/aggregate-membership.ts @@ -0,0 +1,138 @@ +import assert from 'node:assert/strict'; +import {randomUUID, createHash} from 'node:crypto'; +import {mkdirSync, readdirSync, readFileSync} from 'node:fs'; +import {dirname, join, resolve} from 'node:path'; +import {UserContext} from 'teaql-ts'; +import {AbstractSQLTeaQLClient, SQLExecutionEvidenceStore, SQLExecutionMetadata, MutationResult} from 'teaql-ts/sql/core'; +import {SQLiteDriver} from 'teaql-ts/sql/sqlite'; +import {Q} from './lib/src/generated/Q'; +import {E} from './lib/src/generated/E'; +import {GENERATED_RUNTIME_MODULE} from './lib/src/runtime-module'; + +type Order = Parameters[0]; +type Payment = Parameters[0]; +const secret = 'TS-PRIVATE-AGGREGATE-MEMBERSHIP'; +const comment = `inspect ${secret}`, purpose = 'verify complete aggregate membership ancestry'; +function hashes(dir: string): string { + return readdirSync(dir, {withFileTypes: true}).sort((a,b)=>a.name.localeCompare(b.name)) + .map(row=>row.isDirectory()?hashes(join(dir,row.name)): + createHash('sha256').update(readFileSync(join(dir,row.name))).digest('hex')).join(''); +} +class Driver extends SQLiteDriver { + reads: Array<{sql: string; values: unknown[]}> = []; + override async query(sql: string, values: any[] = []) { + if (/^SELECT\b/.test(sql)) this.reads.push({sql,values:[...values]}); + return super.query(sql,values); + } + override async *stream(sql: string, values: any[] = []) { + this.reads.push({sql,values:[...values]}); + yield* super.stream(sql,values); + } +} +class Client extends AbstractSQLTeaQLClient { + commands = 0; + constructor(driver: Driver) {super(driver,GENERATED_RUNTIME_MODULE.schemas);} + override async executeMutation(request: any): Promise { + this.commands++;return super.executeMutation(request); + } +} +async function collect(stream: AsyncIterable): Promise { + const rows: T[]=[];for await (const row of stream) rows.push(row);return rows; +} +function count(row: object): number { + const value=(row as unknown as Record).selectedItemCount; + assert.equal(typeof value,'number','aggregate alias must exist, not default to zero'); + assert(Number.isSafeInteger(value));return value as number; +} +function route(root: string, edges: string[]) { + let owner=root; + const path: Array<[string,string,string]>=[['operation',root,'query'],['request',root,'']]; + for(const edge of edges) { + path.push(['relation',edge,`${owner}.${edge}`]); + owner=edge==='customerOrder'?'CustomerOrder':'OrderItem'; + } + path.push(['provider','sqlite',''],['sql','select','']);return path; +} +async function main() { + const before=hashes('lib'); + const database=resolve(process.env.TEAQL_TRACE_CHAIN_MEMBERSHIP_DB??'.local/aggregate-membership.sqlite'); + mkdirSync(dirname(database),{recursive:true}); + const driver=new Driver(database),client=new Client(driver).install(GENERATED_RUNTIME_MODULE); + const context=new UserContext().insertResource('dataService',client); + const evidence=new SQLExecutionEvidenceStore(),diagnostics: SQLExecutionMetadata[]=[],audits: unknown[]=[]; + client.setRuntimeTelemetrySink(evidence).setDiagnosticSQLLogSink(undefined).setAuditSink(event=>{audits.push(event);}); + const group=randomUUID(); + try { + await context.ensureSchema();await context.ensureSchema(); + const order=Q.customerOrders().comment('initialize membership graph').purpose('verify generated aggregate') + .newEntity(context).updatePlatform('1').updateOrderNumber(group).updateDescription(group); + for(const name of [secret,'ordinary member'])order.orderItemList().push(Q.orderItems() + .comment('initialize membership item').purpose('verify two members').newEntity(context).updateName(name)); + order.paymentList().push(Q.payments().comment('initialize membership payment').purpose('verify nested owner') + .newEntity(context).updateReferenceCode(group)); + await order.auditAs('seed generated aggregate membership').save(context); + const id=order.id!; + for(const nested of [false,true])for(const mode of ['list','stream-full','stream-tail']) + for(const logging of [false,true])for(const filtered of [false,true]) { + driver.reads=[];client.commands=0;audits.length=0;diagnostics.length=0;evidence.enableAll(); + client.setQueryLoggingEnabled(logging).setDiagnosticSQLLogSink({write:entry=>diagnostics.push(entry)}); + const children=Q.orderItems().limit(2).selectCustomerOrderWith(Q.customerOrders() + .withIdIs(filtered?'0':id).limit(1)); + const orders=Q.customerOrders().withIdIs(id).limit(1) + .countOrderItemsWith('selectedItemCount',Q.orderItems().withNameIs(secret).limit(2)) + .selectOrderItemListWith(children); + const query=nested?Q.payments().filterByCustomerOrderIn(id).limit(1).selectCustomerOrderWith(orders):orders; + const request=query.comment(comment).purpose(purpose); + const rows=mode==='list'?await request.executeForList(context): + await collect(request.executeForStream(context,mode==='stream-full'?1:3)); + assert.equal(rows.length,1); + const loaded=nested?E.payment(rows[0] as Payment).customerOrder().eval():rows[0] as Order; + assert(loaded);assert.equal(E.customerOrder(loaded).id().eval(),id); + assert.equal(count(loaded),1); + const items=loaded.orderItemList();assert.equal(items.length,2); + const identities=items.map(item=>{ + const target=E.orderItem(item).customerOrder().eval();assert(target); + assert.equal(E.customerOrder(target).id().eval(),id,'actual FK identity survives filtering'); + if(filtered)assert.throws(()=>E.customerOrder(target).description().eval(),{name:'TeaQLNotLoadedError'}); + else assert.equal(E.customerOrder(target).description().eval(),group); + return E.customerOrder(target).id().eval(); + }); + const safe=evidence.snapshot(); + const edges=nested?[[],['customerOrder'],['customerOrder','orderItemList'], + ['customerOrder','orderItemList'],['customerOrder','orderItemList','customerOrder']]: + [[],['orderItemList'],['orderItemList'],['orderItemList','customerOrder']]; + assert.equal(safe.length,edges.length);assert.equal(driver.reads.length,edges.length); + assert.equal(diagnostics.length,logging?safe.length:0); + // A streamed root records completion after its cursor closes. Its child + // statements complete first; do not pretend metadata is emitted on open. + const completedEdges=mode==='list'?edges:[...edges.slice(1),edges[0]]; + safe.forEach((entry,i)=>{ + const physicalIndex=mode==='list'?i:(i+1)%edges.length; + assert.equal(entry.parameterizedSQL,driver.reads[physicalIndex].sql,'metadata must describe actual driver SQL'); + assert.equal(entry.executionOutcome,'success');assert.equal(entry.comment,'inspect [REDACTED]'); + assert.equal(entry.purpose,purpose); + assert.deepEqual(entry.tracePath.map(n=>[n.kind,n.name,n.detail??'']),route(nested?'Payment':'CustomerOrder',completedEdges[i])); + }); + assert(!JSON.stringify({safe,diagnostics}).includes(secret)); + const aggregates=driver.reads.filter(r=>/COUNT\(/i.test(r.sql));assert.equal(aggregates.length,1); + assert(aggregates[0].values.includes(secret),'masking must not change actual database bindings'); + assert.equal(client.commands,0);assert.equal(audits.length,0); + console.log('TS_AGGREGATE_MEMBERSHIP '+JSON.stringify({nested,mode,logging,filtered,id,count:count(loaded), + members:items.length,foreignIDs:identities,detail:filtered?'NotLoaded':'Loaded', + commands:client.commands,audits:audits.length,diagnostics:diagnostics.length,physical:driver.reads,safe})); + if(filtered) { + const independent=await Q.customerOrders().withIdIs(id).limit(1) + .comment('load independent full detail').purpose('verify edge-owned view').executeForList(context); + assert.equal(E.customerOrder(independent[0]).description().eval(),group); + for(const item of items)assert.throws(()=>E.orderItem(item).customerOrder().description().eval(),{name:'TeaQLNotLoadedError'}); + } + } + assert.equal(hashes('lib'),before,'generated library is unchanged'); + const entry=require.resolve('teaql-ts'),runtimeRoot=resolve(dirname(entry),'..'); + console.log('TS_AGGREGATE_RUNTIME '+JSON.stringify({entry,runtimeRoot, + modules:Object.keys(require.cache).filter(file=>file.startsWith(runtimeRoot+'/dist/')).sort() + .map(file=>({path:file.slice(runtimeRoot.length+1),sha256:createHash('sha256').update(readFileSync(file)).digest('hex')}))})); + console.log('PASS TypeScript generated aggregate membership: 24 scenarios; actual SQL, complete safe ancestry, FK and independent filtered views'); + } finally {await client.close();} +} +main().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/source/teaql-ts/examples/trace-chain/app.ts b/source/teaql-ts/examples/trace-chain/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..c45339d8cb6347496a7b3e28d83385877114ba15 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/app.ts @@ -0,0 +1,436 @@ +import assert from 'node:assert/strict'; +import { randomUUID, createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { MutationRequest, TraceNode, UserContext } from 'teaql-ts'; +import { AbstractSQLTeaQLClient, MutationResult, SQLExecutionEvidenceStore, SQLExecutionMetadata, SqlQueryResult, SqlSession } from 'teaql-ts/sql/core'; +import { SQLiteDriver } from 'teaql-ts/sql/sqlite'; +import { Q } from './lib/src/generated/Q'; +import { E } from './lib/src/generated/E'; +import { GENERATED_RUNTIME_MODULE } from './lib/src/runtime-module'; + +const database = resolve(process.env.TEAQL_TRACE_CHAIN_DB ?? '.local/trace-chain.sqlite'); +mkdirSync(join(database, '..'), { recursive: true }); +const checks: string[] = []; +const nonce = randomUUID(); +function manifest(directory: string, prefix = ''): string { + return readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)) + .map(entry => entry.isDirectory() ? manifest(join(directory, entry.name), `${prefix}${entry.name}/`) + : `${createHash('sha256').update(readFileSync(join(directory, entry.name))).digest('hex')} ${prefix}${entry.name}\n`).join(''); +} +const generatedBefore = manifest('lib'); + +type GraphIdentity = Readonly<{ entity: string; id: string }>; +type ObservedCommand = GraphIdentity & Readonly<{ action: string; lineage: readonly TraceNode[] }>; +function checkIdentities(want: readonly GraphIdentity[], actual: readonly GraphIdentity[], boundary: string) { + assert.equal(want.length, 6); assert.equal(actual.length, 6, `${boundary}: six identities required`); + const keys = (rows: readonly GraphIdentity[]) => rows.map(row => { + assert(typeof row.entity === 'string' && typeof row.id === 'string' && /^[1-9][0-9]*$/.test(row.id), + `${boundary}: missing typed identity`); + assert(BigInt(row.id) <= 18446744073709551615n, `${boundary}: ID exceeds u64`); + return JSON.stringify([row.entity, row.id]); + }); + const expected = keys(want), observed = keys(actual); + assert.equal(new Set(expected).size, 6, 'expected graph must contain six distinct identities'); + assert.equal(new Set(observed).size, 6, `${boundary}: duplicate identity`); + assert.deepEqual(observed.sort(), expected.sort(), `${boundary}: missing or unknown typed identity`); +} +function graphIdentities(graph: ReturnType): GraphIdentity[] { + const identity = (entity: string, id: unknown): GraphIdentity => { + assert(typeof id === 'string', 'saved generated entity must have an assigned ID'); + return { entity, id }; + }; + return [identity('CustomerOrder', graph.order.id), identity('OrderItem', graph.item.id), + identity('OrderItem', graph.removed.id), identity('Payment', graph.payment.id), + identity('PaymentAttempt', graph.attempt.id), identity('Shipment', graph.shipment.id)]; +} +function auditIdentities(events: readonly Readonly>[]): GraphIdentity[] { + return events.map(event => { + assert(typeof event.entity === 'string' && typeof event.id === 'string', 'audit omitted independent typed target identity'); + return { entity: event.entity, id: event.id }; + }); +} +function identityControls() { + const want = [{ entity: 'CustomerOrder', id: '100' }, { entity: 'OrderItem', id: '201' }, + { entity: 'OrderItem', id: '202' }, { entity: 'Payment', id: '100' }, + { entity: 'PaymentAttempt', id: '401' }, { entity: 'Shipment', id: '501' }]; + checkIdentities(want, want, 'positive control'); + for (const corruption of ['duplicate', 'missing', 'type-collapse']) { + const actual = want.map(row => ({ ...row })); + if (corruption === 'duplicate') actual[2] = { ...actual[1] }; + if (corruption === 'missing') actual[5].id = '999'; + if (corruption === 'type-collapse') actual[3].entity = 'CustomerOrder'; + assert.throws(() => checkIdentities(want, actual, corruption)); + } + console.log('PASS TypeScript graph identity controls: duplicate, missing and equal-ID type collapse rejected'); +} + +class Driver extends SQLiteDriver { + failureTable?: string; + readbackFailure = false; + beforeCommit?: () => void; + readonly finishes: string[] = []; + readonly attemptedSQL: { sql: string; values: readonly unknown[] }[] = []; + async transaction(work: (session: SqlSession) => Promise): Promise { + try { + const result = await super.transaction(async session => { + const result = await work(session); + this.beforeCommit?.(); + return result; + }); + this.finishes.push('commit'); + return result; + } catch (error) { + this.finishes.push('rollback'); + throw error; + } + } + async query(sql: string, values: any[] = []): Promise { + this.attemptedSQL.push({ sql, values: [...values] }); + if (this.failureTable && sql.includes(this.failureTable) + && (this.readbackFailure ? sql.startsWith('SELECT') && sql.includes('WHERE "id" = ?') : sql.startsWith('INSERT'))) { + throw new Error('injected trace-chain provider failure'); + } + return super.query(sql, values); + } +} +class Client extends AbstractSQLTeaQLClient { + readonly commands: ObservedCommand[] = []; + readonly rawRequests: MutationRequest[] = []; + readonly rawResults: MutationResult[] = []; + constructor(driver: Driver) { super(driver, GENERATED_RUNTIME_MODULE.schemas); } + async executeMutation(mutation: any): Promise { + assert(mutation instanceof MutationRequest, 'generated save must pass an owned request'); + this.rawRequests.push(mutation); + const result = await super.executeMutation(mutation); + this.rawResults.push(result); + assert(mutation instanceof MutationRequest, 'generated save must pass an owned request'); + assert.equal(result.metadata?.statements?.length, 2, 'successful save must return write/readback metadata'); + assert.equal(result.metadata.statements[0].affectedRows, 1); + assert.equal(result.metadata.statements[1].resultCount, 1); + if (mutation.mutation.id !== undefined && mutation.mutation.id !== null) { + assert.equal(String(mutation.mutation.id), result.id, 'provider result changed the requested target ID'); + } + // Creation may allocate its ID inside the provider. Capture that actual + // result, never a guessed sequence or an ID from inherited responsibility. + this.commands.push({ entity: mutation.mutation.entity, id: result.id, action: mutation.mutation.action, + lineage: mutation.traceFor({ entity: mutation.mutation.entity, id: result.id }) }); + return result; + } +} + +function construct(context: UserContext, suffix: string) { + const order = Q.customerOrders().comment('initialize order').purpose('verify generated graph').newEntity(context) + .updatePlatform('1').updateOrderNumber(`${nonce}-${suffix}`).updateDescription(`fixture-description-${suffix}`); + const item = Q.orderItems().comment('initialize available item').purpose('verify generated graph').newEntity(context) + .updateName(`fixture-available-${suffix}`); + const removed = Q.orderItems().comment('initialize second item').purpose('verify generated graph').newEntity(context) + .updateName(`fixture-unavailable-${suffix}`); + const payment = Q.payments().comment('initialize payment').purpose('verify generated graph').newEntity(context) + .updateReferenceCode(`fixture-payment-${suffix}`).auditAs('authorize payment'); + const attempt = Q.paymentAttempts().comment('initialize payment attempt').purpose('verify generated graph').newEntity(context) + .updateReferenceCode(`fixture-attempt-${suffix}`); + const shipment = Q.shipments().comment('initialize shipment').purpose('verify generated graph').newEntity(context) + .updateReferenceCode(`fixture-shipment-${suffix}`).auditAs('dispatch shipment'); + order.orderItemList().push(item, removed); + order.paymentList().push(payment); + payment.paymentAttemptList().push(attempt); + order.shipmentList().push(shipment); + return { order, item, removed, payment, attempt, shipment }; +} +function plain(nodes: unknown): unknown { + return (nodes as readonly TraceNode[]).map(node => [node.kind, node.name, node.entityId, node.detail]); +} +function privateLineage(nodes: readonly TraceNode[] | undefined, rootID: string, reason: string, boundary: string) { + assert.equal(nodes?.length, 1, `${boundary}: complete typed root lineage required`); + assert.deepEqual(plain(nodes), [['auditReason', 'CustomerOrder', rootID, reason]], `${boundary}: wrong root responsibility`); +} +function checkPrivateGraph(client: Client, driver: Driver, entries: readonly SQLExecutionMetadata[], + audits: readonly Readonly>[], rootID: string, childID: string, + reason: string, secrets: readonly string[], newValue: string | undefined, fail: boolean, logging: boolean, phase: string, + precommitChecks: number) { + const safeReason = secrets.reduce((text, secret) => text.split(secret).join('[REDACTED]'), reason); + const expected = [['CustomerOrder', rootID], ['OrderItem', childID]]; + assert.equal(client.rawRequests.length, 2); + assert.deepEqual(client.rawRequests.map(request => [request.mutation.entity, String(request.mutation.id)]), expected); + assert.equal(client.rawResults.length, fail ? 1 : 2); + assert.deepEqual(driver.finishes, [fail ? 'rollback' : 'commit']); + assert.equal(precommitChecks, fail ? 0 : 1, 'audit isolation must be observed before actual commit'); + const commands = client.rawRequests.map(request => { + const key = { entity: request.mutation.entity, id: String(request.mutation.id) }; + assert.equal(request.comment, reason, 'privacy must not rewrite the owned command reason'); + privateLineage(request.traceFor(key), rootID, reason, 'raw privacy command'); + if (key.entity === 'OrderItem' && newValue !== undefined) + assert.equal(request.mutation.payload?.name, newValue, 'privacy must not rewrite command bindings'); + return { ...key, comment: request.comment, action: request.mutation.action, lineage: request.traceFor(key) }; + }); + if (newValue !== undefined) { + assert(driver.attemptedSQL.some(statement => statement.sql.startsWith('UPDATE "order_item_data"') + && statement.values.includes(newValue)), 'privacy must not rewrite physical provider bindings'); + if (!fail) assert(client.rawResults[1].metadata?.statements?.[0].parameters.includes(newValue), + 'privacy must not rewrite provider result bindings'); + } + assert.equal(entries.length, 4, 'two writes retain two real readbacks, including failed readback'); + for (const [index, fact] of entries.entries()) { + privateLineage(fact.mutationLineage, rootID, safeReason, 'safe privacy SQL'); + const read = index % 2 === 1; + // Mutation SQL exposes the owned comment as auditReason; only derived reads + // also expose Query.comment. Do not require a duplicate intent field. + assert.equal(fact.auditReason, safeReason); + assert.equal(fact.comment, read ? safeReason : undefined); + assert.deepEqual(fact.tracePath.map(node => node.kind), ['operation', read ? 'request' : 'entity', 'provider', 'sql']); + assert.equal(fact.tracePath[0].name, 'CustomerOrder'); assert.equal(fact.tracePath[2].name, 'sqlite'); + assert.equal(fact.tracePath[1].name, read ? 'CustomerOrder' : expected[Math.floor(index / 2)][0]); + assert.equal(fact.executionOutcome, fail && index === 3 ? 'failure' : 'success'); + if (read) { + assert.equal(fact.operation, 'select'); assert.equal(fact.tracePath[3].name, 'select'); + assert.equal(fact.purpose, 'verify persisted mutation result'); + if (!(fail && index === 3)) assert.equal(fact.resultCount, 1); + assert.equal(fact.affectedRows, undefined); + } else { + assert.equal(fact.operation, phase === 'delete' && index === 2 ? 'delete' : 'update'); + assert.equal(fact.tracePath[3].name, fact.operation); assert.equal(fact.affectedRows, 1); + } + } + assert.equal(audits.length, fail ? 0 : 2); + if (!fail) assert.deepEqual(audits.map(event => [event.entity, event.id]), expected); + for (const event of audits) { + privateLineage(event.mutationLineage as readonly TraceNode[], rootID, safeReason, 'safe privacy audit'); + assert.equal(event.reason, safeReason); + } + for (const secret of secrets) assert(!JSON.stringify({ sql: entries, audit: audits }).includes(secret), 'private scalar leaked into safe graph evidence'); + console.log('PRIVATE_LINEAGE_OBSERVED ' + JSON.stringify({ rootId: rootID, childId: childID, rawReason: reason, + safeReason, logging, phase, fail, precommitChecks, commands, sql: entries, audit: audits })); + console.log('PASS TypeScript complete private lineage: raw commands, safe SQL/readback and committed audit'); +} +function expected(graph: ReturnType, rootReason: string, deleted = false) { + const root = ['auditReason', 'CustomerOrder', graph.order.id, rootReason]; + return [[root], [root], deleted ? [root, ['auditReason', 'OrderItem', graph.removed.id, 'remove unavailable item']] : [root], + [root, ['auditReason', 'Payment', graph.payment.id, 'authorize payment']], + [root, ['auditReason', 'Payment', graph.payment.id, 'authorize payment']], + [root, ['auditReason', 'Shipment', graph.shipment.id, 'dispatch shipment']]]; +} + +function checkPhysicalGraph(entries: readonly SQLExecutionMetadata[], lineages: ReturnType, reason: string, + commands: readonly ObservedCommand[]): GraphIdentity[] { + assert.equal(entries.length, 12); assert.equal(commands.length, 6); + const identities: GraphIdentity[] = []; + assert.deepEqual(entries.map(entry => plain(entry.mutationLineage)), lineages.flatMap(lineage => [lineage, lineage])); + for (let index = 0; index < lineages.length; index++) { + const write = entries[index * 2], read = entries[index * 2 + 1]; + assert.notEqual(write.operation, 'select'); assert.equal(write.affectedRows, 1); + assert.equal(write.executionOutcome, 'success'); + assert.equal(write.operation, commands[index].action === 'Create' ? 'insert' : commands[index].action.toLowerCase()); + assert.deepEqual(write.tracePath.map(node => node.kind), ['operation', 'entity', 'provider', 'sql']); + assert.equal(write.tracePath[1].name, commands[index].entity); + // Canonical SQL paths do not contain target IDs. Bind each real write to + // the observed provider command/result at the same ordered boundary. + identities.push({ entity: commands[index].entity, id: commands[index].id }); + assert.equal(read.operation, 'select'); assert.equal(read.resultCount, 1); + assert.equal(read.executionOutcome, 'success'); assert.equal(read.comment, reason); + assert.equal(read.purpose, 'verify persisted mutation result'); + assert.deepEqual(read.tracePath.map(node => node.kind), ['operation', 'request', 'provider', 'sql']); + assert.equal(read.tracePath[0].name, 'CustomerOrder'); assert.equal(read.tracePath[0].detail, 'query'); + assert.deepEqual(read.mutationLineage, write.mutationLineage); + } + return identities; +} + +async function main() { + identityControls(); + const driver = new Driver(database); + const client = new Client(driver).install(GENERATED_RUNTIME_MODULE).setDiagnosticSQLLogSink(undefined); + const context = new UserContext().insertResource('dataService', client); + const sql = new SQLExecutionEvidenceStore(); + const audits: Readonly>[] = []; + client.setAuditSink(event => { + // The sink sees committed, queryable rows, not an intermediate transaction. + assert.equal(driver.finishes.at(-1), 'commit', 'privacy audit escaped before database commit'); + audits.push(event); + }); + try { + await context.ensureSchema(); await context.ensureSchema(); + // Fixture setup through the runtime allocator, not generated ID setters or + // application SQL. Reserve unused IDs and align the two sequence floors so + // retained databases with different per-type histories still exercise the + // same-numeric-ID boundary. Gaps are intentional; no business row is reset. + await driver.transaction(async session => { + const rootID = await driver.nextId(session, 'CustomerOrder'); + const paymentID = await driver.nextId(session, 'Payment'); + const floor = String(Math.max(Number(rootID), Number(paymentID))); + await driver.ensureIdFloor(session, 'CustomerOrder', floor); + await driver.ensureIdFloor(session, 'Payment', floor); + }); + const roots = await Q.platforms().limit(2).comment('read default root').purpose('verify idempotent bootstrap').executeForList(context); + assert.equal(roots.length, 1); assert.equal(E.platform(roots[0]).id().eval(), '1'); + checks.push('generated bootstrap twice'); + client.commands.length = 0; audits.length = 0; + client.setRuntimeTelemetrySink(sql); + const graph = construct(context, 'normative'); + await graph.order.auditAs('submit order').save(context); + assert.equal(client.commands.length, 6); + assert.deepEqual(client.commands.map(command => plain(command.lineage)), expected(graph, 'submit order')); + const createdIdentities = graphIdentities(graph); + checkIdentities(createdIdentities, client.commands, 'create commands'); + checkIdentities(createdIdentities, checkPhysicalGraph(sql.snapshot(), expected(graph, 'submit order'), 'submit order', client.commands), 'create physical writes'); + checkIdentities(createdIdentities, auditIdentities(audits), 'create committed audit'); + assert.deepEqual(audits.map(event => plain(event.mutationLineage)), expected(graph, 'submit order')); + assert.equal(graph.order.id, graph.payment.id, 'aligned fixture must exercise same-ID/different-type identity'); + checks.push('generated six creates with assigned IDs and branch-local lineage'); + + client.commands.length = 0; audits.length = 0; sql.enableAll(); + graph.order.updateDescription('fixture-description-updated'); + graph.item.updateName('fixture-available-updated'); + graph.removed.markForDeletion().auditAs('remove unavailable item'); + graph.payment.updateReferenceCode('fixture-payment-updated'); + graph.attempt.updateReferenceCode('fixture-attempt-updated'); + graph.shipment.updateReferenceCode('fixture-shipment-updated'); + await graph.order.auditAs('submit order').save(context); + assert.deepEqual(client.commands.map(command => plain(command.lineage)), expected(graph, 'submit order', true)); + const wantIdentities = graphIdentities(graph); + checkIdentities(wantIdentities, client.commands, 'actual commands'); + const physicalIdentities = checkPhysicalGraph(sql.snapshot(), expected(graph, 'submit order', true), 'submit order', client.commands); + checkIdentities(wantIdentities, physicalIdentities, 'command-bound physical SQL'); + const committedIdentities = auditIdentities(audits); + checkIdentities(wantIdentities, committedIdentities, 'committed audit'); + assert.deepEqual(audits.map(event => plain(event.mutationLineage)), expected(graph, 'submit order', true)); + assert(sql.snapshot().every(entry => entry.auditReason === 'submit order' && entry.tracePath[0].name === 'CustomerOrder')); + assert.deepEqual(client.commands.map(command => command.action), ['Update', 'Update', 'Delete', 'Update', 'Update', 'Update']); + console.log('GRAPH IDENTITY EVIDENCE ' + JSON.stringify({ expected: wantIdentities, + commands: client.commands.map(({ entity, id }) => ({ entity, id })), physical: physicalIdentities, audit: committedIdentities })); + checks.push('generated normative update and child markForDeletion then root save'); + + sql.enableAll(); + const attempts = await Q.paymentAttempts().withIdIs(graph.attempt.id) + .selectPaymentWith(Q.payments().limit(1).selectCustomerOrderWith( + Q.customerOrders().limit(1).selectPlatformWith(Q.platforms().limit(1)))) + .limit(1).comment('load generated three-level graph').purpose('verify query lineage').executeForList(context); + assert.equal(attempts.length, 1); + assert.equal(E.paymentAttempt(attempts[0]).referenceCode().eval(), 'fixture-attempt-updated'); + assert.equal(E.paymentAttempt(attempts[0]).paymentId().eval(), graph.payment.id); + assert.equal(E.paymentAttempt(attempts[0]).payment().customerOrder().platform().id().eval(), '1'); + assert.deepEqual(sql.snapshot().map(entry => entry.tracePath.filter(node => node.kind === 'relation').map(node => [node.name, node.detail])), + [[], [['payment', 'PaymentAttempt.payment']], [['payment', 'PaymentAttempt.payment'], ['customerOrder', 'Payment.customerOrder']], + [['payment', 'PaymentAttempt.payment'], ['customerOrder', 'Payment.customerOrder'], ['platform', 'CustomerOrder.platform']]]); + assert(sql.snapshot().every(entry => entry.comment === 'load generated three-level graph')); + assert(sql.snapshot().every(entry => entry.purpose === 'verify query lineage')); + assert(sql.snapshot().every(entry => entry.tracePath[0].kind === 'operation' + && entry.tracePath[0].name === 'PaymentAttempt' + && entry.tracePath[1].kind === 'request' && entry.tracePath[1].name === 'PaymentAttempt' + && entry.tracePath.at(-2)?.kind === 'provider' + && entry.tracePath.at(-1)?.kind === 'sql' && entry.tracePath.at(-1)?.name === 'select')); + const qualifiedQueryRelations = [['payment', 'PaymentAttempt.payment'], + ['customerOrder', 'Payment.customerOrder'], ['platform', 'CustomerOrder.platform']]; + sql.snapshot().forEach((entry, depth) => assert.deepEqual( + entry.tracePath.map(node => [node.kind, node.name, node.detail ?? '']), + [['operation', 'PaymentAttempt', 'query'], ['request', 'PaymentAttempt', ''], + ...qualifiedQueryRelations.slice(0, depth).map(([name, detail]) => ['relation', name, detail]), + ['provider', 'sqlite', ''], ['sql', 'select', '']], + 'canonical generated path at every physical boundary')); + checks.push('generated bounded Q and E across three relation levels'); + + audits.length = 0; client.commands.length = 0; sql.enableAll(); + const first = construct(context, 'concurrent-first'), second = construct(context, 'concurrent-second'); + await Promise.all([first.order.auditAs('first independent operation').save(context), + second.order.auditAs('second independent operation').save(context)]); + for (const [graph, reason] of [[first, 'first independent operation'], [second, 'second independent operation']] as const) { + assert.deepEqual(audits.filter(event => event.reason === reason).map(event => plain(event.mutationLineage)), expected(graph, reason)); + const commands = client.commands.filter(command => command.lineage[0]?.detail === reason), want = graphIdentities(graph); + checkIdentities(want, commands, 'independent commands'); + checkIdentities(want, checkPhysicalGraph(sql.snapshot().filter(entry => entry.auditReason === reason), expected(graph, reason), reason, commands), 'independent physical writes'); + checkIdentities(want, auditIdentities(audits.filter(event => event.reason === reason)), 'independent committed audit'); + } + checks.push('generated overlapping graph saves on the same Context'); + + for (const readback of [false, true]) { + const failed = construct(context, `failed-${readback}`); + client.commands.length = 0; audits.length = 0; sql.enableAll(); + driver.failureTable = 'payment_data'; driver.readbackFailure = readback; + await assert.rejects(failed.order.auditAs('submit failing order').save(context), /injected trace-chain provider failure/); + assert.equal(audits.length, 0); + const last = sql.snapshot()[sql.snapshot().length - 1]; + assert.equal(last.executionOutcome, 'failure'); assert.equal(last.auditReason, 'submit failing order'); + assert.equal(last.mutationLineage?.length, 2); + assert.equal(last.mutationLineage?.[1].detail, 'authorize payment'); + if (readback) { + assert.equal(last.operation, 'select'); + assert.equal(sql.snapshot()[sql.snapshot().length - 2].executionOutcome, 'success'); + } + driver.failureTable = undefined; + const rows = await Q.customerOrders().withOrderNumberIs(`${nonce}-failed-${readback}`).limit(1) + .comment('inspect failed graph').purpose('verify atomic rollback').executeForList(context); + assert.equal(rows.length, 0); + } + checks.push('generated provider and readback failures retain trace and produce no committed audit'); + + for (const logging of [false, true]) { + const privacy = construct(context, `loaded-privacy-${logging}`); + privacy.item.updateName('PRIVATEOLDITEM'); + await privacy.order.auditAs('seed loaded privacy graph').save(context); + const loaded = (await Q.customerOrders().withIdIs(privacy.order.id) + .selectOrderItemListWith(Q.orderItems().limit(2)).limit(1) + .comment('load privacy graph').purpose('verify authoritative scalar snapshot').executeForList(context))[0]; + const item = loaded.orderItemList().find(row => row.id === privacy.item.id)!; + assert.equal(E.orderItem(item).name().eval(), 'PRIVATEOLDITEM'); + for (const [oldValue, newValue, fail] of [ + ['PRIVATEOLDITEM', 'PRIVATENEWITEM', false], + ['PRIVATENEWITEM', 'PRIVATEROLLBACKITEM', true], + ['PRIVATENEWITEM', 'PRIVATERETRYITEM', false], + ] as const) { + loaded.updateDescription(`privacy update ${newValue.length}`); + item.updateName(newValue); + audits.length = 0; sql.enableAll(); + client.commands.length = 0; client.rawRequests.length = 0; client.rawResults.length = 0; + driver.finishes.length = 0; driver.attemptedSQL.length = 0; + let precommitChecks = 0; + driver.beforeCommit = () => { assert.equal(audits.length, 0, 'privacy audit escaped before database commit'); precommitChecks++; }; + client.setQueryLoggingEnabled(logging).setMutationLoggingEnabled(logging); + driver.failureTable = fail ? 'order_item_data' : undefined; + driver.readbackFailure = fail; + const reason = `replace ${oldValue} with ${newValue}`; + const operation = loaded.auditAs(reason).save(context); + if (fail) await assert.rejects(operation, /injected trace-chain provider failure/); + else await operation; + const evidence = sql.snapshot(); + assert.equal(evidence.length, 4, 'parent and child writes plus both readbacks'); + assert(!JSON.stringify(evidence).includes(oldValue), 'old scalar leaked into graph SQL'); + assert(!JSON.stringify(evidence).includes(newValue), 'new scalar leaked into graph SQL'); + assert(!JSON.stringify(audits).includes(oldValue), 'old scalar leaked into graph audit'); + assert.equal(audits.length, fail ? 0 : 2); + checkPrivateGraph(client, driver, evidence, audits, loaded.id!, item.id!, reason, + [oldValue, newValue], newValue, fail, logging, fail ? 'rollback' : oldValue === 'PRIVATEOLDITEM' ? 'update' : 'retry', precommitChecks); + driver.beforeCommit = undefined; + driver.failureTable = undefined; + const persisted = (await Q.orderItems().withIdIs(item.id).limit(1) + .comment('verify item privacy mutation').purpose('check committed or rolled-back value').executeForList(context))[0]; + assert.equal(E.orderItem(persisted).name().eval(), fail ? oldValue : newValue); + } + // The private original remains provenance even when deletion binds only ID/version. + loaded.updateDescription('delete loaded private child'); item.markForDeletion(); + audits.length = 0; sql.enableAll(); + client.commands.length = 0; client.rawRequests.length = 0; client.rawResults.length = 0; + driver.finishes.length = 0; driver.attemptedSQL.length = 0; + let precommitChecks = 0; + driver.beforeCommit = () => { assert.equal(audits.length, 0, 'privacy audit escaped before database commit'); precommitChecks++; }; + const reason = 'remove PRIVATERETRYITEM'; + await loaded.auditAs(reason).save(context); + checkPrivateGraph(client, driver, sql.snapshot(), audits, loaded.id!, item.id!, reason, + ['PRIVATERETRYITEM'], undefined, false, logging, 'delete', precommitChecks); + driver.beforeCommit = undefined; + const missing = await Q.orderItems().withIdIs(item.id).limit(1) + .comment('verify loaded private child deletion').purpose('confirm soft-deleted row is hidden').executeForList(context); + assert.equal(missing.length, 0); + // No unrelated request may inherit the preceding graph's privacy snapshot. + sql.enableAll(); + await Q.platforms().limit(1).comment('independent PRIVATEOLDITEM').purpose('verify graph privacy isolation').executeForList(context); + assert.equal(sql.snapshot()[0].comment, 'independent PRIVATEOLDITEM'); + } + checks.push('generated loaded old-value privacy, committed refresh, rollback retry and independent request isolation'); + } finally { await client.close(); } + assert.equal(manifest('lib'), generatedBefore, 'application execution changed generated source'); + mkdirSync('evidence', { recursive: true }); + writeFileSync('evidence/generated-library-manifest.sha256', generatedBefore); + console.log(JSON.stringify({ database, nonce, checks, generatedSourceUnchanged: true })); + console.log(`PASS TypeScript generated trace-chain example: ${checks.length} checks`); +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/trace-chain/bootstrap-intent.ts b/source/teaql-ts/examples/trace-chain/bootstrap-intent.ts new file mode 100644 index 0000000000000000000000000000000000000000..a7dd1945513835c132f71911099811c8e5316270 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/bootstrap-intent.ts @@ -0,0 +1,160 @@ +import assert from 'node:assert/strict'; +import Database from 'better-sqlite3'; +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, readdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { MutationRequest, QueryRequest, UserContext } from 'teaql-ts'; +import { AbstractSQLTeaQLClient, MutationResult, SQLExecutionEvidenceStore, + SQLExecutionMetadata, SqlSession } from 'teaql-ts/sql/core'; +import { SQLiteDriver } from 'teaql-ts/sql/sqlite'; +import { Q } from './lib/src/generated/Q'; +import { GENERATED_RUNTIME_MODULE } from './lib/src/runtime-module'; + +// Mechanical fingerprints, not generated-source API discovery. +function fingerprint(directory: string, prefix = ''): string { + return readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)) + .map(entry => entry.isDirectory() ? fingerprint(join(directory, entry.name), `${prefix}${entry.name}/`) + : `${createHash('sha256').update(readFileSync(join(directory, entry.name))).digest('hex')} ${prefix}${entry.name}\n`).join(''); +} +const before = fingerprint('lib'); +const base = resolve(process.env.TEAQL_TRACE_CHAIN_BOOTSTRAP_DB ?? '.local/bootstrap-intent.sqlite'); +mkdirSync(join(base, '..'), { recursive: true }); + +class Driver extends SQLiteDriver { + active = false; + async transaction(work: (session: SqlSession) => Promise): Promise { + this.active = true; + try { return await super.transaction(work); } + finally { this.active = false; } + } +} +class Client extends AbstractSQLTeaQLClient { + readonly lookups: Array<{ comment: string; purpose: string; rows: number }> = []; + readonly commands: Array<{ request: MutationRequest; result: MutationResult }> = []; + constructor(driver: Driver) { super(driver, GENERATED_RUNTIME_MODULE.schemas); } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + const rows = await super.executeQuery(query); + this.lookups.push({ comment: request.comment, purpose: request.purpose, rows: rows.length }); + return rows; + } + async executeMutation(request: any): Promise { + assert(request instanceof MutationRequest, 'generated bootstrap owns a validated mutation request'); + const result = await super.executeMutation(request); + this.commands.push({ request, result }); + return result; + } +} +function route(entry: SQLExecutionMetadata, mutation: boolean): void { + assert.equal(entry.executionOutcome, 'success'); + assert.deepEqual(entry.tracePath.map(node => node.kind), + ['operation', mutation ? 'entity' : 'request', 'provider', 'sql']); + assert.equal(entry.tracePath[0].name, 'Platform'); + assert.equal(entry.tracePath[2].name, 'sqlite'); + assert.equal(entry.tracePath[3].name, entry.operation); +} +async function run(logging: boolean): Promise { + const database = `${base}.${logging ? 'on' : 'off'}`; + const driver = new Driver(database); + const client = new Client(driver).install(GENERATED_RUNTIME_MODULE); + const context = new UserContext().insertResource('dataService', client) + .insertResource('bootstrapActor', 'caller-before-bootstrap') + .insertResource('bootstrapCategory', 'caller-category'); + client.setUserContext(context); + const physical = new SQLExecutionEvidenceStore(); + const diagnostics: SQLExecutionMetadata[] = []; + const audits: Readonly>[] = []; + // Install every observer BEFORE schema/startup; never replace the module's bootstrap. + client.setQueryLoggingEnabled(logging).setMutationLoggingEnabled(logging) + .setRuntimeTelemetrySink(physical) + .setDiagnosticSQLLogSink({ write: entry => diagnostics.push(entry) }) + .setAuditSink(event => { + assert.equal(driver.active, false, 'audit callback must run after transaction commit'); + const reader = new Database(database, { readonly: true }); + try { + assert.deepEqual(reader.prepare('SELECT id, version, name FROM platform_data WHERE id = 1').get(), + { id: 1, version: 1, name: 'Trace Chain Verification' }, 'independent connection sees committed bootstrap'); + } finally { reader.close(); } + audits.push(event); + }); + const restored = () => { + assert.equal(context.getResource('bootstrapActor'), 'caller-before-bootstrap'); + assert.equal(context.getResource('bootstrapCategory'), 'caller-category'); + assert.equal(context.getResource('dataService'), client); + }; + try { + await context.ensureSchema(); + restored(); + assert.equal(client.lookups.length, 1, 'one actual generated root lookup'); + const lookup = client.lookups[0]; + assert(lookup.comment.trim() && lookup.purpose.trim(), 'runtime owns nonblank bootstrap query intent'); + const firstWrites = client.commands.length; + assert(firstWrites === 0 || firstWrites === 1); + assert.equal(lookup.rows, firstWrites ? 0 : 1); + assert.equal(audits.length, firstWrites); + const entries = physical.snapshot(); + assert.equal(entries.length, 1 + 2 * firstWrites, 'real root lookup plus optional write/readback'); + assert.equal(diagnostics.length, logging ? entries.length : 0); + route(entries[0], false); + assert.equal(entries[0].comment, lookup.comment); + assert.equal(entries[0].purpose, lookup.purpose); + assert.equal(entries[0].resultCount, lookup.rows); + if (firstWrites) { + const { request, result } = client.commands[0]; + assert.equal(request.mutation.entity, 'Platform'); + assert.equal(request.mutation.action, 'Create'); + assert(request.comment.trim(), 'runtime owns nonblank bootstrap mutation intent'); + assert.equal(result.id, '1'); assert.equal(result.version, 1); + const lineage = request.traceFor({ entity: 'Platform', id: result.id }); + assert.deepEqual(lineage.map(node => [node.kind, node.name, node.entityId, node.detail]), + [['auditReason', 'Platform', '1', request.comment]]); + assert.equal(result.metadata?.statements?.length, 2); + const [write, readback] = result.metadata!.statements!; + route(write, true); route(readback, false); + assert.equal(write.operation, 'insert'); assert.equal(write.affectedRows, 1); + assert.equal(readback.operation, 'select'); assert.equal(readback.resultCount, 1); + for (const raw of [write, readback]) { + assert.equal(raw.auditReason, request.comment); + assert.deepEqual(raw.mutationLineage, lineage); + } + assert.equal(readback.comment, request.comment); + assert.equal(readback.purpose, 'verify persisted mutation result'); + const expected = request.auditProjection({ entity: 'Platform', id: result.id }, request.mutation.payload); + assert.equal(audits[0].actor, 'teaql-generated-bootstrap'); + assert.equal(audits[0].category, 'runtime-bootstrap'); + assert.equal(audits[0].entity, 'Platform'); assert.equal(audits[0].id, '1'); + assert.equal(audits[0].reason, expected.reason); + assert.deepEqual(audits[0].mutationLineage, expected.mutationLineage); + for (const safe of entries.slice(1)) { + route(safe, safe.operation === 'insert'); + assert.equal(safe.auditReason, expected.reason); + assert.deepEqual(safe.mutationLineage, expected.mutationLineage); + } + } + physical.enableAll(); diagnostics.length = 0; audits.length = 0; + client.lookups.length = 0; client.commands.length = 0; + await context.ensureSchema(); + restored(); + assert.equal(client.commands.length, 0); assert.equal(audits.length, 0); + assert.deepEqual(client.lookups, [{ ...lookup, rows: 1 }], 'repeated startup owns identical query intent'); + assert.equal(client.lookups[0].comment, lookup.comment); + assert.equal(physical.snapshot().length, 1); + assert.equal(diagnostics.length, logging ? 1 : 0); + route(physical.snapshot()[0], false); + assert.equal(physical.snapshot()[0].comment, lookup.comment); + assert.equal(physical.snapshot()[0].purpose, lookup.purpose); + const roots = await Q.platforms().withIdIs('1').limit(1) + .comment('read bootstrap root').purpose('verify generated bootstrap persistence').executeForList(context); + assert.equal(roots.length, 1); assert.equal(roots[0].id, '1'); assert.equal(roots[0].version, 1); + console.log(JSON.stringify({ case: 'TC-REQ-09', path: 'generated default bootstrap', logging, + firstWrites, repeatWrites: 0, committedAudits: firstWrites, + physicalStatements: entries.length, diagnostics: logging ? entries.length : 0, + comment: lookup.comment, purpose: lookup.purpose, restoredContext: true })); + } finally { await client.close(); } +} +async function main(): Promise { + for (const logging of [false, true]) await run(logging); + assert.equal(fingerprint('lib'), before); + console.log('PASS TypeScript generated bootstrap intent: logging off/on, committed audit, repeat no writes, unchanged generated library'); +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/trace-chain/checker-overlap.ts b/source/teaql-ts/examples/trace-chain/checker-overlap.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb4909fa93e88ee2d654805346a84c4c18b46c30 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/checker-overlap.ts @@ -0,0 +1,213 @@ +import assert from 'node:assert/strict'; +import { randomUUID, createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { CheckException, EntityRoot, GraphMutationSession, MutationIntent, MutationRequest, TraceNode, UserContext } from 'teaql-ts'; +import { AbstractSQLTeaQLClient, MutationResult, SQLExecutionEvidenceStore, SQLExecutionMetadata, SqlQueryResult, SqlSession } from 'teaql-ts/sql/core'; +import { SQLiteDriver } from 'teaql-ts/sql/sqlite'; +import { Q } from './lib/src/generated/Q'; +import { E } from './lib/src/generated/E'; +import { GENERATED_RUNTIME_MODULE } from './lib/src/runtime-module'; + +// Mechanical fingerprinting only: never inspect generated source for APIs. +function manifest(directory: string, prefix = ''): string { + return readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)) + .map(entry => entry.isDirectory() ? manifest(join(directory, entry.name), `${prefix}${entry.name}/`) + : `${createHash('sha256').update(readFileSync(join(directory, entry.name))).digest('hex')} ${prefix}${entry.name}\n`).join(''); +} +const before = manifest('lib'); +const database = resolve(process.env.TEAQL_TRACE_CHAIN_CHECKER_DB ?? '.local/checker-overlap.sqlite'); +const evidence = resolve(process.env.TEAQL_TRACE_CHAIN_CHECKER_EVIDENCE ?? '.local/checker-overlap-evidence'); +const attempt = process.env.TEAQL_TRACE_CHAIN_CHECKER_RUN ?? 'manual'; +mkdirSync(join(database, '..'), { recursive: true }); mkdirSync(evidence, { recursive: true }); +writeFileSync(join(evidence, `${attempt}-library-before.sha256`), before); +const nonce = randomUUID(); +const ledger = (entity: unknown): EntityRoot => (entity as { _root: EntityRoot })._root; +const plain = (nodes: unknown) => (nodes as readonly TraceNode[]).map(node => [node.kind, node.name, node.entityId, node.detail]); +type Transaction = { reason?: string; outcome: 'pending' | 'commit' | 'rollback'; sql: string[] }; +class Driver extends SQLiteDriver { + readonly transactions: Transaction[] = []; + current?: Transaction; + async transaction(work: (session: SqlSession) => Promise): Promise { + assert.equal(this.current, undefined, 'the real SQLite transaction gate must serialize writers'); + const transaction: Transaction = { outcome: 'pending', sql: [] }; + this.transactions.push(transaction); this.current = transaction; + try { const result = await super.transaction(work); transaction.outcome = 'commit'; return result; } + catch (error) { transaction.outcome = 'rollback'; throw error; } + finally { this.current = undefined; } + } + async query(sql: string, values: any[] = []): Promise { + this.current?.sql.push(sql); + return super.query(sql, values); + } +} +class Client extends AbstractSQLTeaQLClient { + readonly commands: Array<{ entity: string; id: string; reason: string; lineage: readonly TraceNode[] }> = []; + readonly physical: SQLExecutionMetadata[] = []; + readonly preflights: Array<{ entity: string; reason: string; rejected: boolean }> = []; + readonly snapshots = new Map>>(); + readonly sharedSnapshots: unknown[] = []; + activeSaves = 0; maxSaves = 0; activeCallbacks = 0; maxCallbacks = 0; + constructor(readonly observedDriver: Driver) { super(observedDriver, GENERATED_RUNTIME_MODULE.schemas); } + async executeQuery(query: any): Promise { + const rows = await super.executeQuery(query); + for (const row of rows) if (row.platform && typeof row.platform === 'object') { + const key = `${row.platform.id}:${row.platform.version}`; + let snapshot = this.snapshots.get(key); + if (!snapshot) { + const loaded: Readonly> = Object.freeze({ ...row.platform }); + this.snapshots.set(key, loaded); snapshot = loaded; + } + row.platform = snapshot; this.sharedSnapshots.push(snapshot); + } + return rows; + } + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + this.activeSaves++; this.maxSaves = Math.max(this.maxSaves, this.activeSaves); + try { + return await super.executeGraphSave(intent, async graph => { + this.activeCallbacks++; this.maxCallbacks = Math.max(this.maxCallbacks, this.activeCallbacks); + assert(this.observedDriver.current); this.observedDriver.current.reason = intent.comment; + try { return await work(graph); } finally { this.activeCallbacks--; } + }); + } finally { this.activeSaves--; } + } + preflightMutation(input: any): any { + assert(input instanceof MutationRequest); + const entry = { entity: input.mutation.entity, reason: input.comment, rejected: false }; + this.preflights.push(entry); + try { return super.preflightMutation(input); } + catch (error) { entry.rejected = error instanceof CheckException; throw error; } + } + async executeMutation(input: any): Promise { + assert(input instanceof MutationRequest); + // Record entry, not only successful completion: rejected graphs must never get here. + const entry = { entity: input.mutation.entity, id: String(input.mutation.id), reason: input.comment, + lineage: input.traceFor({ entity: input.mutation.entity, id: input.mutation.id }) }; + this.commands.push(entry); + const result = await super.executeMutation(input); + entry.id = result.id; + this.physical.push(...result.metadata!.statements!); + return result; + } +} + +async function main() { + const driver = new Driver(database); + const client = new Client(driver).install(GENERATED_RUNTIME_MODULE); + const context = new UserContext().insertResource('dataService', client); + client.setUserContext(context); + const sql = new SQLExecutionEvidenceStore(); + const diagnostics: SQLExecutionMetadata[] = []; + const audit: Readonly>[] = []; + client.setRuntimeTelemetrySink(sql).setDiagnosticSQLLogSink({ write: entry => diagnostics.push(entry) }) + .setAuditSink(event => { audit.push(event); }); + assert(GENERATED_RUNTIME_MODULE.checkers.CustomerOrder); + assert(GENERATED_RUNTIME_MODULE.checkers.OrderItem); + const reset = () => { + client.commands.length = 0; client.physical.length = 0; client.preflights.length = 0; + audit.length = 0; diagnostics.length = 0; driver.transactions.length = 0; + client.maxSaves = 0; client.maxCallbacks = 0; sql.enableAll(); + }; + const create = async (suffix: string) => { + const root = Q.customerOrders().comment('initialize Checker overlap fixture').purpose('verify generated validation') + .newEntity(context).updatePlatform('1').updateOrderNumber(`${nonce}-${suffix}`).updateDescription(`before-${suffix}`); + root.orderItemList().push(Q.orderItems().comment('initialize Checker item').purpose('verify generated validation') + .newEntity(context).updateName(`${nonce}-${suffix}-item`)); + await root.auditAs('seed Checker overlap fixture').save(context); + return root; + }; + const load = async (id: string) => { + const rows = await Q.customerOrders().withIdIs(id).selectPlatformWith(Q.platforms().limit(1)) + .selectOrderItemListWith(Q.orderItems().limit(10)).limit(1) + .comment('load complete Checker graph').purpose('retain optimistic versions and readonly references').executeForList(context); + assert.equal(rows.length, 1); return rows[0]; + }; + try { + await context.ensureSchema(); await context.ensureSchema(); + for (const logging of [false, true]) for (const invalidFirst of [false, true]) { + client.setQueryLoggingEnabled(logging).setMutationLoggingEnabled(logging); + const suffix = `${logging}-${invalidFirst}`; + const a = await create(`valid-${suffix}`), b = await create(`invalid-${suffix}`); + client.sharedSnapshots.length = 0; + const valid = await load(a.id!), invalid = await load(b.id!); + const platformA = E.customerOrder(valid).platform().eval()!, platformB = E.customerOrder(invalid).platform().eval()!; + assert.equal(client.sharedSnapshots[0], client.sharedSnapshots[1]); + assert(Object.isFrozen(client.sharedSnapshots[0])); + assert.notEqual(platformA, platformB); assert.notEqual(ledger(valid), ledger(invalid)); + const platformVersion = E.platform(platformA).version().eval(); + const invalidVersion = E.customerOrder(invalid).version().eval(); + const invalidDescription = E.customerOrder(invalid).description().eval(); + const validReason = `accept graph ${suffix}`, invalidReason = `reject graph ${suffix}`; + valid.updateDescription(`accepted-${nonce}-${suffix}`); + valid.orderItemList()[0].updateName(`accepted-child-${nonce}-${suffix}`).auditAs('accepted child responsibility'); + invalid.updateDescription(`must-remain-pending-${nonce}-${suffix}`); + const missingName = Q.orderItems().comment('initialize invalid child').purpose('verify real required-field Checker') + .newEntity(context).auditAs('rejected child responsibility'); + invalid.orderItemList().push(missingName); + reset(); + const jobs = invalidFirst + ? [invalid.auditAs(invalidReason).save(context), valid.auditAs(validReason).save(context)] + : [valid.auditAs(validReason).save(context), invalid.auditAs(invalidReason).save(context)]; + const settled = await Promise.allSettled(jobs); + const accepted = settled[invalidFirst ? 1 : 0], rejected = settled[invalidFirst ? 0 : 1]; + assert.equal(accepted.status, 'fulfilled'); assert.equal(rejected.status, 'rejected'); + if (rejected.status !== 'rejected') throw new Error('missing generated Checker rejection'); + assert(rejected.reason instanceof CheckException); + assert(rejected.reason.violations.some((v: { ruleId: string; location: { nativePath(): string } }) => + v.ruleId.toLowerCase() === 'required' && v.location.nativePath() === 'orderItemList[1].name'), JSON.stringify(rejected.reason.violations)); + assert.equal(client.maxSaves, 2, 'both public Save invocations must be live'); + assert.equal(client.maxCallbacks, 1, 'runtime gate serializes Checker/work callbacks'); + assert(client.preflights.some(p => p.entity === 'OrderItem' && p.reason === invalidReason && p.rejected)); + assert(client.preflights.some(p => p.entity === 'OrderItem' && p.reason === validReason && !p.rejected)); + assert.deepEqual(client.commands.map(c => [c.entity, c.id, c.reason]), + [['CustomerOrder', valid.id, validReason], ['OrderItem', valid.orderItemList()[0].id, validReason]]); + assert.equal(audit.length, 2); assert.equal(client.physical.length, 4); assert.equal(sql.snapshot().length, 4); + assert.equal(diagnostics.length, logging ? 4 : 0); + const expected = [[['auditReason', 'CustomerOrder', valid.id, validReason]], + [['auditReason', 'CustomerOrder', valid.id, validReason], + ['auditReason', 'OrderItem', valid.orderItemList()[0].id, 'accepted child responsibility']]]; + assert.deepEqual(client.commands.map(c => plain(c.lineage)), expected); + assert.deepEqual(audit.map(event => plain(event.mutationLineage)), expected); + assert.deepEqual(client.physical.map(entry => plain(entry.mutationLineage)), expected.flatMap(chain => [chain, chain])); + assert.equal(driver.transactions.length, 2); + const failed = driver.transactions.find(t => t.reason === invalidReason)!; + assert.equal(failed.outcome, 'rollback'); assert.deepEqual(failed.sql, [], 'no ID allocation or business SQL before Checker rejection'); + assert.equal(driver.transactions.find(t => t.reason === validReason)!.outcome, 'commit'); + assert.equal(ledger(platformA).snapshot().length, 0); assert.equal(ledger(platformB).snapshot().length, 0); + assert.equal(E.platform(platformA).version().eval(), platformVersion); + assert.equal(context.getResource('fixTime'), undefined); assert.equal(context.getResource('fixEvidenceCurrent'), undefined); + const observation = { logging, invalidFirst, publicOverlap: client.maxSaves, serializedCallbacks: client.maxCallbacks, + violations: rejected.reason.violations, preflights: client.preflights.slice(), commands: client.commands.slice(), + statements: sql.snapshot(), committedAudit: audit.slice(), transactions: driver.transactions.slice() }; + const storedValid = await load(valid.id!), storedInvalid = await load(invalid.id!); + assert.equal(E.customerOrder(storedValid).description().eval(), `accepted-${nonce}-${suffix}`); + assert.equal(E.orderItem(storedValid.orderItemList()[0]).name().eval(), `accepted-child-${nonce}-${suffix}`); + assert.equal(E.customerOrder(storedInvalid).description().eval(), invalidDescription); + assert.equal(E.customerOrder(storedInvalid).version().eval(), invalidVersion); + assert.equal(storedInvalid.orderItemList().length, 1); + assert.equal(E.platform(E.customerOrder(storedInvalid).platform().eval()!).version().eval(), platformVersion); + assert.equal(ledger(invalid).change({ entity: 'CustomerOrder', id: invalid.id! }).description, + `must-remain-pending-${nonce}-${suffix}`); + reset(); + const nextReason = `independent after rejection ${suffix}`; + storedInvalid.updateDescription(`next-${nonce}-${suffix}`); + await storedInvalid.auditAs(nextReason).save(context); + assert.equal(client.commands.length, 1); assert.equal(audit.length, 1); + assert.equal(client.commands[0].reason, nextReason); + const nextLineage = [['auditReason', 'CustomerOrder', invalid.id, nextReason]]; + assert.deepEqual(plain(client.commands[0].lineage), nextLineage); + assert.deepEqual(plain(audit[0].mutationLineage), nextLineage); + assert.deepEqual(client.physical.map(entry => plain(entry.mutationLineage)), [nextLineage, nextLineage]); + assert.equal(sql.snapshot().length, 2); assert.equal(diagnostics.length, logging ? 2 : 0); + assert.equal(context.getResource('fixTime'), undefined); assert.equal(context.getResource('fixEvidenceCurrent'), undefined); + assert.equal(E.customerOrder(await load(invalid.id!)).description().eval(), `next-${nonce}-${suffix}`); + console.log(JSON.stringify({ ...observation, nextIndependentSave: 'committed', sharedReadonlyReference: true })); + } + } finally { await client.close(); } + const after = manifest('lib'); assert.equal(after, before); + writeFileSync(join(evidence, `${attempt}-library-after.sha256`), after); + console.log(JSON.stringify({ database, nonce, attempt, generatedFiles: before.trim().split('\n').length, generatedSourceUnchanged: true })); + console.log('PASS TypeScript generated Checker overlap: 4 scenarios; real Required rejection, no rejected commands/business SQL/audit; transactions serialized'); +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/customer_order.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/customer_order.md new file mode 100644 index 0000000000000000000000000000000000000000..cc4a01c5b2b9fdbcd6097efce458f47c74e3c40b --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/customer_order.md @@ -0,0 +1,103 @@ + + +# TypeScript Assist — Create `Customer Order` + +Use the exact generated `Q.customerOrders()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { UserContext } from '../teaql-ts'; +import { Q } from './Q'; +import { CustomerOrder } from './models/CustomerOrder'; + +export interface CreateCustomerOrderInput { + platform: string | number; + orderNumber: string; + description: string; + +} + +export async function createCustomerOrder( + input: CreateCustomerOrderInput, + context: UserContext, +): Promise { + const entity = Q.customerOrders() + .comment('what: initialize Customer Order') + .purpose('why: create Customer Order') + .newEntity(context); + + entity.updatePlatform(input.platform); + entity.updateOrderNumber(input.orderNumber); + entity.updateDescription(input.description); + + await entity + .auditAs('Create Customer Order for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + +## Compose one audited graph + +Create each child using its own generated Q entry point and Create Assist, then +attach it with the exact model-derived collection API: + +| Reverse relation | Child entry point | Attach | +| --- | --- | --- | +| `order_item_list` | `Q.orderItems()` | `entity.orderItemList().push(child)` | +| `payment_list` | `Q.payments()` | `entity.paymentList().push(child)` | +| `shipment_list` | `Q.shipments()` | `entity.shipmentList().push(child)` | + + +Use `child.auditAs('authorize payment')` to add a local reason. Leave it unset +to inherit the root reason; creation-query comment is separate. Keep an existing +child marked with `child.markForDeletion().auditAs('remove unavailable item')` +in the composed graph. Call only `entity.auditAs('submit order').save(context)` +on the root. Generated cascades preserve branch-local reasons and assigned IDs; +the runtime emits committed audit only after the complete graph commits. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/order_item.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/order_item.md new file mode 100644 index 0000000000000000000000000000000000000000..4f9b289ba9235f6be3970a3c792fc91c8f317761 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/order_item.md @@ -0,0 +1,82 @@ + + +# TypeScript Assist — Create `Order Item` + +Use the exact generated `Q.orderItems()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { UserContext } from '../teaql-ts'; +import { Q } from './Q'; +import { OrderItem } from './models/OrderItem'; + +export interface CreateOrderItemInput { + customerOrder: string | number; + name: string; + +} + +export async function createOrderItem( + input: CreateOrderItemInput, + context: UserContext, +): Promise { + const entity = Q.orderItems() + .comment('what: initialize Order Item') + .purpose('why: create Order Item') + .newEntity(context); + + entity.updateCustomerOrder(input.customerOrder); + entity.updateName(input.name); + + await entity + .auditAs('Create Order Item for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/payment.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/payment.md new file mode 100644 index 0000000000000000000000000000000000000000..83e24739dcd5ade380006b6d09c0bf173e980580 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/payment.md @@ -0,0 +1,99 @@ + + +# TypeScript Assist — Create `Payment` + +Use the exact generated `Q.payments()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { UserContext } from '../teaql-ts'; +import { Q } from './Q'; +import { Payment } from './models/Payment'; + +export interface CreatePaymentInput { + customerOrder: string | number; + referenceCode: string; + +} + +export async function createPayment( + input: CreatePaymentInput, + context: UserContext, +): Promise { + const entity = Q.payments() + .comment('what: initialize Payment') + .purpose('why: create Payment') + .newEntity(context); + + entity.updateCustomerOrder(input.customerOrder); + entity.updateReferenceCode(input.referenceCode); + + await entity + .auditAs('Create Payment for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + +## Compose one audited graph + +Create each child using its own generated Q entry point and Create Assist, then +attach it with the exact model-derived collection API: + +| Reverse relation | Child entry point | Attach | +| --- | --- | --- | +| `payment_attempt_list` | `Q.paymentAttempts()` | `entity.paymentAttemptList().push(child)` | + + +Use `child.auditAs('authorize payment')` to add a local reason. Leave it unset +to inherit the root reason; creation-query comment is separate. Keep an existing +child marked with `child.markForDeletion().auditAs('remove unavailable item')` +in the composed graph. Call only `entity.auditAs('submit order').save(context)` +on the root. Generated cascades preserve branch-local reasons and assigned IDs; +the runtime emits committed audit only after the complete graph commits. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/payment_attempt.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/payment_attempt.md new file mode 100644 index 0000000000000000000000000000000000000000..cecc4cb1796cb99686baa5e7f3c5ba965cfdbe78 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/payment_attempt.md @@ -0,0 +1,82 @@ + + +# TypeScript Assist — Create `Payment Attempt` + +Use the exact generated `Q.paymentAttempts()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { UserContext } from '../teaql-ts'; +import { Q } from './Q'; +import { PaymentAttempt } from './models/PaymentAttempt'; + +export interface CreatePaymentAttemptInput { + payment: string | number; + referenceCode: string; + +} + +export async function createPaymentAttempt( + input: CreatePaymentAttemptInput, + context: UserContext, +): Promise { + const entity = Q.paymentAttempts() + .comment('what: initialize Payment Attempt') + .purpose('why: create Payment Attempt') + .newEntity(context); + + entity.updatePayment(input.payment); + entity.updateReferenceCode(input.referenceCode); + + await entity + .auditAs('Create Payment Attempt for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/shipment.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/shipment.md new file mode 100644 index 0000000000000000000000000000000000000000..cc10f1c08bff511026c449c3a614ae0c0cecd844 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-create/shipment.md @@ -0,0 +1,82 @@ + + +# TypeScript Assist — Create `Shipment` + +Use the exact generated `Q.shipments()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { UserContext } from '../teaql-ts'; +import { Q } from './Q'; +import { Shipment } from './models/Shipment'; + +export interface CreateShipmentInput { + customerOrder: string | number; + referenceCode: string; + +} + +export async function createShipment( + input: CreateShipmentInput, + context: UserContext, +): Promise { + const entity = Q.shipments() + .comment('what: initialize Shipment') + .purpose('why: create Shipment') + .newEntity(context); + + entity.updateCustomerOrder(input.customerOrder); + entity.updateReferenceCode(input.referenceCode); + + await entity + .auditAs('Create Shipment for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-delete/order_item.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-delete/order_item.md new file mode 100644 index 0000000000000000000000000000000000000000..62391c50eae2b5ca0143538c75f42f87cbbe0108 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-delete/order_item.md @@ -0,0 +1,72 @@ + + +# TypeScript Assist — Delete `Order Item` + +Load the current row and its original optimistic version. Never reconstruct an +entity from client-supplied ID/version. Delete is audited, version-aware soft +deletion; do not invent physical-delete APIs. + +```typescript +import { Q } from './Q'; +import { UserContext } from '../teaql-ts'; + +export async function deleteOrderItem( + id: string, + context: UserContext, +): Promise { + const entity = await Q.orderItems() + .withIdIs(id) + + .comment('what: load current Order Item for deletion') + .purpose('why: preserve original version for optimistic locking') + .executeForOne(context); + if (!entity) return false; + + await entity.markForDeletion() + .auditAs('Delete Order Item for the requested business operation') + .save(context); + return true; +} +``` + +Compile the source unchanged. Prove retained negative-version persistence, +normal-query hiding, `deletedRowsOnly()` visibility, stale-copy rejection, +not-found false, audit enforcement, and physical-delete compilation failure. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `delete`. + +- Load the policy-scoped current entity, mark it for deletion, then use audited + save with the same UserContext. Do not invent a physical-delete API. +- Require an audit reason and optimistic version. Test missing audit and stale + version as explicit failures. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/customer_order.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/customer_order.md new file mode 100644 index 0000000000000000000000000000000000000000..511acb574be598d75de7ded3406cac64410db33f --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/customer_order.md @@ -0,0 +1,141 @@ + + +# TypeScript Assist — Expression `Customer Order` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +```typescript +import { E } from './E'; +import { CustomerOrder } from './models/CustomerOrder'; + +export function extractId(entity: CustomerOrder) { + return E.customerOrder(entity).id().eval(); +} + +export function extractIdOrElse( + entity: CustomerOrder, fallback: NonNullable, +) { + return E.customerOrder(entity).id().orElse(fallback); +} + +export function extractOrderNumber(entity: CustomerOrder) { + return E.customerOrder(entity).orderNumber().eval(); +} + +export function extractOrderNumberOrElse( + entity: CustomerOrder, fallback: NonNullable, +) { + return E.customerOrder(entity).orderNumber().orElse(fallback); +} + +export function extractDescription(entity: CustomerOrder) { + return E.customerOrder(entity).description().eval(); +} + +export function extractDescriptionOrElse( + entity: CustomerOrder, fallback: NonNullable, +) { + return E.customerOrder(entity).description().orElse(fallback); +} + +export function extractVersion(entity: CustomerOrder) { + return E.customerOrder(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: CustomerOrder, fallback: NonNullable, +) { + return E.customerOrder(entity).version().orElse(fallback); +} + +export function extractPlatformId(entity: CustomerOrder) { + return E.customerOrder(entity).platformId().eval(); +} + +export function traversePlatform(entity: CustomerOrder) { + return E.customerOrder(entity).platform().eval(); +} + +export function aggregateOrderItemListSize(entity: CustomerOrder) { + return E.customerOrder(entity).orderItemList().size().eval(); +} + +export function firstOrderItemListId(entity: CustomerOrder) { + return E.customerOrder(entity).orderItemList().first().id().eval(); +} + +export function getOrderItemListId(entity: CustomerOrder, index: number) { + return E.customerOrder(entity).orderItemList().get(index).id().eval(); +} + +export function aggregatePaymentListSize(entity: CustomerOrder) { + return E.customerOrder(entity).paymentList().size().eval(); +} + +export function firstPaymentListId(entity: CustomerOrder) { + return E.customerOrder(entity).paymentList().first().id().eval(); +} + +export function getPaymentListId(entity: CustomerOrder, index: number) { + return E.customerOrder(entity).paymentList().get(index).id().eval(); +} + +export function aggregateShipmentListSize(entity: CustomerOrder) { + return E.customerOrder(entity).shipmentList().size().eval(); +} + +export function firstShipmentListId(entity: CustomerOrder) { + return E.customerOrder(entity).shipmentList().first().id().eval(); +} + +export function getShipmentListId(entity: CustomerOrder, index: number) { + return E.customerOrder(entity).shipmentList().get(index).id().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/order_item.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/order_item.md new file mode 100644 index 0000000000000000000000000000000000000000..05e4381e00eb49612ae7300abfd7caa24391cd60 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/order_item.md @@ -0,0 +1,95 @@ + + +# TypeScript Assist — Expression `Order Item` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +```typescript +import { E } from './E'; +import { OrderItem } from './models/OrderItem'; + +export function extractId(entity: OrderItem) { + return E.orderItem(entity).id().eval(); +} + +export function extractIdOrElse( + entity: OrderItem, fallback: NonNullable, +) { + return E.orderItem(entity).id().orElse(fallback); +} + +export function extractName(entity: OrderItem) { + return E.orderItem(entity).name().eval(); +} + +export function extractNameOrElse( + entity: OrderItem, fallback: NonNullable, +) { + return E.orderItem(entity).name().orElse(fallback); +} + +export function extractVersion(entity: OrderItem) { + return E.orderItem(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: OrderItem, fallback: NonNullable, +) { + return E.orderItem(entity).version().orElse(fallback); +} + +export function extractCustomerOrderId(entity: OrderItem) { + return E.orderItem(entity).customerOrderId().eval(); +} + +export function traverseCustomerOrder(entity: OrderItem) { + return E.orderItem(entity).customerOrder().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/payment.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/payment.md new file mode 100644 index 0000000000000000000000000000000000000000..be2241337b99f64841691b348dd6c12a7faed631 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/payment.md @@ -0,0 +1,107 @@ + + +# TypeScript Assist — Expression `Payment` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +```typescript +import { E } from './E'; +import { Payment } from './models/Payment'; + +export function extractId(entity: Payment) { + return E.payment(entity).id().eval(); +} + +export function extractIdOrElse( + entity: Payment, fallback: NonNullable, +) { + return E.payment(entity).id().orElse(fallback); +} + +export function extractReferenceCode(entity: Payment) { + return E.payment(entity).referenceCode().eval(); +} + +export function extractReferenceCodeOrElse( + entity: Payment, fallback: NonNullable, +) { + return E.payment(entity).referenceCode().orElse(fallback); +} + +export function extractVersion(entity: Payment) { + return E.payment(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: Payment, fallback: NonNullable, +) { + return E.payment(entity).version().orElse(fallback); +} + +export function extractCustomerOrderId(entity: Payment) { + return E.payment(entity).customerOrderId().eval(); +} + +export function traverseCustomerOrder(entity: Payment) { + return E.payment(entity).customerOrder().eval(); +} + +export function aggregatePaymentAttemptListSize(entity: Payment) { + return E.payment(entity).paymentAttemptList().size().eval(); +} + +export function firstPaymentAttemptListId(entity: Payment) { + return E.payment(entity).paymentAttemptList().first().id().eval(); +} + +export function getPaymentAttemptListId(entity: Payment, index: number) { + return E.payment(entity).paymentAttemptList().get(index).id().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/payment_attempt.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/payment_attempt.md new file mode 100644 index 0000000000000000000000000000000000000000..fca1f909aa546925e8b58022896e9b24b308a642 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/payment_attempt.md @@ -0,0 +1,95 @@ + + +# TypeScript Assist — Expression `Payment Attempt` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +```typescript +import { E } from './E'; +import { PaymentAttempt } from './models/PaymentAttempt'; + +export function extractId(entity: PaymentAttempt) { + return E.paymentAttempt(entity).id().eval(); +} + +export function extractIdOrElse( + entity: PaymentAttempt, fallback: NonNullable, +) { + return E.paymentAttempt(entity).id().orElse(fallback); +} + +export function extractReferenceCode(entity: PaymentAttempt) { + return E.paymentAttempt(entity).referenceCode().eval(); +} + +export function extractReferenceCodeOrElse( + entity: PaymentAttempt, fallback: NonNullable, +) { + return E.paymentAttempt(entity).referenceCode().orElse(fallback); +} + +export function extractVersion(entity: PaymentAttempt) { + return E.paymentAttempt(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: PaymentAttempt, fallback: NonNullable, +) { + return E.paymentAttempt(entity).version().orElse(fallback); +} + +export function extractPaymentId(entity: PaymentAttempt) { + return E.paymentAttempt(entity).paymentId().eval(); +} + +export function traversePayment(entity: PaymentAttempt) { + return E.paymentAttempt(entity).payment().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/platform.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/platform.md new file mode 100644 index 0000000000000000000000000000000000000000..1ea5836c9c1a77ad79bddee5eaaed65fb591a710 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-expression/platform.md @@ -0,0 +1,99 @@ + + +# TypeScript Assist — Expression `Platform` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +```typescript +import { E } from './E'; +import { Platform } from './models/Platform'; + +export function extractId(entity: Platform) { + return E.platform(entity).id().eval(); +} + +export function extractIdOrElse( + entity: Platform, fallback: NonNullable, +) { + return E.platform(entity).id().orElse(fallback); +} + +export function extractName(entity: Platform) { + return E.platform(entity).name().eval(); +} + +export function extractNameOrElse( + entity: Platform, fallback: NonNullable, +) { + return E.platform(entity).name().orElse(fallback); +} + +export function extractVersion(entity: Platform) { + return E.platform(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: Platform, fallback: NonNullable, +) { + return E.platform(entity).version().orElse(fallback); +} + +export function aggregateCustomerOrderListSize(entity: Platform) { + return E.platform(entity).customerOrderList().size().eval(); +} + +export function firstCustomerOrderListId(entity: Platform) { + return E.platform(entity).customerOrderList().first().id().eval(); +} + +export function getCustomerOrderListId(entity: Platform, index: number) { + return E.platform(entity).customerOrderList().get(index).id().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-list-page/customer_order.md b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-list-page/customer_order.md new file mode 100644 index 0000000000000000000000000000000000000000..6a93a41a3ecf394f26d790efc0f1410bb8315965 --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/evidence/assist/typescript-assist-list-page/customer_order.md @@ -0,0 +1,90 @@ + + +# TypeScript Assist — List page `Customer Order` + +Use the exact generated entry point and APIs below. The result is a typed +page result whose `data` is a `SmartList` with exact filtered `totalCount`. The fixed 10,000-row +runtime ceiling cannot be overridden by generated client code. + +```typescript +import { Q } from './Q'; +import { CustomerOrder } from './models/CustomerOrder'; +import { TeaQLPage, UserContext } from '../teaql-ts'; + +export async function listActiveCustomerOrderPage( + context: UserContext, + offset: number, + limit: number, +): Promise> { + return Q.customerOrdersWithMinimalFields() + .selectOrderNumber() + .selectDescription() + .selectPlatformWith(Q.platformsWithMinimalFields()) + .selectOrderItemListWith(Q.orderItemsWithMinimalFields()) + .selectPaymentListWith(Q.paymentsWithMinimalFields()) + .selectShipmentListWith(Q.shipmentsWithMinimalFields()) + .orderByIdAscending() + .comment('what: list the active Customer Order page') + .purpose('why: serve the authorized Customer Order directory') + .executeForPage(context, offset, limit); +} +``` + +Compile and execute this source unchanged. Keep stable unique ID ordering. +Rows and total count must share the exact generated filters; count excludes +projection, relations, ordering, offset, and limit. Reject negative offsets, +limits outside `1...10000`, unknown filters/sorts, raw UI query JSON, missing +intent, and every generated-client attempt to call `hardLimit`. + +For bounded streaming, use the same generated request and Context. Streaming +does not compute an exact total count and does not imply an authorization bypass: + +```typescript +for await (const entity of Q.customerOrders() + .orderByIdAscending() + .limit(20) + .comment('what: stream a bounded Customer Order selection') + .purpose('why: process the authorized selection') + .executeForStream(context, 10)) { + // Use loaded E expressions here. Each returned root owns its mutation graph. +} +``` + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `list-page`. + +- Validate offset, page size, filters, deep paths, IN-list size, and sort against + explicit allow-lists. Reject invalid input instead of widening the query. +- Use a stable unique ordering and retain the runtime hard limit. Continuous-page + optimization is opt-in, browsing-only, local runtime policy and cannot cross TFP. +- Run count only when explicitly requested; otherwise use the returned list length.