philipgreat commited on
Commit
f3f2565
·
verified ·
1 Parent(s): f8491b7

docs: explain model-driven development process

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +13 -3
  2. assets/dynamic-search-BwvXmN4R.js +0 -0
  3. assets/entity-creation-Bqaw1C4U.js +1 -0
  4. assets/main-Csdici-L.js +104 -0
  5. assets/orders-DBfzfR_e.js +0 -0
  6. assets/sqlite.worker-BcUEWFpc.js +0 -0
  7. assets/style-F0ZYuCV2.css +1 -0
  8. assets/workItems-DS6iz1SR.js +1 -0
  9. dist/assets/dynamic-search-BwvXmN4R.js +0 -0
  10. dist/assets/entity-creation-Bqaw1C4U.js +1 -0
  11. dist/assets/main-Csdici-L.js +104 -0
  12. dist/assets/orders-DBfzfR_e.js +0 -0
  13. dist/assets/sqlite.worker-BcUEWFpc.js +0 -0
  14. dist/assets/style-F0ZYuCV2.css +1 -0
  15. dist/assets/workItems-DS6iz1SR.js +1 -0
  16. dist/index.html +60 -3
  17. dist/orders.html +4 -4
  18. dist/work-items.html +3 -3
  19. index.html +60 -3
  20. orders.html +4 -4
  21. source/provenance.json +6 -6
  22. source/teaql-ts/.github/release-signing-key.asc +52 -0
  23. source/teaql-ts/.github/workflows/example-gate.yml +3 -2
  24. source/teaql-ts/.github/workflows/release.yml +49 -14
  25. source/teaql-ts/README.md +8 -0
  26. source/teaql-ts/examples/browser-sqlite/README.md +9 -0
  27. source/teaql-ts/examples/browser-sqlite/generated-order-hashes.json +15 -15
  28. source/teaql-ts/examples/browser-sqlite/index.html +57 -0
  29. source/teaql-ts/examples/browser-sqlite/orders-lib/current-generator-fixture.json +36 -0
  30. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts +5 -5
  31. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/E.ts +258 -241
  32. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts +187 -45
  33. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts +191 -47
  34. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts +150 -30
  35. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts +193 -45
  36. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts +234 -62
  37. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts +108 -98
  38. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts +67 -57
  39. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts +64 -56
  40. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts +95 -85
  41. source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts +69 -57
  42. source/teaql-ts/examples/browser-sqlite/orders-lib/src/runtime-module.ts +1 -0
  43. source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-schemas.ts +3 -3
  44. source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-ts.ts +279 -69
  45. source/teaql-ts/examples/browser-sqlite/package-lock.json +3 -3
  46. source/teaql-ts/examples/browser-sqlite/scripts/orders-smoke.mjs +12 -4
  47. source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs +30 -0
  48. source/teaql-ts/examples/browser-sqlite/src/main.ts +27 -3
  49. source/teaql-ts/examples/browser-sqlite/src/orders.ts +6 -6
  50. source/teaql-ts/examples/browser-sqlite/src/style.css +90 -0
README.md CHANGED
@@ -27,6 +27,14 @@ TypeScript, Java, Rust, Go, Python, .NET and Swift. The language strip on the
27
  page links to each runtime source and marks TypeScript as the runtime currently
28
  executing in the browser.
29
 
 
 
 
 
 
 
 
 
30
  The final section preserves an unmodified OpenObserve dashboard capture of the
31
  Order-query business TraceChain. It shows the page purpose and nested request
32
  comments connected to the eight SQL executions captured by the observability
@@ -56,7 +64,7 @@ cross-origin isolation.
56
 
57
  The exact runtime, tests, model, generated Order library and browser application
58
  source are retained under [`source/teaql-ts`](./source/teaql-ts). They correspond to
59
- TeaQL TypeScript commit `1e1f50e7a54f2f47753a24cdd988e53fbde78180` on `main`.
60
 
61
  ```bash
62
  cd source/teaql-ts
@@ -71,8 +79,10 @@ npm run smoke
71
  npm run smoke:orders
72
  ```
73
 
74
- The validated runtime result was 57 passing suites and 608 passing tests, with six
75
- tests skipped by the repository configuration. Both real-browser smoke suites pass.
 
 
76
 
77
  Learn more at [teaql.io](https://teaql.io/) and inspect the upstream source at
78
  [github.com/teaql/teaql-ts](https://github.com/teaql/teaql-ts).
 
27
  page links to each runtime source and marks TypeScript as the runtime currently
28
  executing in the browser.
29
 
30
+ The new development-process section links directly to the canonical
31
+ [`order-model.xml`](https://github.com/teaql/teaql-ts/blob/main/examples/browser-sqlite/order-model.xml)
32
+ and the model-aware Assist files. It shows the actual path from domain model to
33
+ generated typed APIs, one bounded Q request, runtime execution, TraceChain and
34
+ the SQL SQLite/WASM executed. It also explains how progressive entity, action
35
+ and field Assist reduces repeated context use without claiming an unmeasured
36
+ percentage.
37
+
38
  The final section preserves an unmodified OpenObserve dashboard capture of the
39
  Order-query business TraceChain. It shows the page purpose and nested request
40
  comments connected to the eight SQL executions captured by the observability
 
64
 
65
  The exact runtime, tests, model, generated Order library and browser application
66
  source are retained under [`source/teaql-ts`](./source/teaql-ts). They correspond to
67
+ TeaQL TypeScript commit `b7c0f71f717d368c222da7cc8484db32bf281f11` on `main`.
68
 
69
  ```bash
70
  cd source/teaql-ts
 
79
  npm run smoke:orders
80
  ```
81
 
82
+ For this release, the TypeScript runtime build and the browser application build
83
+ passed. Both real-browser smoke suites also pass, including the generated-library
84
+ hash gate. Earlier aggregate test counts were removed because they described an
85
+ older source snapshot.
86
 
87
  Learn more at [teaql.io](https://teaql.io/) and inspect the upstream source at
88
  [github.com/teaql/teaql-ts](https://github.com/teaql/teaql-ts).
assets/dynamic-search-BwvXmN4R.js ADDED
The diff for this file is too large to render. See raw diff
 
assets/entity-creation-Bqaw1C4U.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{U as l,k as f,L as p}from"./dynamic-search-BwvXmN4R.js";const d=new WeakMap,u=new WeakSet,i=new WeakMap,y=(o,t)=>JSON.stringify([o,t]);class a extends Error{constructor(){super("ENTITY_CREATION_CONTEXT_REQUIRED: create through the Context-bound Q factory or load a persisted version before mutation"),this.code="ENTITY_CREATION_CONTEXT_REQUIRED",this.name="EntityCreationError"}}class T{static async create(t,r,s){if(!(t instanceof l))throw new a;const n=await t.generateInternalId(r),e=s(n);return d.set(e,Object.freeze({entity:r,id:n})),e}static bootstrap(t,r,s,n){if(!(t instanceof l))throw new a;const e=f(s);if(!i.get(t)?.has(y(r,e)))throw new a;const c=n(e);return d.set(c,Object.freeze({entity:r,id:e})),c}static hydrated(t){return u.add(t),t}static requireMutation(t,r,s,n,e,c){if(!c)return;let w;try{w=f(s)}catch{throw new a}if(f(r.id)!==w)throw new a;const h=p.forEntity(t);if(n==="Create"){const E=d.get(t);if(!E||E.entity!==r.entity||E.id!==w||h?.origin!=="creationBaseline"||!e.isNew(r))throw new a}else if(!u.has(t)&&!d.has(t)||h?.origin!=="hydrated"||h.persistedVersion===void 0)throw new a}}async function I(o,t,r){const s=i.get(o),n=new Set;for(const e of[t.defaultDomainRoot,...t.constants??[]])e&&n.add(y(e.entity,f(e.id)));i.set(o,n);try{await r()}finally{s?i.set(o,s):i.delete(o)}}export{T as EntityCreation,a as EntityCreationError,I as runGeneratedBootstrap};
assets/main-Csdici-L.js ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import{S as x,m as De,a as qe,e as xe,O as R,B as Qe,b as Be,R as Re,U as $e,D as ke,c as Fe,M as ze}from"./dynamic-search-BwvXmN4R.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),h=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),We=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}}],V={Platform:{table:"platform_data",columns:{id:C("id"),name:h("name"),code:h("code"),region:h("region"),currency:h("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:h("name"),email:h("email"),city:h("city"),tier:h("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:h("order_number"),orderDate:We("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:h("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:h("name"),code:h("code"),color:h("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:h("product_name"),sku:h("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:h("provider"),status:h("status"),amount:I("amount"),currency:h("currency"),transactionId:h("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:h("carrier"),status:h("status"),trackingNumber:h("tracking_number"),shipToCity:h("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:200,lineAmount:400}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:80,lineAmount:80}},{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:168,lineAmount:168}},{entity:"OrderItem",id:"2012",payload:{orderId:"1008",productName:"Keyboard Protective Case",sku:"KB-CASE-68",quantity:1,unitPrice:30,lineAmount:30}},{entity:"OrderItem",id:"2013",payload:{orderId:"1008",productName:"Foldable Travel Stand",sku:"KB-STAND-FOLD",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2014",payload:{orderId:"1008",productName:"Braided USB-C Cable",sku:"CABLE-USBC",quantity:1,unitPrice:20,lineAmount:20}},{entity:"OrderItem",id:"2015",payload:{orderId:"1008",productName:"Accent Keycap Set",sku:"KEYCAP-ACCENT",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2016",payload:{orderId:"1006",productName:"Balanced Audio Cable",sku:"AUDIO-XLR",quantity:1,unitPrice:40,lineAmount:40}},{entity:"OrderItem",id:"2017",payload:{orderId:"1006",productName:"Speaker Isolation Pads",sku:"SPK-PADS",quantity:1,unitPrice:60,lineAmount:60}},{entity:"OrderItem",id:"2018",payload:{orderId:"1006",productName:"USB DAC Adapter",sku:"AUDIO-DAC-USB",quantity:1,unitPrice:60,lineAmount:60}},{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}}],N=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(`
2
+ `,"\\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(${N(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${N(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(`
3
+ `)}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(m=>!(String(m.function).toLowerCase()==="count"&&m.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,m=>e.prepareQuery(m),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"?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 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 Ge 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 Ye 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(${N(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${N(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}=De(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"?R.asc(s):R.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(${N(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(${N(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(${N(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 Ge}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ye}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const F=document.querySelector("#status"),$=document.querySelector("#persist"),G=document.querySelector("#reset"),k=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),X=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"),B=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),ee=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=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"},developmentProcess:{en:"00 / DEVELOPMENT PROCESS",zh:"00 / 开发过程"},developmentProcessTitle:{en:"From one domain model to executable evidence.",zh:"从一份领域模型,到可以执行和审查的证据。"},developmentProcessIntro:{en:"TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.",zh:"TeaQL 让业务模型保持精简、可读,从模型生成确定性的领域 API,并把请求意图一直带到 Runtime 实际执行的 SQL。"},modelSource:{en:"MODEL SOURCE",zh:"模型源文件"},viewOrderModel:{en:"View order-model.xml",zh:"查看 order-model.xml"},scopedGuidance:{en:"SCOPED GUIDANCE",zh:"按需指导"},viewModelAssist:{en:"View model-aware Assist",zh:"查看模型感知 Assist"},processModelTitle:{en:"Model the domain",zh:"建立领域模型"},processModelBody:{en:"Define entities, fields, relationships, constant objects, and constraints in one model file.",zh:"在一个模型文件中定义对象、字段、关系、常数对象��约束。"},processGenerateTitle:{en:"Generate the working surface",zh:"生成领域开发接口"},processGenerateBody:{en:"Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.",zh:"从模型生成强类型 Q 与 E API、Schema、可审计变更和字段级 Assist。"},processQueryTitle:{en:"Build one bounded Q request",zh:"构建一个有界的 Q 请求"},processQueryBody:{en:"Application code selects only what the page needs and attaches a readable comment and purpose.",zh:"应用代码只选择页面需要的内容,并附上可读的 comment 和 purpose。"},processEvidenceTitle:{en:"Run and retain evidence",zh:"运行并保留证据"},processEvidenceBody:{en:"The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.",zh:"Runtime 执行策略和 SQLite/WASM,并保留从 purpose、嵌套 comment 到耗时和实际 SQL 的 TraceChain。"},contextEfficiency:{en:"CONTEXT EFFICIENCY",zh:"上下文效率"},contextEfficiencyTitle:{en:"Spend context on the business change.",zh:"把上下文窗口留给真正的业务变更。"},contextEfficiencyBody:{en:"Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.",zh:"Agent 不需要加载 Runtime 内部实现和所有生成文件,而是从精简模型出发,只打开当前对象、动作或字段所需的 Assist。强类型领域操作把数据库和 Provider 细节压缩成更小的工作界面,减少重复占用上下文,同时保持行为确定、可审查。"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},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,z=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",T,fe=0,te;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";$.checked=Ae==="opfs";async function Y(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 re(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)
4
+ .limit(pageSize)
5
+ .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:re(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()
6
+ .selectPlatformWith(Q.platforms().selectName())
7
+ .selectCustomerWith(Q.customers().selectName().selectCity().selectTier())
8
+ .selectStatusWith(Q.orderStatuses().selectName().selectColor())
9
+ .orderByOrderDateDescending()
10
+ .orderByIdDescending()
11
+ .limit(8)
12
+ .comment('what: list recent commerce orders')
13
+ .purpose('why: provide the default order overview')
14
+ .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()
15
+ .withOrderNumberIs('TQL-2026-1003')
16
+ .selectPlatformWith(Q.platforms())
17
+ .selectCustomerWith(Q.customers())
18
+ .selectStatusWith(Q.orderStatuses().selectName().selectColor())
19
+ .selectItemListWith(Q.orderItems().orderByIdAscending())
20
+ .selectPaymentListWith(Q.payments().orderByIdAscending())
21
+ .selectShipmentListWith(Q.shipments().orderByIdAscending())
22
+ .limit(1)
23
+ .comment('what: load one complete order graph')
24
+ .purpose('why: inspect items, payment and fulfillment together')
25
+ .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()
26
+ .selectPlatformWith(Q.platforms().selectName())
27
+ .countOrderListAs('orderCount')
28
+ .orderByNameAscending()
29
+ .comment('what: list customers with related order counts')
30
+ .purpose('why: compare customer activity at a glance')
31
+ .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()
32
+ .groupByCurrency().groupByStatus()
33
+ .countAs('orderCount')
34
+ .sumTotalAmountAs('grossAmount')
35
+ .averageTotalAmountAs('averageOrderValue')
36
+ .comment('what: aggregate orders by currency and status')
37
+ .purpose('why: show the current order funnel')
38
+ .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()
39
+ .groupByProductName()
40
+ .sumQuantityAs('units')
41
+ .sumLineAmountAs('revenue')
42
+ .comment('what: aggregate sold units and line revenue')
43
+ .purpose('why: identify the strongest products in the demo data')
44
+ .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()
45
+ .groupByCurrency().groupByProvider().groupByStatus()
46
+ .countAs('paymentCount').sumAmountAs('paymentAmount')
47
+ .orderByCurrencyAscending().orderByProviderAscending()
48
+ .comment('what: reconcile payment totals by provider')
49
+ .purpose('why: compare captured, pending and refunded money')
50
+ .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()
51
+ .withStatusIsPendingPayment()
52
+ .selectStatusWith(Q.orderStatuses().selectName().selectColor())
53
+ .selectCustomerWith(Q.customers().selectName())
54
+ .selectPaymentListWith(Q.payments())
55
+ .comment('what: find orders awaiting payment')
56
+ .purpose('why: support payment follow-up')
57
+ .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()
58
+ .withPlatformIdIs('1')
59
+ .withTotalAmountGreaterThanOrEqualTo(500)
60
+ .selectCustomerWith(Q.customers().selectName().selectCity())
61
+ .orderByTotalAmountDescending()
62
+ .comment('what: find high-value domestic orders')
63
+ .purpose('why: prioritize valuable fulfillment work')
64
+ .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()
65
+ .withStatusIn('READY', 'IN_TRANSIT')
66
+ .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency())
67
+ .orderByStatusAscending().orderByIdAscending()
68
+ .comment('what: find shipments that are not delivered')
69
+ .purpose('why: monitor active fulfillment')
70
+ .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 = {
71
+ "filter": {
72
+ "currency": "CNY",
73
+ "totalAmount": { "$gte": "250" },
74
+ "status": { "$in": ["PAID", "SHIPPED"] }
75
+ },
76
+ "orderBy": [{ "field": "totalAmount", "direction": "desc" }]
77
+ };
78
+ const data = await Q.customerOrders()
79
+ .filterByJson(input)
80
+ .limit(20)
81
+ .comment('what: execute a validated browser search')
82
+ .purpose('why: demonstrate safe dynamic order discovery')
83
+ .executeForList(ctx);`,run:t=>Y(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 = {
84
+ "filter": { "orderDate": { "$gte": "2026-09-15" } },
85
+ "orderBy": [{ "field": "orderDate", "direction": "asc" }]
86
+ };
87
+ const data = await Q.customerOrders()
88
+ .filterByJson(input)
89
+ .limit(20)
90
+ .comment('what: execute a validated browser search')
91
+ .purpose('why: demonstrate safe dynamic order discovery')
92
+ .executeForList(ctx);`,run:t=>Y(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = {
93
+ "filter": {
94
+ "status": "DELIVERED",
95
+ "internalNote": { "$contains": "not queryable" }
96
+ }
97
+ };
98
+ const request = Q.customerOrders().filterByJson(input);
99
+ const data = await request
100
+ .limit(20)
101
+ .comment('what: execute a validated browser search')
102
+ .purpose('why: demonstrate safe dynamic order discovery')
103
+ .executeForList(ctx);
104
+ const warnings = request.warnings();`,run:t=>Y(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-BcUEWFpc.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...V},{storage:t,databaseName:"teaql-order-playground-v4.sqlite3"}),n=new Be().enableSelect();r.install(new Re(V,{},{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-v2"}),o=new $e().insertResource("dataService",r).withMutationPolicyRegistry(new ke(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Fe(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 ze("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:Object.fromEntries(Object.entries(o.payload).map(([a,i])=>{const c=V[o.entity]?.columns[a];if(!c)throw new Error(`Unknown fixture field ${o.entity}.${a}`);return[c.modelName??a,i]}))}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){k.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(),z=a.id,history.replaceState(null,"",`#${a.id}`),Z(),E&&v(a,E).catch(L)}),o.append(i)}e.append(r,o),k.append(e)}Z()}function Z(){k.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===z;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function v(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.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"),w.classList.toggle("dashboard-result",t.view==="dashboard"),ee.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),B.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",X.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),T={data:s,query:t,active:e},b=t.view==="dashboard"||J(s)?"table":"tree",W();const o=Math.max(1,Math.round(performance.now()-r));fe=o,te=n;const a=e.evidence.snapshot();be(a,n),Ne(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=te){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(l=>l.kind==="relation"||l.kind==="request"||l.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=`${T?.query.id??"query"} · #${n+1} · ${o?.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 p=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${p}`,s.append(a,i,c,m),ue.append(s)})}function J(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function W(){if(!T)return;const{data:t,query:e,active:r}=T,n=e.view==="dashboard"||J(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),H.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),H.setAttribute("aria-pressed",String(b==="tree")),ee.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){B.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&J(t)){B.textContent=d==="en"?"Result table":"结果表格",ut(t);return}B.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),w.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 m of r){const p=document.createElement("td");p.textContent=lt(i[m]),c.append(p)}a.append(c)}n.append(s,a),e.append(n),w.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=re(e);if(r)return we(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 m=document.createElement("input");m.type="search",m.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const p=document.createElement("button");p.type="submit",p.className="order-search-submit",p.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),p.title=d==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),p.append(l),c.append(m,p),c.addEventListener("submit",y=>{y.preventDefault(),A.search=m.value.trim(),A.page=0,v(r,e).catch(L)}),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,v(r,e).catch(L)}));for(const y of t.statusFacets)S.append(me(y.name,y.orderCount,y.code.toLowerCase(),y.color,t.search.toUpperCase()===y.code,()=>{A.search=y.code,A.page=0,v(r,e).catch(L)},`${d==="en"?"Total":"总额"} ${pt(y.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const Te=d==="en"?["Order number","Order date","Status","Line Items"]:["订单号","订单日期","状态","订单明细"];for(const y of Te){const q=document.createElement("span");q.textContent=y,M.append(q)}if(g.append(M),!t.orders.length){const y=document.createElement("div");y.className="order-empty",y.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(y)}for(const y of t.orders)g.append(yt(y));const _=document.createElement("div");_.className="order-center-footer";const se=document.createElement("p"),oe=t.filteredOrders?t.page*t.pageSize+1:0,ae=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);se.textContent=d==="en"?`Showing ${oe}–${ae} of ${t.filteredOrders} orders`:`显示 ${oe}–${ae},共 ${t.filteredOrders} 条订单`;const D=document.createElement("div");D.className="pagination";const ie=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));D.append(j("‹",t.page-1,t.page===0,e,r));for(let y=0;y<ie;y+=1){const q=j(String(y+1),y,!1,e,r);q.classList.toggle("active",y===t.page),D.append(q)}D.append(j("›",t.page+1,t.page>=ie-1,e,r)),_.append(se,D),n.append(s,S,g,_),w.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 m=document.createElement("strong");if(m.textContent=String(e),i.append(c,m),a){const p=document.createElement("small");p.textContent=a,i.append(p)}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(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=re(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=we(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 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 p=Number(t.itemCount??n.length);if(p>n.length){const l=document.createElement("small");l.className="line-item-count",l.textContent=d==="en"?`${p} items`:`共 ${p} 项`,l.title=d==="en"?`Showing ${n.length} of ${p} line items`:`显示 ${n.length} 项,共 ${p} 项订单明细`,m.append(l)}return e.append(m),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,v(s,n).catch(L)}),o}function we(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){w.replaceChildren(Le(t,"result",0))}function Le(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"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const p=document.createElement("span");p.className="tree-preview",p.textContent=ht(t,a.length),c.append(m,p),i.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of a)l.append(Le(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(l),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 Ne(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"?"匹配订单":"结果"}`;X.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;F.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){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":"运行时设置"),k.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(),T){const{data:e,query:r,active:n}=T;ye.textContent=O(r.title),he.textContent=O(r.description),W(),be(n.evidence.snapshot(),te),Ne(e,r,fe),Oe($.checked?"opfs":"memory")}else F.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function ne(){return le.find(t=>t.id===z)??le[0]}async function Pe(t){F.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 v(ne(),r),Oe(t)}$.addEventListener("change",()=>{const t=$.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Pe(t).catch(L)});G.addEventListener("click",async()=>{if(E){G.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await v(ne(),E)}catch(t){L(t)}finally{G.disabled=!1}}});ee.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",W())});H.addEventListener("click",()=>{b="tree",W()});tt.addEventListener("click",()=>{w.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),ve()})});function L(t){const e=t instanceof Error?t:new Error(String(t));F.textContent=`${e.name}: ${e.message}`,X.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}ve();z=ne().id;Z();Pe(Ae).catch(L);
assets/orders-DBfzfR_e.js ADDED
The diff for this file is too large to render. See raw diff
 
assets/sqlite.worker-BcUEWFpc.js ADDED
The diff for this file is too large to render. See raw diff
 
assets/style-F0ZYuCV2.css ADDED
@@ -0,0 +1 @@
 
 
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}.development-process{margin:54px 0 28px;padding:42px;border:1px solid var(--line);border-radius:24px;background:var(--paper);box-shadow:0 18px 48px #213c280d}.development-process-heading{display:grid;grid-template-columns:minmax(280px,.9fr) minmax(0,1.1fr);align-items:end;gap:48px}.development-process-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,3.5vw,48px);font-weight:500;line-height:1.08;letter-spacing:-.04em}.development-process-intro>p{margin:0;color:var(--muted);font-size:16px;line-height:1.7}.development-process-links{margin-top:22px;display:flex;flex-wrap:wrap;gap:10px}.source-link{min-width:210px;padding:12px 15px;display:grid;gap:3px;border:1px solid #cad3c9;border-radius:10px;color:var(--ink);background:#f8faf5;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.source-link:hover,.source-link:focus-visible{border-color:#819586;background:#fff;outline:none;transform:translateY(-1px)}.source-link-primary{color:#fff;border-color:var(--green);background:var(--green)}.source-link-primary:hover,.source-link-primary:focus-visible{border-color:var(--green-deep);background:var(--green-deep)}.source-link span{color:#77847a;font-size:10px;font-weight:850;letter-spacing:.13em}.source-link-primary span{color:#c8dccd}.source-link strong{font-size:14px;line-height:1.35}.development-process-flow{margin:38px 0 0;padding:0;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));border:1px solid #d7ddd3;border-radius:16px;background:#f8faf5;list-style:none;overflow:hidden}.development-process-flow li{min-width:0;padding:22px;border-left:1px solid #d7ddd3}.development-process-flow li:first-child{border-left:0}.development-step{display:block;margin-bottom:20px;color:var(--orange);font:800 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace}.development-process-flow strong{display:block;min-height:48px;font-size:16px;line-height:1.45}.development-process-flow p{min-height:92px;margin:10px 0 18px;color:var(--muted);font-size:14px;line-height:1.6}.development-process-flow code{color:var(--green);font:650 12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.context-efficiency{margin-top:18px;padding:24px;display:grid;grid-template-columns:minmax(230px,.72fr) minmax(0,1.28fr);align-items:center;gap:34px;border-radius:14px;color:#edf7ef;background:var(--green-deep)}.context-efficiency .section-index{margin-bottom:8px;color:var(--lime)}.context-efficiency h3{margin:0;font:500 24px/1.2 Georgia,"Noto Serif SC",serif;letter-spacing:-.025em}.context-efficiency>p{margin:0;color:#c7d8cc;font-size:15px;line-height:1.7}.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}.observability-proof{padding:88px 0 52px}.observability-proof-heading{margin-bottom:26px;display:grid;grid-template-columns:minmax(260px,.72fr) minmax(0,1.28fr);align-items:end;gap:34px}.observability-proof-heading h2{margin:8px 0 0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,4vw,48px);font-weight:500;line-height:1.05;letter-spacing:-.04em}.observability-proof-heading>p{margin:0;color:var(--muted);font-size:15px;line-height:1.7}.observability-proof-figure{margin:0}.observability-proof-figure img{width:100%;height:auto;display:block;border:1px solid #d7ddd5;border-radius:18px;background:#f4f5fb;box-shadow:0 22px 54px #1c2d221a}.observability-proof-figure figcaption{margin-top:12px;color:var(--muted);font-size:11px}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))}.development-process-heading{grid-template-columns:1fr;align-items:start;gap:24px}.development-process-flow{grid-template-columns:repeat(2,minmax(0,1fr))}.development-process-flow li:nth-child(3){border-left:0;border-top:1px solid #d7ddd3}.development-process-flow li:nth-child(4){border-top:1px solid #d7ddd3}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}.observability-proof-heading{grid-template-columns:1fr;align-items:start;gap:14px}}@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}.development-process{margin-top:38px;padding:26px 18px}.development-process-intro>p{font-size:15px}.development-process-links{align-items:stretch;flex-direction:column}.source-link{min-width:0;width:100%}.development-process-flow{grid-template-columns:1fr}.development-process-flow li{border-top:1px solid #d7ddd3;border-left:0}.development-process-flow li:first-child{border-top:0}.development-process-flow li:nth-child(3),.development-process-flow li:nth-child(4){border-left:0}.development-process-flow strong,.development-process-flow p{min-height:0}.context-efficiency{grid-template-columns:1fr;gap:16px;padding:20px}.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}.observability-proof{padding:64px 0 34px}.observability-proof-figure img{border-radius:12px}}
assets/workItems-DS6iz1SR.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{S as it,f as j,E as k,g as Q,L as l,M as I,n as U,C as w,d as f,a as b,j as z,e as O,Q as J,U as K,R as rt,B as st,D as nt,c as ot}from"./dynamic-search-BwvXmN4R.js";import{EntityCreationError as H,EntityCreation as v}from"./entity-creation-Bqaw1C4U.js";class N extends it{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",n=!0,s){return super.relationQuery(t,e,i,r,n,s)}}const R=Symbol("managed entity construction");class m{static teaqlTemporaryId=0;static teaqlMutationFields=new j("WorkItem",["id","title","description","platform","version"],{id:"immutable_field",version:"immutable_field"});id;title;description;platform;version;constructor(t,e,i=!1){if(e!==R)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];Object.assign(this,n),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof p?t.platform:p.fromRecord(t.platform),this.markLoaded("platform"))}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=v.hydrated(new m(t,R));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){return Object.fromEntries(Object.entries(this))}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 m.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"WorkItem",e,i=>new m({id:i},R,!0))}static teaqlCreate(t){return v.create(t,"WorkItem",e=>new m({id:e},R,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());return v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),i}teaqlValidateLoadedIdentities(t=new Set){t.has(this)||(t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version))}teaqlDiscardRestoredGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)))}teaqlNormalizeGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()}})))}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),m.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}return i}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){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 w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y),y.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"WorkItem",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();return d.scopeFor(c),e.afterGraphRollback(()=>{for(const P of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,P)||delete this[P];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c),d.scopeFor(c),e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),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}}const T=Symbol("managed entity construction");class p{static teaqlTemporaryId=0;static teaqlMutationFields=new j("Platform",["id","name","version"],{id:"immutable_field",version:"immutable_field"});id;name;version;constructor(t,e,i=!1){if(e!==T)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--p.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:i?new b:b.empty(),writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];if(delete n.workItemList,Object.assign(this,n),Array.isArray(t.workItemList)){const s=t.workItemList;this._workItemList=new b(s.map(o=>o instanceof m?o:m.fromRecord(o)),{totalCount:s.totalCount,aggregations:s.aggregations,summary:s.summary,facets:s.facets,isLoaded:s.isLoaded??!0}),this.markLoaded("workItemList")}}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const i of this._workItemList)i.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const i=v.hydrated(new p(t,T));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("workItemList")&&(t.workItemList=this._workItemList),t}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 p.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"Platform",e,i=>new p({id:i},T,!0))}static teaqlCreate(t){return v.create(t,"Platform",e=>new p({id:e},T,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i);for(const r of this._workItemList)i=r.teaqlValidateMutationOrigins(t)||i;return i}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,i]of this._workItemList.entries())try{i.teaqlValidateLoadedIdentities(t)}catch(r){if(!(r instanceof w))throw r;const n=f.property("work_item_list").index(e);throw new w(r.violations.map(s=>({...s,location:s.location.prefixedBy(n)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));for(const i of this._workItemList)i.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},work_item_list:t.sourceMembers(this._workItemList)}));for(const i of this._workItemList){i.teaqlAttachRoot(this._root);const r=i.platform;(i._action!=="Update"||i._root.hasPending(i.teaqlEntityKey()))&&(this.id===void 0||!i.isLoaded("platform")||(typeof r=="object"&&r!==null?r.id:r)!==this.id)&&i.updatePlatform(this),i.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),p.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}let r=i;for(const[n,s]of this._workItemList.entries())try{r=s.teaqlAdmitGraph(t)||r}catch(o){if(!(o instanceof w))throw o;const y=f.property("work_item_list").index(n);throw new w(o.violations.map(d=>({...d,location:d.location.prefixedBy(y)})))}return r}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(u)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y);const d=y.scopeFor(this.teaqlEntityKey());for(const[u,a]of this._workItemList.entries()){a.teaqlAttachRoot(this._root);const q=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof q=="object"&&q!==null?q.id:q)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,i,d,n)}catch(c){if(!(c instanceof w))throw c;const $=f.property("work_item_list").index(u);throw new w(t.translateCheckResults(c.violations.map(P=>({...P,location:P.location.prefixedBy($)}))))}}}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"Platform",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const L=d.scopeFor(this.teaqlEntityKey());for(const[_,g]of this._workItemList.entries()){g.teaqlAttachRoot(this._root);const E=g.platform;(g._action!=="Update"||g._root.hasPending(g.teaqlEntityKey()))&&(this.id===void 0||!g.isLoaded("platform")||(typeof E=="object"&&E!==null?E.id:E)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,i,L,n)}catch(C){if(!(C instanceof w))throw C;const F=f.property("work_item_list").index(_);throw new w(t.translateCheckResults(C.violations.map(V=>({...V,location:V.location.prefixedBy(F)}))))}}return this}const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();d.scopeFor(c),e.afterGraphRollback(()=>{for(const L of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,L)||delete this[L];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c);const P=d.scopeFor(c);for(const[L,_]of this._workItemList.entries()){_.teaqlAttachRoot(this._root);const g=_.platform;(_._action!=="Update"||_._root.hasPending(_.teaqlEntityKey()))&&(this.id===void 0||!_.isLoaded("platform")||(typeof g=="object"&&g!==null?g.id:g)!==this.id)&&_.updatePlatform(this);try{await _.teaqlSaveWithinGraph(t,e,i,P,n)}catch(E){if(!(E instanceof w))throw E;const C=f.property("work_item_list").index(L);throw new w(t.translateCheckResults(E.violations.map(F=>({...F,location:F.location.prefixedBy(C)}))))}}return e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),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 Y=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 D{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Platform"}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=z(i,t,Y,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 at(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.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),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({entityName:"WorkItem",toQuery:()=>new N("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({entityName:"WorkItem",toQuery:()=>new N("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 N("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{entityName:"WorkItem",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",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",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,n=r?[]:i.map(o=>o instanceof p?o:p.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(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,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof p?a:p.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}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),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof p?o:p.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class at{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return p.teaqlCreate(t)}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 G{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"WorkItem"}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=z(i,t,Y,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 ht(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.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),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",t),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title",t),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),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,n=r?[]:i.map(o=>o instanceof m?o:m.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(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,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof m?a:m.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}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),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof m?o:m.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class ht{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return m.teaqlCreate(t)}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 A{static platforms(){return new D(!1)}static platformsWithMinimalFields(){return new D(!0)}static workItems(){return new G(!1)}static workItemsWithMinimalFields(){return new G(!0)}}const lt={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 ut(h){let t=(await A.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];t||(t=p.teaqlBootstrapNew(h,"1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(h)),h.withActiveRoot({entity:"Platform",id:t.id})}const dt=new rt(lt,{Platform:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:f.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:f.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:f.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:f.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:f.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:f.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:f.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:ut}),ct={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}}}},x=document.querySelector("#status"),pt=document.querySelector("#result"),B=document.querySelector("#persist"),W=document.querySelector("#reset");let S;const X=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=X==="opfs";async function mt(h){const t=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),e=await st.open(t,{...ct},{storage:h,databaseName:"teaql-browser-example.sqlite3"});e.install(dt);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new K().insertResource("dataService",e).withMutationPolicyRegistry(new nt(()=>({identity:i,review:(n,s)=>s.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ot(n=>({policy:n,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Z({context:h}){if(!(await A.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(h)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await(await A.workItems().comment("reserve one browser demo work item").purpose("seed deterministic data through managed creation").newEntity(h)).updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(h)}async function tt(h){const t=await A.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(h.context);pt.textContent=JSON.stringify(t,null,2),x.textContent=`${h.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function et(h){x.textContent=`Opening ${h.toUpperCase()} SQLite/WASM…`;const t=S;S=void 0,await t?.client.close();const e=await mt(h);S=e,await Z(e),await tt(e)}B.addEventListener("change",()=>{const h=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",h),et(h).catch(M)});W.addEventListener("click",async()=>{if(S){W.disabled=!0;try{await S.client.reset(S.context),await Z(S),await tt(S)}catch(h){M(h)}finally{W.disabled=!1}}});function M(h){const t=h instanceof Error?h:new Error(String(h));x.textContent=`${t.name}: ${t.message}`}et(X).catch(M);
dist/assets/dynamic-search-BwvXmN4R.js ADDED
The diff for this file is too large to render. See raw diff
 
dist/assets/entity-creation-Bqaw1C4U.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{U as l,k as f,L as p}from"./dynamic-search-BwvXmN4R.js";const d=new WeakMap,u=new WeakSet,i=new WeakMap,y=(o,t)=>JSON.stringify([o,t]);class a extends Error{constructor(){super("ENTITY_CREATION_CONTEXT_REQUIRED: create through the Context-bound Q factory or load a persisted version before mutation"),this.code="ENTITY_CREATION_CONTEXT_REQUIRED",this.name="EntityCreationError"}}class T{static async create(t,r,s){if(!(t instanceof l))throw new a;const n=await t.generateInternalId(r),e=s(n);return d.set(e,Object.freeze({entity:r,id:n})),e}static bootstrap(t,r,s,n){if(!(t instanceof l))throw new a;const e=f(s);if(!i.get(t)?.has(y(r,e)))throw new a;const c=n(e);return d.set(c,Object.freeze({entity:r,id:e})),c}static hydrated(t){return u.add(t),t}static requireMutation(t,r,s,n,e,c){if(!c)return;let w;try{w=f(s)}catch{throw new a}if(f(r.id)!==w)throw new a;const h=p.forEntity(t);if(n==="Create"){const E=d.get(t);if(!E||E.entity!==r.entity||E.id!==w||h?.origin!=="creationBaseline"||!e.isNew(r))throw new a}else if(!u.has(t)&&!d.has(t)||h?.origin!=="hydrated"||h.persistedVersion===void 0)throw new a}}async function I(o,t,r){const s=i.get(o),n=new Set;for(const e of[t.defaultDomainRoot,...t.constants??[]])e&&n.add(y(e.entity,f(e.id)));i.set(o,n);try{await r()}finally{s?i.set(o,s):i.delete(o)}}export{T as EntityCreation,a as EntityCreationError,I as runGeneratedBootstrap};
dist/assets/main-Csdici-L.js ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import{S as x,m as De,a as qe,e as xe,O as R,B as Qe,b as Be,R as Re,U as $e,D as ke,c as Fe,M as ze}from"./dynamic-search-BwvXmN4R.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),h=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),We=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}}],V={Platform:{table:"platform_data",columns:{id:C("id"),name:h("name"),code:h("code"),region:h("region"),currency:h("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:h("name"),email:h("email"),city:h("city"),tier:h("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:h("order_number"),orderDate:We("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:h("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:h("name"),code:h("code"),color:h("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:h("product_name"),sku:h("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:h("provider"),status:h("status"),amount:I("amount"),currency:h("currency"),transactionId:h("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:h("carrier"),status:h("status"),trackingNumber:h("tracking_number"),shipToCity:h("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:200,lineAmount:400}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:80,lineAmount:80}},{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:168,lineAmount:168}},{entity:"OrderItem",id:"2012",payload:{orderId:"1008",productName:"Keyboard Protective Case",sku:"KB-CASE-68",quantity:1,unitPrice:30,lineAmount:30}},{entity:"OrderItem",id:"2013",payload:{orderId:"1008",productName:"Foldable Travel Stand",sku:"KB-STAND-FOLD",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2014",payload:{orderId:"1008",productName:"Braided USB-C Cable",sku:"CABLE-USBC",quantity:1,unitPrice:20,lineAmount:20}},{entity:"OrderItem",id:"2015",payload:{orderId:"1008",productName:"Accent Keycap Set",sku:"KEYCAP-ACCENT",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2016",payload:{orderId:"1006",productName:"Balanced Audio Cable",sku:"AUDIO-XLR",quantity:1,unitPrice:40,lineAmount:40}},{entity:"OrderItem",id:"2017",payload:{orderId:"1006",productName:"Speaker Isolation Pads",sku:"SPK-PADS",quantity:1,unitPrice:60,lineAmount:60}},{entity:"OrderItem",id:"2018",payload:{orderId:"1006",productName:"USB DAC Adapter",sku:"AUDIO-DAC-USB",quantity:1,unitPrice:60,lineAmount:60}},{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}}],N=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(`
2
+ `,"\\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(${N(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${N(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(`
3
+ `)}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(m=>!(String(m.function).toLowerCase()==="count"&&m.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,m=>e.prepareQuery(m),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"?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 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 Ge 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 Ye 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(${N(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${N(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}=De(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"?R.asc(s):R.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(${N(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(${N(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(${N(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 Ge}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ye}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const F=document.querySelector("#status"),$=document.querySelector("#persist"),G=document.querySelector("#reset"),k=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),X=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"),B=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),ee=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=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"},developmentProcess:{en:"00 / DEVELOPMENT PROCESS",zh:"00 / 开发过程"},developmentProcessTitle:{en:"From one domain model to executable evidence.",zh:"从一份领域模型,到可以执行和审查的证据。"},developmentProcessIntro:{en:"TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.",zh:"TeaQL 让业务模型保持精简、可读,从模型生成确定性的领域 API,并把请求意图一直带到 Runtime 实际执行的 SQL。"},modelSource:{en:"MODEL SOURCE",zh:"模型源文件"},viewOrderModel:{en:"View order-model.xml",zh:"查看 order-model.xml"},scopedGuidance:{en:"SCOPED GUIDANCE",zh:"按需指导"},viewModelAssist:{en:"View model-aware Assist",zh:"查看模型感知 Assist"},processModelTitle:{en:"Model the domain",zh:"建立领域模型"},processModelBody:{en:"Define entities, fields, relationships, constant objects, and constraints in one model file.",zh:"在一个模型文件中定义对象、字段、关系、常数对象��约束。"},processGenerateTitle:{en:"Generate the working surface",zh:"生成领域开发接口"},processGenerateBody:{en:"Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.",zh:"从模型生成强类型 Q 与 E API、Schema、可审计变更和字段级 Assist。"},processQueryTitle:{en:"Build one bounded Q request",zh:"构建一个有界的 Q 请求"},processQueryBody:{en:"Application code selects only what the page needs and attaches a readable comment and purpose.",zh:"应用代码只选择页面需要的内容,并附上可读的 comment 和 purpose。"},processEvidenceTitle:{en:"Run and retain evidence",zh:"运行并保留证据"},processEvidenceBody:{en:"The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.",zh:"Runtime 执行策略和 SQLite/WASM,并保留从 purpose、嵌套 comment 到耗时和实际 SQL 的 TraceChain。"},contextEfficiency:{en:"CONTEXT EFFICIENCY",zh:"上下文效率"},contextEfficiencyTitle:{en:"Spend context on the business change.",zh:"把上下文窗口留给真正的业务变更。"},contextEfficiencyBody:{en:"Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.",zh:"Agent 不需要加载 Runtime 内部实现和所有生成文件,而是从精简模型出发,只打开当前对象、动作或字段所需的 Assist。强类型领域操作把数据库和 Provider 细节压缩成更小的工作界面,减少重复占用上下文,同时保持行为确定、可审查。"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},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,z=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",T,fe=0,te;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";$.checked=Ae==="opfs";async function Y(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 re(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)
4
+ .limit(pageSize)
5
+ .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:re(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()
6
+ .selectPlatformWith(Q.platforms().selectName())
7
+ .selectCustomerWith(Q.customers().selectName().selectCity().selectTier())
8
+ .selectStatusWith(Q.orderStatuses().selectName().selectColor())
9
+ .orderByOrderDateDescending()
10
+ .orderByIdDescending()
11
+ .limit(8)
12
+ .comment('what: list recent commerce orders')
13
+ .purpose('why: provide the default order overview')
14
+ .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()
15
+ .withOrderNumberIs('TQL-2026-1003')
16
+ .selectPlatformWith(Q.platforms())
17
+ .selectCustomerWith(Q.customers())
18
+ .selectStatusWith(Q.orderStatuses().selectName().selectColor())
19
+ .selectItemListWith(Q.orderItems().orderByIdAscending())
20
+ .selectPaymentListWith(Q.payments().orderByIdAscending())
21
+ .selectShipmentListWith(Q.shipments().orderByIdAscending())
22
+ .limit(1)
23
+ .comment('what: load one complete order graph')
24
+ .purpose('why: inspect items, payment and fulfillment together')
25
+ .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()
26
+ .selectPlatformWith(Q.platforms().selectName())
27
+ .countOrderListAs('orderCount')
28
+ .orderByNameAscending()
29
+ .comment('what: list customers with related order counts')
30
+ .purpose('why: compare customer activity at a glance')
31
+ .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()
32
+ .groupByCurrency().groupByStatus()
33
+ .countAs('orderCount')
34
+ .sumTotalAmountAs('grossAmount')
35
+ .averageTotalAmountAs('averageOrderValue')
36
+ .comment('what: aggregate orders by currency and status')
37
+ .purpose('why: show the current order funnel')
38
+ .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()
39
+ .groupByProductName()
40
+ .sumQuantityAs('units')
41
+ .sumLineAmountAs('revenue')
42
+ .comment('what: aggregate sold units and line revenue')
43
+ .purpose('why: identify the strongest products in the demo data')
44
+ .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()
45
+ .groupByCurrency().groupByProvider().groupByStatus()
46
+ .countAs('paymentCount').sumAmountAs('paymentAmount')
47
+ .orderByCurrencyAscending().orderByProviderAscending()
48
+ .comment('what: reconcile payment totals by provider')
49
+ .purpose('why: compare captured, pending and refunded money')
50
+ .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()
51
+ .withStatusIsPendingPayment()
52
+ .selectStatusWith(Q.orderStatuses().selectName().selectColor())
53
+ .selectCustomerWith(Q.customers().selectName())
54
+ .selectPaymentListWith(Q.payments())
55
+ .comment('what: find orders awaiting payment')
56
+ .purpose('why: support payment follow-up')
57
+ .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()
58
+ .withPlatformIdIs('1')
59
+ .withTotalAmountGreaterThanOrEqualTo(500)
60
+ .selectCustomerWith(Q.customers().selectName().selectCity())
61
+ .orderByTotalAmountDescending()
62
+ .comment('what: find high-value domestic orders')
63
+ .purpose('why: prioritize valuable fulfillment work')
64
+ .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()
65
+ .withStatusIn('READY', 'IN_TRANSIT')
66
+ .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency())
67
+ .orderByStatusAscending().orderByIdAscending()
68
+ .comment('what: find shipments that are not delivered')
69
+ .purpose('why: monitor active fulfillment')
70
+ .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 = {
71
+ "filter": {
72
+ "currency": "CNY",
73
+ "totalAmount": { "$gte": "250" },
74
+ "status": { "$in": ["PAID", "SHIPPED"] }
75
+ },
76
+ "orderBy": [{ "field": "totalAmount", "direction": "desc" }]
77
+ };
78
+ const data = await Q.customerOrders()
79
+ .filterByJson(input)
80
+ .limit(20)
81
+ .comment('what: execute a validated browser search')
82
+ .purpose('why: demonstrate safe dynamic order discovery')
83
+ .executeForList(ctx);`,run:t=>Y(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 = {
84
+ "filter": { "orderDate": { "$gte": "2026-09-15" } },
85
+ "orderBy": [{ "field": "orderDate", "direction": "asc" }]
86
+ };
87
+ const data = await Q.customerOrders()
88
+ .filterByJson(input)
89
+ .limit(20)
90
+ .comment('what: execute a validated browser search')
91
+ .purpose('why: demonstrate safe dynamic order discovery')
92
+ .executeForList(ctx);`,run:t=>Y(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = {
93
+ "filter": {
94
+ "status": "DELIVERED",
95
+ "internalNote": { "$contains": "not queryable" }
96
+ }
97
+ };
98
+ const request = Q.customerOrders().filterByJson(input);
99
+ const data = await request
100
+ .limit(20)
101
+ .comment('what: execute a validated browser search')
102
+ .purpose('why: demonstrate safe dynamic order discovery')
103
+ .executeForList(ctx);
104
+ const warnings = request.warnings();`,run:t=>Y(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-BcUEWFpc.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...V},{storage:t,databaseName:"teaql-order-playground-v4.sqlite3"}),n=new Be().enableSelect();r.install(new Re(V,{},{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-v2"}),o=new $e().insertResource("dataService",r).withMutationPolicyRegistry(new ke(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Fe(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 ze("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:Object.fromEntries(Object.entries(o.payload).map(([a,i])=>{const c=V[o.entity]?.columns[a];if(!c)throw new Error(`Unknown fixture field ${o.entity}.${a}`);return[c.modelName??a,i]}))}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){k.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(),z=a.id,history.replaceState(null,"",`#${a.id}`),Z(),E&&v(a,E).catch(L)}),o.append(i)}e.append(r,o),k.append(e)}Z()}function Z(){k.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===z;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function v(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.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"),w.classList.toggle("dashboard-result",t.view==="dashboard"),ee.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),B.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",X.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),T={data:s,query:t,active:e},b=t.view==="dashboard"||J(s)?"table":"tree",W();const o=Math.max(1,Math.round(performance.now()-r));fe=o,te=n;const a=e.evidence.snapshot();be(a,n),Ne(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=te){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(l=>l.kind==="relation"||l.kind==="request"||l.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=`${T?.query.id??"query"} · #${n+1} · ${o?.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 p=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${p}`,s.append(a,i,c,m),ue.append(s)})}function J(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function W(){if(!T)return;const{data:t,query:e,active:r}=T,n=e.view==="dashboard"||J(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),H.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),H.setAttribute("aria-pressed",String(b==="tree")),ee.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){B.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&J(t)){B.textContent=d==="en"?"Result table":"结果表格",ut(t);return}B.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),w.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 m of r){const p=document.createElement("td");p.textContent=lt(i[m]),c.append(p)}a.append(c)}n.append(s,a),e.append(n),w.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=re(e);if(r)return we(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 m=document.createElement("input");m.type="search",m.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const p=document.createElement("button");p.type="submit",p.className="order-search-submit",p.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),p.title=d==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),p.append(l),c.append(m,p),c.addEventListener("submit",y=>{y.preventDefault(),A.search=m.value.trim(),A.page=0,v(r,e).catch(L)}),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,v(r,e).catch(L)}));for(const y of t.statusFacets)S.append(me(y.name,y.orderCount,y.code.toLowerCase(),y.color,t.search.toUpperCase()===y.code,()=>{A.search=y.code,A.page=0,v(r,e).catch(L)},`${d==="en"?"Total":"总额"} ${pt(y.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const Te=d==="en"?["Order number","Order date","Status","Line Items"]:["订单号","订单日期","状态","订单明细"];for(const y of Te){const q=document.createElement("span");q.textContent=y,M.append(q)}if(g.append(M),!t.orders.length){const y=document.createElement("div");y.className="order-empty",y.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(y)}for(const y of t.orders)g.append(yt(y));const _=document.createElement("div");_.className="order-center-footer";const se=document.createElement("p"),oe=t.filteredOrders?t.page*t.pageSize+1:0,ae=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);se.textContent=d==="en"?`Showing ${oe}–${ae} of ${t.filteredOrders} orders`:`显示 ${oe}–${ae},共 ${t.filteredOrders} 条订单`;const D=document.createElement("div");D.className="pagination";const ie=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));D.append(j("‹",t.page-1,t.page===0,e,r));for(let y=0;y<ie;y+=1){const q=j(String(y+1),y,!1,e,r);q.classList.toggle("active",y===t.page),D.append(q)}D.append(j("›",t.page+1,t.page>=ie-1,e,r)),_.append(se,D),n.append(s,S,g,_),w.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 m=document.createElement("strong");if(m.textContent=String(e),i.append(c,m),a){const p=document.createElement("small");p.textContent=a,i.append(p)}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(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=re(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=we(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 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 p=Number(t.itemCount??n.length);if(p>n.length){const l=document.createElement("small");l.className="line-item-count",l.textContent=d==="en"?`${p} items`:`共 ${p} 项`,l.title=d==="en"?`Showing ${n.length} of ${p} line items`:`显示 ${n.length} 项,共 ${p} 项订单明细`,m.append(l)}return e.append(m),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,v(s,n).catch(L)}),o}function we(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){w.replaceChildren(Le(t,"result",0))}function Le(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"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const p=document.createElement("span");p.className="tree-preview",p.textContent=ht(t,a.length),c.append(m,p),i.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of a)l.append(Le(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(l),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 Ne(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"?"匹配订单":"结果"}`;X.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;F.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){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":"运行时设置"),k.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(),T){const{data:e,query:r,active:n}=T;ye.textContent=O(r.title),he.textContent=O(r.description),W(),be(n.evidence.snapshot(),te),Ne(e,r,fe),Oe($.checked?"opfs":"memory")}else F.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function ne(){return le.find(t=>t.id===z)??le[0]}async function Pe(t){F.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 v(ne(),r),Oe(t)}$.addEventListener("change",()=>{const t=$.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Pe(t).catch(L)});G.addEventListener("click",async()=>{if(E){G.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await v(ne(),E)}catch(t){L(t)}finally{G.disabled=!1}}});ee.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",W())});H.addEventListener("click",()=>{b="tree",W()});tt.addEventListener("click",()=>{w.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),ve()})});function L(t){const e=t instanceof Error?t:new Error(String(t));F.textContent=`${e.name}: ${e.message}`,X.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}ve();z=ne().id;Z();Pe(Ae).catch(L);
dist/assets/orders-DBfzfR_e.js ADDED
The diff for this file is too large to render. See raw diff
 
dist/assets/sqlite.worker-BcUEWFpc.js ADDED
The diff for this file is too large to render. See raw diff
 
dist/assets/style-F0ZYuCV2.css ADDED
@@ -0,0 +1 @@
 
 
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}.development-process{margin:54px 0 28px;padding:42px;border:1px solid var(--line);border-radius:24px;background:var(--paper);box-shadow:0 18px 48px #213c280d}.development-process-heading{display:grid;grid-template-columns:minmax(280px,.9fr) minmax(0,1.1fr);align-items:end;gap:48px}.development-process-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,3.5vw,48px);font-weight:500;line-height:1.08;letter-spacing:-.04em}.development-process-intro>p{margin:0;color:var(--muted);font-size:16px;line-height:1.7}.development-process-links{margin-top:22px;display:flex;flex-wrap:wrap;gap:10px}.source-link{min-width:210px;padding:12px 15px;display:grid;gap:3px;border:1px solid #cad3c9;border-radius:10px;color:var(--ink);background:#f8faf5;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.source-link:hover,.source-link:focus-visible{border-color:#819586;background:#fff;outline:none;transform:translateY(-1px)}.source-link-primary{color:#fff;border-color:var(--green);background:var(--green)}.source-link-primary:hover,.source-link-primary:focus-visible{border-color:var(--green-deep);background:var(--green-deep)}.source-link span{color:#77847a;font-size:10px;font-weight:850;letter-spacing:.13em}.source-link-primary span{color:#c8dccd}.source-link strong{font-size:14px;line-height:1.35}.development-process-flow{margin:38px 0 0;padding:0;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));border:1px solid #d7ddd3;border-radius:16px;background:#f8faf5;list-style:none;overflow:hidden}.development-process-flow li{min-width:0;padding:22px;border-left:1px solid #d7ddd3}.development-process-flow li:first-child{border-left:0}.development-step{display:block;margin-bottom:20px;color:var(--orange);font:800 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace}.development-process-flow strong{display:block;min-height:48px;font-size:16px;line-height:1.45}.development-process-flow p{min-height:92px;margin:10px 0 18px;color:var(--muted);font-size:14px;line-height:1.6}.development-process-flow code{color:var(--green);font:650 12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.context-efficiency{margin-top:18px;padding:24px;display:grid;grid-template-columns:minmax(230px,.72fr) minmax(0,1.28fr);align-items:center;gap:34px;border-radius:14px;color:#edf7ef;background:var(--green-deep)}.context-efficiency .section-index{margin-bottom:8px;color:var(--lime)}.context-efficiency h3{margin:0;font:500 24px/1.2 Georgia,"Noto Serif SC",serif;letter-spacing:-.025em}.context-efficiency>p{margin:0;color:#c7d8cc;font-size:15px;line-height:1.7}.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}.observability-proof{padding:88px 0 52px}.observability-proof-heading{margin-bottom:26px;display:grid;grid-template-columns:minmax(260px,.72fr) minmax(0,1.28fr);align-items:end;gap:34px}.observability-proof-heading h2{margin:8px 0 0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,4vw,48px);font-weight:500;line-height:1.05;letter-spacing:-.04em}.observability-proof-heading>p{margin:0;color:var(--muted);font-size:15px;line-height:1.7}.observability-proof-figure{margin:0}.observability-proof-figure img{width:100%;height:auto;display:block;border:1px solid #d7ddd5;border-radius:18px;background:#f4f5fb;box-shadow:0 22px 54px #1c2d221a}.observability-proof-figure figcaption{margin-top:12px;color:var(--muted);font-size:11px}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))}.development-process-heading{grid-template-columns:1fr;align-items:start;gap:24px}.development-process-flow{grid-template-columns:repeat(2,minmax(0,1fr))}.development-process-flow li:nth-child(3){border-left:0;border-top:1px solid #d7ddd3}.development-process-flow li:nth-child(4){border-top:1px solid #d7ddd3}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}.observability-proof-heading{grid-template-columns:1fr;align-items:start;gap:14px}}@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}.development-process{margin-top:38px;padding:26px 18px}.development-process-intro>p{font-size:15px}.development-process-links{align-items:stretch;flex-direction:column}.source-link{min-width:0;width:100%}.development-process-flow{grid-template-columns:1fr}.development-process-flow li{border-top:1px solid #d7ddd3;border-left:0}.development-process-flow li:first-child{border-top:0}.development-process-flow li:nth-child(3),.development-process-flow li:nth-child(4){border-left:0}.development-process-flow strong,.development-process-flow p{min-height:0}.context-efficiency{grid-template-columns:1fr;gap:16px;padding:20px}.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}.observability-proof{padding:64px 0 34px}.observability-proof-figure img{border-radius:12px}}
dist/assets/workItems-DS6iz1SR.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{S as it,f as j,E as k,g as Q,L as l,M as I,n as U,C as w,d as f,a as b,j as z,e as O,Q as J,U as K,R as rt,B as st,D as nt,c as ot}from"./dynamic-search-BwvXmN4R.js";import{EntityCreationError as H,EntityCreation as v}from"./entity-creation-Bqaw1C4U.js";class N extends it{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",n=!0,s){return super.relationQuery(t,e,i,r,n,s)}}const R=Symbol("managed entity construction");class m{static teaqlTemporaryId=0;static teaqlMutationFields=new j("WorkItem",["id","title","description","platform","version"],{id:"immutable_field",version:"immutable_field"});id;title;description;platform;version;constructor(t,e,i=!1){if(e!==R)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];Object.assign(this,n),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof p?t.platform:p.fromRecord(t.platform),this.markLoaded("platform"))}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=v.hydrated(new m(t,R));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){return Object.fromEntries(Object.entries(this))}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 m.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"WorkItem",e,i=>new m({id:i},R,!0))}static teaqlCreate(t){return v.create(t,"WorkItem",e=>new m({id:e},R,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());return v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),i}teaqlValidateLoadedIdentities(t=new Set){t.has(this)||(t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version))}teaqlDiscardRestoredGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)))}teaqlNormalizeGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()}})))}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),m.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}return i}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){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 w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y),y.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"WorkItem",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();return d.scopeFor(c),e.afterGraphRollback(()=>{for(const P of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,P)||delete this[P];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c),d.scopeFor(c),e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),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}}const T=Symbol("managed entity construction");class p{static teaqlTemporaryId=0;static teaqlMutationFields=new j("Platform",["id","name","version"],{id:"immutable_field",version:"immutable_field"});id;name;version;constructor(t,e,i=!1){if(e!==T)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--p.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:i?new b:b.empty(),writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];if(delete n.workItemList,Object.assign(this,n),Array.isArray(t.workItemList)){const s=t.workItemList;this._workItemList=new b(s.map(o=>o instanceof m?o:m.fromRecord(o)),{totalCount:s.totalCount,aggregations:s.aggregations,summary:s.summary,facets:s.facets,isLoaded:s.isLoaded??!0}),this.markLoaded("workItemList")}}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const i of this._workItemList)i.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const i=v.hydrated(new p(t,T));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("workItemList")&&(t.workItemList=this._workItemList),t}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 p.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"Platform",e,i=>new p({id:i},T,!0))}static teaqlCreate(t){return v.create(t,"Platform",e=>new p({id:e},T,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i);for(const r of this._workItemList)i=r.teaqlValidateMutationOrigins(t)||i;return i}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,i]of this._workItemList.entries())try{i.teaqlValidateLoadedIdentities(t)}catch(r){if(!(r instanceof w))throw r;const n=f.property("work_item_list").index(e);throw new w(r.violations.map(s=>({...s,location:s.location.prefixedBy(n)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));for(const i of this._workItemList)i.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},work_item_list:t.sourceMembers(this._workItemList)}));for(const i of this._workItemList){i.teaqlAttachRoot(this._root);const r=i.platform;(i._action!=="Update"||i._root.hasPending(i.teaqlEntityKey()))&&(this.id===void 0||!i.isLoaded("platform")||(typeof r=="object"&&r!==null?r.id:r)!==this.id)&&i.updatePlatform(this),i.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),p.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}let r=i;for(const[n,s]of this._workItemList.entries())try{r=s.teaqlAdmitGraph(t)||r}catch(o){if(!(o instanceof w))throw o;const y=f.property("work_item_list").index(n);throw new w(o.violations.map(d=>({...d,location:d.location.prefixedBy(y)})))}return r}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(u)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y);const d=y.scopeFor(this.teaqlEntityKey());for(const[u,a]of this._workItemList.entries()){a.teaqlAttachRoot(this._root);const q=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof q=="object"&&q!==null?q.id:q)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,i,d,n)}catch(c){if(!(c instanceof w))throw c;const $=f.property("work_item_list").index(u);throw new w(t.translateCheckResults(c.violations.map(P=>({...P,location:P.location.prefixedBy($)}))))}}}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"Platform",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const L=d.scopeFor(this.teaqlEntityKey());for(const[_,g]of this._workItemList.entries()){g.teaqlAttachRoot(this._root);const E=g.platform;(g._action!=="Update"||g._root.hasPending(g.teaqlEntityKey()))&&(this.id===void 0||!g.isLoaded("platform")||(typeof E=="object"&&E!==null?E.id:E)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,i,L,n)}catch(C){if(!(C instanceof w))throw C;const F=f.property("work_item_list").index(_);throw new w(t.translateCheckResults(C.violations.map(V=>({...V,location:V.location.prefixedBy(F)}))))}}return this}const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();d.scopeFor(c),e.afterGraphRollback(()=>{for(const L of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,L)||delete this[L];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c);const P=d.scopeFor(c);for(const[L,_]of this._workItemList.entries()){_.teaqlAttachRoot(this._root);const g=_.platform;(_._action!=="Update"||_._root.hasPending(_.teaqlEntityKey()))&&(this.id===void 0||!_.isLoaded("platform")||(typeof g=="object"&&g!==null?g.id:g)!==this.id)&&_.updatePlatform(this);try{await _.teaqlSaveWithinGraph(t,e,i,P,n)}catch(E){if(!(E instanceof w))throw E;const C=f.property("work_item_list").index(L);throw new w(t.translateCheckResults(E.violations.map(F=>({...F,location:F.location.prefixedBy(C)}))))}}return e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),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 Y=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 D{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Platform"}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=z(i,t,Y,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 at(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.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),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({entityName:"WorkItem",toQuery:()=>new N("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({entityName:"WorkItem",toQuery:()=>new N("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 N("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{entityName:"WorkItem",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",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",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,n=r?[]:i.map(o=>o instanceof p?o:p.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(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,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof p?a:p.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}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),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof p?o:p.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class at{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return p.teaqlCreate(t)}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 G{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"WorkItem"}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=z(i,t,Y,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 ht(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.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),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",t),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title",t),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),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,n=r?[]:i.map(o=>o instanceof m?o:m.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(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,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof m?a:m.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}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),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof m?o:m.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class ht{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return m.teaqlCreate(t)}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 A{static platforms(){return new D(!1)}static platformsWithMinimalFields(){return new D(!0)}static workItems(){return new G(!1)}static workItemsWithMinimalFields(){return new G(!0)}}const lt={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 ut(h){let t=(await A.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];t||(t=p.teaqlBootstrapNew(h,"1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(h)),h.withActiveRoot({entity:"Platform",id:t.id})}const dt=new rt(lt,{Platform:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:f.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:f.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:f.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:f.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:f.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:f.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:f.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:ut}),ct={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}}}},x=document.querySelector("#status"),pt=document.querySelector("#result"),B=document.querySelector("#persist"),W=document.querySelector("#reset");let S;const X=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=X==="opfs";async function mt(h){const t=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),e=await st.open(t,{...ct},{storage:h,databaseName:"teaql-browser-example.sqlite3"});e.install(dt);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new K().insertResource("dataService",e).withMutationPolicyRegistry(new nt(()=>({identity:i,review:(n,s)=>s.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ot(n=>({policy:n,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Z({context:h}){if(!(await A.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(h)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await(await A.workItems().comment("reserve one browser demo work item").purpose("seed deterministic data through managed creation").newEntity(h)).updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(h)}async function tt(h){const t=await A.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(h.context);pt.textContent=JSON.stringify(t,null,2),x.textContent=`${h.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function et(h){x.textContent=`Opening ${h.toUpperCase()} SQLite/WASM…`;const t=S;S=void 0,await t?.client.close();const e=await mt(h);S=e,await Z(e),await tt(e)}B.addEventListener("change",()=>{const h=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",h),et(h).catch(M)});W.addEventListener("click",async()=>{if(S){W.disabled=!0;try{await S.client.reset(S.context),await Z(S),await tt(S)}catch(h){M(h)}finally{W.disabled=!1}}});function M(h){const t=h instanceof Error?h:new Error(String(h));x.textContent=`${t.name}: ${t.message}`}et(X).catch(M);
dist/index.html CHANGED
@@ -6,9 +6,9 @@
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
- <script type="module" crossorigin src="/assets/main-DKg7I1TH.js"></script>
10
- <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
11
- <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
13
  <body>
14
  <div class="page-shell">
@@ -96,6 +96,63 @@
96
  </nav>
97
  </section>
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  <section class="runtime-bar" aria-label="Runtime settings">
100
  <p id="status" role="status">Starting SQLite/WASM…</p>
101
  <div class="controls">
 
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
+ <script type="module" crossorigin src="/assets/main-Csdici-L.js"></script>
10
+ <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BwvXmN4R.js">
11
+ <link rel="stylesheet" crossorigin href="/assets/style-F0ZYuCV2.css">
12
  </head>
13
  <body>
14
  <div class="page-shell">
 
96
  </nav>
97
  </section>
98
 
99
+ <section class="development-process" aria-labelledby="development-process-title">
100
+ <div class="development-process-heading">
101
+ <div>
102
+ <p class="section-index" data-i18n="developmentProcess">00 / DEVELOPMENT PROCESS</p>
103
+ <h2 id="development-process-title" data-i18n="developmentProcessTitle">From one domain model to executable evidence.</h2>
104
+ </div>
105
+ <div class="development-process-intro">
106
+ <p data-i18n="developmentProcessIntro">TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.</p>
107
+ <div class="development-process-links">
108
+ <a class="source-link source-link-primary" href="https://github.com/teaql/teaql-ts/blob/main/examples/browser-sqlite/order-model.xml" target="_blank" rel="noreferrer">
109
+ <span data-i18n="modelSource">MODEL SOURCE</span>
110
+ <strong data-i18n="viewOrderModel">View order-model.xml</strong>
111
+ </a>
112
+ <a class="source-link" href="https://github.com/teaql/teaql-ts/tree/main/examples/browser-sqlite/assist" target="_blank" rel="noreferrer">
113
+ <span data-i18n="scopedGuidance">SCOPED GUIDANCE</span>
114
+ <strong data-i18n="viewModelAssist">View model-aware Assist</strong>
115
+ </a>
116
+ </div>
117
+ </div>
118
+ </div>
119
+
120
+ <ol class="development-process-flow">
121
+ <li>
122
+ <span class="development-step">01</span>
123
+ <strong data-i18n="processModelTitle">Model the domain</strong>
124
+ <p data-i18n="processModelBody">Define entities, fields, relationships, constant objects, and constraints in one model file.</p>
125
+ <code>order-model.xml</code>
126
+ </li>
127
+ <li>
128
+ <span class="development-step">02</span>
129
+ <strong data-i18n="processGenerateTitle">Generate the working surface</strong>
130
+ <p data-i18n="processGenerateBody">Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.</p>
131
+ <code>Q · E · Schema · Assist</code>
132
+ </li>
133
+ <li>
134
+ <span class="development-step">03</span>
135
+ <strong data-i18n="processQueryTitle">Build one bounded Q request</strong>
136
+ <p data-i18n="processQueryBody">Application code selects only what the page needs and attaches a readable comment and purpose.</p>
137
+ <code>comment · purpose · execute</code>
138
+ </li>
139
+ <li>
140
+ <span class="development-step">04</span>
141
+ <strong data-i18n="processEvidenceTitle">Run and retain evidence</strong>
142
+ <p data-i18n="processEvidenceBody">The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.</p>
143
+ <code>Result · TraceChain · SQL</code>
144
+ </li>
145
+ </ol>
146
+
147
+ <div class="context-efficiency">
148
+ <div>
149
+ <p class="section-index" data-i18n="contextEfficiency">CONTEXT EFFICIENCY</p>
150
+ <h3 data-i18n="contextEfficiencyTitle">Spend context on the business change.</h3>
151
+ </div>
152
+ <p data-i18n="contextEfficiencyBody">Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.</p>
153
+ </div>
154
+ </section>
155
+
156
  <section class="runtime-bar" aria-label="Runtime settings">
157
  <p id="status" role="status">Starting SQLite/WASM…</p>
158
  <div class="controls">
dist/orders.html CHANGED
@@ -5,10 +5,10 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="data:," />
7
  <title>TeaQL browser order TraceChain</title>
8
- <script type="module" crossorigin src="/assets/orders--ZnCV5fY.js"></script>
9
- <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
10
- <link rel="modulepreload" crossorigin href="/assets/object-location-CJfVWqJC.js">
11
- <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
13
  <body>
14
  <main>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="data:," />
7
  <title>TeaQL browser order TraceChain</title>
8
+ <script type="module" crossorigin src="/assets/orders-DBfzfR_e.js"></script>
9
+ <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BwvXmN4R.js">
10
+ <link rel="modulepreload" crossorigin href="/assets/entity-creation-Bqaw1C4U.js">
11
+ <link rel="stylesheet" crossorigin href="/assets/style-F0ZYuCV2.css">
12
  </head>
13
  <body>
14
  <main>
dist/work-items.html CHANGED
@@ -5,9 +5,9 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="data:," />
7
  <title>TeaQL Browser SQLite WorkItems</title>
8
- <script type="module" crossorigin src="/assets/workItems-B6je_A1X.js"></script>
9
- <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
10
- <link rel="modulepreload" crossorigin href="/assets/object-location-CJfVWqJC.js">
11
  <link rel="stylesheet" crossorigin href="/assets/workItems-5mJKEgxC.css">
12
  </head>
13
  <body>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="data:," />
7
  <title>TeaQL Browser SQLite WorkItems</title>
8
+ <script type="module" crossorigin src="/assets/workItems-DS6iz1SR.js"></script>
9
+ <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BwvXmN4R.js">
10
+ <link rel="modulepreload" crossorigin href="/assets/entity-creation-Bqaw1C4U.js">
11
  <link rel="stylesheet" crossorigin href="/assets/workItems-5mJKEgxC.css">
12
  </head>
13
  <body>
index.html CHANGED
@@ -6,9 +6,9 @@
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
- <script type="module" crossorigin src="/assets/main-DKg7I1TH.js"></script>
10
- <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
11
- <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
13
  <body>
14
  <div class="page-shell">
@@ -96,6 +96,63 @@
96
  </nav>
97
  </section>
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  <section class="runtime-bar" aria-label="Runtime settings">
100
  <p id="status" role="status">Starting SQLite/WASM…</p>
101
  <div class="controls">
 
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
+ <script type="module" crossorigin src="/assets/main-Csdici-L.js"></script>
10
+ <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BwvXmN4R.js">
11
+ <link rel="stylesheet" crossorigin href="/assets/style-F0ZYuCV2.css">
12
  </head>
13
  <body>
14
  <div class="page-shell">
 
96
  </nav>
97
  </section>
98
 
99
+ <section class="development-process" aria-labelledby="development-process-title">
100
+ <div class="development-process-heading">
101
+ <div>
102
+ <p class="section-index" data-i18n="developmentProcess">00 / DEVELOPMENT PROCESS</p>
103
+ <h2 id="development-process-title" data-i18n="developmentProcessTitle">From one domain model to executable evidence.</h2>
104
+ </div>
105
+ <div class="development-process-intro">
106
+ <p data-i18n="developmentProcessIntro">TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.</p>
107
+ <div class="development-process-links">
108
+ <a class="source-link source-link-primary" href="https://github.com/teaql/teaql-ts/blob/main/examples/browser-sqlite/order-model.xml" target="_blank" rel="noreferrer">
109
+ <span data-i18n="modelSource">MODEL SOURCE</span>
110
+ <strong data-i18n="viewOrderModel">View order-model.xml</strong>
111
+ </a>
112
+ <a class="source-link" href="https://github.com/teaql/teaql-ts/tree/main/examples/browser-sqlite/assist" target="_blank" rel="noreferrer">
113
+ <span data-i18n="scopedGuidance">SCOPED GUIDANCE</span>
114
+ <strong data-i18n="viewModelAssist">View model-aware Assist</strong>
115
+ </a>
116
+ </div>
117
+ </div>
118
+ </div>
119
+
120
+ <ol class="development-process-flow">
121
+ <li>
122
+ <span class="development-step">01</span>
123
+ <strong data-i18n="processModelTitle">Model the domain</strong>
124
+ <p data-i18n="processModelBody">Define entities, fields, relationships, constant objects, and constraints in one model file.</p>
125
+ <code>order-model.xml</code>
126
+ </li>
127
+ <li>
128
+ <span class="development-step">02</span>
129
+ <strong data-i18n="processGenerateTitle">Generate the working surface</strong>
130
+ <p data-i18n="processGenerateBody">Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.</p>
131
+ <code>Q · E · Schema · Assist</code>
132
+ </li>
133
+ <li>
134
+ <span class="development-step">03</span>
135
+ <strong data-i18n="processQueryTitle">Build one bounded Q request</strong>
136
+ <p data-i18n="processQueryBody">Application code selects only what the page needs and attaches a readable comment and purpose.</p>
137
+ <code>comment · purpose · execute</code>
138
+ </li>
139
+ <li>
140
+ <span class="development-step">04</span>
141
+ <strong data-i18n="processEvidenceTitle">Run and retain evidence</strong>
142
+ <p data-i18n="processEvidenceBody">The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.</p>
143
+ <code>Result · TraceChain · SQL</code>
144
+ </li>
145
+ </ol>
146
+
147
+ <div class="context-efficiency">
148
+ <div>
149
+ <p class="section-index" data-i18n="contextEfficiency">CONTEXT EFFICIENCY</p>
150
+ <h3 data-i18n="contextEfficiencyTitle">Spend context on the business change.</h3>
151
+ </div>
152
+ <p data-i18n="contextEfficiencyBody">Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.</p>
153
+ </div>
154
+ </section>
155
+
156
  <section class="runtime-bar" aria-label="Runtime settings">
157
  <p id="status" role="status">Starting SQLite/WASM…</p>
158
  <div class="controls">
orders.html CHANGED
@@ -5,10 +5,10 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="data:," />
7
  <title>TeaQL browser order TraceChain</title>
8
- <script type="module" crossorigin src="/assets/orders--ZnCV5fY.js"></script>
9
- <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
10
- <link rel="modulepreload" crossorigin href="/assets/object-location-CJfVWqJC.js">
11
- <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
13
  <body>
14
  <main>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="data:," />
7
  <title>TeaQL browser order TraceChain</title>
8
+ <script type="module" crossorigin src="/assets/orders-DBfzfR_e.js"></script>
9
+ <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BwvXmN4R.js">
10
+ <link rel="modulepreload" crossorigin href="/assets/entity-creation-Bqaw1C4U.js">
11
+ <link rel="stylesheet" crossorigin href="/assets/style-F0ZYuCV2.css">
12
  </head>
13
  <body>
14
  <main>
source/provenance.json CHANGED
@@ -1,17 +1,17 @@
1
  {
2
  "repository": "https://github.com/teaql/teaql-ts",
3
- "commit": "1e1f50e7a54f2f47753a24cdd988e53fbde78180",
4
  "branch": "main",
5
- "runtimeVersion": "0.3.1",
6
  "sourceDirectory": "source/teaql-ts",
7
  "applicationDirectory": "source/teaql-ts/examples/browser-sqlite",
8
  "buildDirectory": "dist",
9
  "validation": {
10
- "runtimeSuitesPassed": 57,
11
- "runtimeTestsPassed": 608,
12
- "runtimeTestsSkipped": 6,
13
  "browserSmoke": "passed",
14
- "generatedOrderSmoke": "passed"
 
15
  },
16
  "limitations": [
17
  "No application backend",
 
1
  {
2
  "repository": "https://github.com/teaql/teaql-ts",
3
+ "commit": "b7c0f71f717d368c222da7cc8484db32bf281f11",
4
  "branch": "main",
5
+ "runtimeVersion": "0.6.0",
6
  "sourceDirectory": "source/teaql-ts",
7
  "applicationDirectory": "source/teaql-ts/examples/browser-sqlite",
8
  "buildDirectory": "dist",
9
  "validation": {
10
+ "runtimeBuild": "passed",
11
+ "browserBuild": "passed",
 
12
  "browserSmoke": "passed",
13
+ "generatedOrderSmoke": "passed",
14
+ "visualQA": "desktop and 390px English/Chinese"
15
  },
16
  "limitations": [
17
  "No application backend",
source/teaql-ts/.github/release-signing-key.asc ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN PGP PUBLIC KEY BLOCK-----
2
+
3
+ mQINBGpsF40BEAC+Olumai3qpCWXV6QYFufotbsG2TK+mIvFfHxOjX0qq24PsGW7
4
+ D3iXxAYxG1Ohu3dNIM7Rj2lvLpxL1si6pJCvuD8vSnuhuubcpOJJIhGeG4S+r3sy
5
+ CFbgYw5Wde0t9MG4Gr5+p6OB0o3yeOeLB8Xeyk+jTZ/O9ukGgpGANNu8wMpEKE5t
6
+ 06mjYPcajUdpPCs0FIC9WhyyPBQw4CLywMuJ1amnrs+yWDyaJogkw39m1/VZtnHE
7
+ FEg9PLg3SKq60DydI2kiOL2ozum/nj9y0Oe+wxNH+k+ACokZsoGV5PMG+PcDsOO/
8
+ dPQ1v1Jm7aKAl6pyyV/jCq9tU43toKXD5MHm8Rffsb1nfgRHERzbqcl9bxsxmk1/
9
+ 62ePdc3RWiqlMS0YdqXYkd7yFtrZmJUL5xrRB0bI5tEbH0i4yema73WeSMV4PSlq
10
+ xU71TdA41Tq9OgmKKpVfWAThunKg50Dt1JXApTnCVMuEG+ejdvzXDwqlH+T9fXnp
11
+ knVgMpusZhhk4S9rP4QTmBmwNJZMIOMYNoKja0K/VAjKTfYmSHSrhpdWCkD71tqF
12
+ vD3RfTG/QohuhUz34EzN9pIpZpBAAQ6LHfISVLp9R8wdDRlOm0ICK6eVWooxtdLP
13
+ x6dQA/C4MApbuRj1pKgfwCk1X0k6HkZJA8KOqDWdmthHuFS6l1//LCVzeQARAQAB
14
+ tChQaGlsaXAgWiAoZ3BnIGZvciB0ZWFxbCkgPGluZm9AdGVhcWwuaW8+iQJUBBMB
15
+ CgA+FiEE0ZXN0QKIVz1lAZPaa58fi+AL1ZUFAmpsF40CGwMFCQHhM4AFCwkIBwIG
16
+ FQoJCAsCBBYCAwECHgECF4AACgkQa58fi+AL1ZUBdw//Qd9RBSgaxtJcSV4SnYDh
17
+ 0Q2g8rWjA9WqREQAaMJJkwSHw3WsuvDi1At/zUDOy1DOjN0BrS/1tj5UneOqC4AF
18
+ jg/tuHFxTcfUPUFpPp/0Nj/jA7QPbGC2Ih2wVO8guO4JqUGbNsU0d59scwHRxSlI
19
+ l4PndTKVANi6l/cgdWXuejfLr/uPvMUji0lsODFBI4YOSvAG0RH1Ut2HHNMiNejZ
20
+ acstCPSKut01YSTDYce74RMZlBu3N+I1jW5ivOFabjkpnP2gMrYSzDzF+TsZLZAr
21
+ QYWi4pYdepf0/4LoBCUO7PqU2secg5rZ7r74E6xnBIntpTc2EG4zO4LfV4xDkavH
22
+ 0Ar/I+L1VySx2QN9DiMywFJBau7Ajbc62gQacEzUzpBzPu2IW76XICLP0b5ZOltm
23
+ oBZg7xW1kvY/fFbfYT7K0K9L03K/fhIYzRRyhryZUAzv474zr9E7Tb96lsgubul6
24
+ 8s43GmQOadgHG3ZElX8XE8vGJ/ARm2FsIL99Iyw1AsSH7e2ri4diLktuVGKv7xSc
25
+ Jzywf+iTlTABPMlHJ/VDJ4KbzS5qlI/uwpdNlmCYfizXZncWIXAGpTJwoJgb0KC5
26
+ wasDtFBNgX0cI/70Q0uDkligIQCLnqpu+LBmOynzJfwos2fzDGcsssf4ZMyL44gV
27
+ wQ0oEO5pocdEBLtGLlc4wuO5Ag0EamwXjQEQAJeD4iIKzNhQ1eJZSYmHMOcXh4pR
28
+ 1rxISk0Pnu3u0raUeCKCj5iIUQTTD7b49O9j1HIxwCbjnjSeiIjE+4n/K88v/bIk
29
+ oa4yT8e+pwxs260KivtikltePAR3aNr3yr/XJEO1qCOIBaz2tW3AZlTDEOUli3Rt
30
+ unIwBwf9BC7CC9IbSDapSnWEp54XrV/uP/I1xtBB6hKla5IJNyaJzgUljb9aRXdD
31
+ nPXh7eTBsErY3io+x/EQXhmgS2qtnfC7nqDXreLohC2WrllqvyWVto1apYzS/g42
32
+ onm3yvdMadt6FhX1oBZcktLQjY/fat7OCsAHvmluCwRpOQDw+zfMpLuWw6fbWSHl
33
+ 6i1hE/1iKfW0a4NHtNleH+ClFJPyW3U5a5cWOv8mTC8xXVT+bAxdcEOxpDVzFkgl
34
+ +zgRFPB++kJAjyHqAqcFZOlQSfY0wHRT+DJKoWDGziNc5ae0U7e5oF+1kYUqOe00
35
+ EAZajSDQj5BpF+dCrA8F08i48fVbb7WqYHRivARhkh/+z6qcbqjzJP799BCOYetB
36
+ 0wehG5q9EZCgi0FqSjq+Ze0C+aGB0wuehOqgXqGG3C3xOpgduUNPucdIR8et27Pa
37
+ ij0zmKciYbs3VsvlcDxkx/7No3xh5oIk9If2ThE+A2/nbIC3rLjjo7dVOqvvrRxR
38
+ x030Qy7h2/NmycPZABEBAAGJAjwEGAEKACYWIQTRlc3RAohXPWUBk9prnx+L4AvV
39
+ lQUCamwXjQIbDAUJAeEzgAAKCRBrnx+L4AvVldZfD/9EMaDjuUXDFzVrCa4/03Wz
40
+ 1HStHRLL8U9q+tc7GQDFeQELE7HH45MqA1j2ayRBOdhCcNlq0hRA371T3khqwxZ7
41
+ PsU0TFYxosfDfuZ0nneJtFjI9yeABPhaXc+vcJZRTSn0qtvsSQeA+xJxfeNYLjK9
42
+ 0RCxd6qipVQjNnZgmpAvZNbqGO1RSLH8kdQcU21iXSL6EEawZmvYqHWX4pXVYI07
43
+ YRbLUMUlXFSoTQTi20LORgOfk/gHNQxgRed82RGhtv7Fx8wm2jXOFOrlGDYjJ6f3
44
+ RwxDC3GPX+DR3HWYk8tGxYiCxvVa/aP+ezamBDs+wzVJ+GtzTkeP/jYTRSBUFfCS
45
+ R9e1XyRqt+SsvutxkeMA89QlV9TkBGG1P+66Ibjf3pb6BG+3EBH77OXlMMmn1Q/q
46
+ rT0woJQXF4q3ZndunaIPYoIVlqajdIL7qJ9HMvpXN6cuD8F9J27DJGuZwTUYA7ps
47
+ 0f6n4ylfO8UK0aEYQ4aoWGcgHONxYU7mXLwkUCcMhAd44HWUQwKr44XPalZtwGka
48
+ 5MCfgdv2DQAWisuLZO6kYXeaallxRhfwO6Qr+7v4qBGogb4iBNtRrM8R+UYv9RTa
49
+ dsuUUWeDko0TFNxYFsCmFRtX3nN/eSn6E2DW3GS2+05PISd9f5Aun6AOCjwQNneZ
50
+ QCad98Aov4EvyhTT7opivw==
51
+ =gHhI
52
+ -----END PGP PUBLIC KEY BLOCK-----
source/teaql-ts/.github/workflows/example-gate.yml CHANGED
@@ -20,8 +20,9 @@ jobs:
20
  with:
21
  node-version: '22'
22
  cache: npm
23
- - run: npm install
24
- - run: npm run build
 
25
  - name: Start dedicated S3 example fixture
26
  run: |
27
  docker run -d --name teaql-ts-example-s3 \
 
20
  with:
21
  node-version: '22'
22
  cache: npm
23
+ # The canonical gate hashes the complete checked-in source before its
24
+ # isolated builds replace tracked dist chunks. Do not prebuild here.
25
+ - run: npm ci --no-audit --fund=false
26
  - name: Start dedicated S3 example fixture
27
  run: |
28
  docker run -d --name teaql-ts-example-s3 \
source/teaql-ts/.github/workflows/release.yml CHANGED
@@ -1,32 +1,67 @@
1
- name: Publish TypeScript package
2
 
3
  on:
4
  workflow_dispatch:
5
- push:
6
- tags:
7
- - "typescript-v*"
 
 
 
 
 
 
 
 
 
 
8
 
9
  jobs:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  publish:
 
11
  runs-on: ubuntu-latest
12
  environment: npm
13
  permissions:
14
  contents: read
15
  id-token: write
16
  steps:
17
- - uses: actions/checkout@v4
 
 
 
18
  - uses: actions/setup-node@v4
19
  with:
20
  node-version: "24"
21
  registry-url: https://registry.npmjs.org
22
- cache: npm
23
- - run: npm ci
24
- - name: Verify tag matches package version
25
- run: test "${GITHUB_REF_NAME#typescript-v}" = "$(node -p 'require("./package.json").version')"
26
- # Keep native SQLite lifecycle coverage deterministic and verify the
27
- # current Node LTS used by generated TeaQL projects.
28
- - run: npm test -- --runInBand
29
- - run: npm run build
30
  - name: Upgrade npm for trusted publishing
31
  run: npm install --global npm@latest
32
- - run: npm publish --access public
 
 
1
+ name: Promote qualified typescript packages
2
 
3
  on:
4
  workflow_dispatch:
5
+ inputs:
6
+ release_tag:
7
+ description: Existing signed tag whose exact packages passed internal qualification
8
+ required: true
9
+ type: string
10
+ qualification_sha256:
11
+ description: SHA-256 of logging-qualification.json retained with the release evidence
12
+ required: true
13
+ type: string
14
+
15
+ concurrency:
16
+ group: typescript-public-promotion
17
+ cancel-in-progress: false
18
 
19
  jobs:
20
+ verify:
21
+ runs-on: ubuntu-latest
22
+ permissions:
23
+ contents: read
24
+ steps:
25
+ - uses: actions/checkout@v4
26
+ with:
27
+ ref: ${{ inputs.release_tag }}
28
+ fetch-depth: 0
29
+ - name: Verify signed source and qualified package bytes
30
+ env:
31
+ GH_TOKEN: ${{ github.token }}
32
+ RELEASE_TAG: ${{ inputs.release_tag }}
33
+ QUALIFICATION_SHA256: ${{ inputs.qualification_sha256 }}
34
+ shell: bash
35
+ run: |
36
+ export GNUPGHOME="$RUNNER_TEMP/teaql-release-signatures"
37
+ mkdir -m 700 "$GNUPGHOME"
38
+ gpg --batch --import .github/release-signing-key.asc
39
+ python3 scripts/verify-qualified-release.py \
40
+ --tag "$RELEASE_TAG" --manifest-sha256 "$QUALIFICATION_SHA256" \
41
+ --language typescript --repository "$GITHUB_REPOSITORY"
42
+ - uses: actions/upload-artifact@v4
43
+ with:
44
+ name: qualified-typescript-packages
45
+ path: qualified-packages/
46
+ if-no-files-found: error
47
+
48
  publish:
49
+ needs: verify
50
  runs-on: ubuntu-latest
51
  environment: npm
52
  permissions:
53
  contents: read
54
  id-token: write
55
  steps:
56
+ - uses: actions/download-artifact@v4
57
+ with:
58
+ name: qualified-typescript-packages
59
+ path: qualified-packages/
60
  - uses: actions/setup-node@v4
61
  with:
62
  node-version: "24"
63
  registry-url: https://registry.npmjs.org
 
 
 
 
 
 
 
 
64
  - name: Upgrade npm for trusted publishing
65
  run: npm install --global npm@latest
66
+ - name: Publish the verified tarball
67
+ run: npm publish ./qualified-packages/*.tgz --access public --provenance
source/teaql-ts/README.md CHANGED
@@ -282,6 +282,14 @@ final execution report. It is a workflow, not a guarantee of unattended correctn
282
 
283
  Node.js/npm for the repository examples. Browser SQLite runs in a Web Worker with SQLite/WASM. From a checkout of this repository:
284
 
 
 
 
 
 
 
 
 
285
  ```bash
286
  cd examples/school-management
287
  npm install
 
282
 
283
  Node.js/npm for the repository examples. Browser SQLite runs in a Web Worker with SQLite/WASM. From a checkout of this repository:
284
 
285
+ The Node SQLite adapter and its examples require **Node 22+** and
286
+ **better-sqlite3 13.0.3+ (13.x)**. Version 13 uses N-API; the older 12.x binding can
287
+ abort during allocation-driven garbage collection on Node 24.19.0 even when a
288
+ manual `global.gc()` check passes. The repository regression executes 300,000
289
+ prepared queries in a separate real Node process twice. This native-provider
290
+ requirement does not apply to browser SQLite/WASM or Expo SQLite, and does not
291
+ raise the runtime core's Node requirement for unrelated providers.
292
+
293
  ```bash
294
  cd examples/school-management
295
  npm install
source/teaql-ts/examples/browser-sqlite/README.md CHANGED
@@ -12,6 +12,15 @@ Java, Rust, Go, Python, .NET and Swift runtimes. The seven-language strip links
12
  to each runtime source and marks TypeScript as the current browser runtime; it
13
  does not imply that selecting another link swaps the page's execution engine.
14
 
 
 
 
 
 
 
 
 
 
15
  `OrderStatus` is a seventh, constant model object rather than a string field.
16
  Its five fixed values are reconciled through `RuntimeModule` bootstrap, orders
17
  store the status object ID, and generated Q expressions select, filter, and
 
12
  to each runtime source and marks TypeScript as the current browser runtime; it
13
  does not imply that selecting another link swaps the page's execution engine.
14
 
15
+ The page includes a development-process section linking directly to
16
+ `order-model.xml` and the model-aware Assist directory. It explains the real
17
+ model-to-runtime path: define the domain once, generate typed Q/E APIs and
18
+ scoped Assist, write one bounded Q request with comment and purpose, then let
19
+ the runtime retain TraceChain, timing and actual SQL evidence. Progressive
20
+ entity/action/field Assist keeps agents from loading the runtime internals and
21
+ the entire generated library into every context window; no unmeasured context
22
+ savings are claimed.
23
+
24
  `OrderStatus` is a seventh, constant model object rather than a string field.
25
  Its five fixed values are reconciled through `RuntimeModule` bootstrap, orders
26
  store the status object ID, and generated Q expressions select, filter, and
source/teaql-ts/examples/browser-sqlite/generated-order-hashes.json CHANGED
@@ -1,19 +1,19 @@
1
  {
2
- "src/generated-bootstrap.ts": "5f3065c1e4794c0d21ada7c2eef48f4694cec1cbc4771fa48bc7d6ff9221540b",
3
  "src/generated-search-models.ts": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3",
4
- "src/generated/E.ts": "940a5dfa19912a7973ac44879488b37132d981cd3325f7f28aefdef0480c7542",
5
  "src/generated/Q.ts": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f",
6
- "src/generated/models/Customer.ts": "5ff4b46a58b2dad54858b7ed444f3b78c49941b8e01b150008d6f48ae11cc067",
7
- "src/generated/models/CustomerOrder.ts": "94168486fb9dffd2f99296bf93eb0bfcfa83744d4516e706f8b144cec8317f1a",
8
- "src/generated/models/OrderItem.ts": "e2884b4013b7478d8e3083b1a18ed9b3321c19b49004249b5486a31385c6797e",
9
- "src/generated/models/OrderStatus.ts": "2bb7bfe245ab3dd75ca4359037769a3f760c90fed5ac214032f008c90fb39c14",
10
- "src/generated/models/Platform.ts": "55d9146a4b42929e4f206beb9288921dfaee5c08ac9616100898d4c6e7817c5a",
11
- "src/generated/requests/CustomerOrderRequest.ts": "167326d997fa314411fdad1349ea34aef3c1232c2c469253714318905f041744",
12
- "src/generated/requests/CustomerRequest.ts": "7c1dfc760a67d523579ef0758731d7c6772930d8360e5594a37926aa5df3e5f3",
13
- "src/generated/requests/OrderItemRequest.ts": "ee3fe2e2d3dc6eae0c1ff1697cb7f73626595682dd2b5a87218b855287468c0a",
14
- "src/generated/requests/OrderStatusRequest.ts": "fbb8ed0507ec80f4b9a5d0d260f7e08ecc524d56cc4b78166326750629cfec24",
15
- "src/generated/requests/PlatformRequest.ts": "dcf958694498114f744ea59570dc92e4fd2e93b84ddb2c831af99be04b08c2b7",
16
- "src/runtime-module.ts": "f92fe9a9474678d26a233eb734b14493b4ddc216ed3b648bfad723b4b6a46eeb",
17
- "src/teaql-schemas.ts": "68cb7cacc725ff041d2289f17d7817ae56f37d035c92f2feb6c1318face6f806",
18
- "src/teaql-ts.ts": "cc705f9f7873450eae541311317db3402dc40b7cf068c440169bd7ba06dcb1ed"
19
  }
 
1
  {
2
+ "src/generated-bootstrap.ts": "2c1ebd40196256d590417568ff08bc883e2d65c9663ef649f3665a502c77b76c",
3
  "src/generated-search-models.ts": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3",
4
+ "src/generated/E.ts": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983",
5
  "src/generated/Q.ts": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f",
6
+ "src/generated/models/Customer.ts": "0169ad722f34c8a9e5a30eab390ed4bd83a84c46fe4410d7178cf136edb0e28a",
7
+ "src/generated/models/CustomerOrder.ts": "0510b3ce7c628bae67699d37e35e758882b6c4fa718c4f4a527dba80b055758c",
8
+ "src/generated/models/OrderItem.ts": "4363421c144d79ca76fd11fbe11115186f3193e19b8bffd1671b92817e4e8f64",
9
+ "src/generated/models/OrderStatus.ts": "a9e0b751597f2e8ba881184d397679a9fc3968ef34efbab5158796e7e335a04e",
10
+ "src/generated/models/Platform.ts": "f8107a5bac9a98bb867f89c1c80969b9c3e978b5b28291722c0be8c558a11415",
11
+ "src/generated/requests/CustomerOrderRequest.ts": "5090c29d8a539b08f3abbf2bcff98f5aa354240c990df4f89c28d06e96285244",
12
+ "src/generated/requests/CustomerRequest.ts": "5b8bd3ec2b080a3134e2f53a8ac8392b1307dec49f6acea42b4377931697f4bf",
13
+ "src/generated/requests/OrderItemRequest.ts": "4a40a7eb45166b69110af8413c0ad5353acff1cc7b927444fba117a72598db9b",
14
+ "src/generated/requests/OrderStatusRequest.ts": "fa9c36b305a410b16cd87f84a3932efb425f53fe6537f447d15824f39d186b77",
15
+ "src/generated/requests/PlatformRequest.ts": "77760c1213a1012c98601dfced364ecf5fa5636e8f04a0186150fe7744cbcc22",
16
+ "src/runtime-module.ts": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b",
17
+ "src/teaql-schemas.ts": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3",
18
+ "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814"
19
  }
source/teaql-ts/examples/browser-sqlite/index.html CHANGED
@@ -93,6 +93,63 @@
93
  </nav>
94
  </section>
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  <section class="runtime-bar" aria-label="Runtime settings">
97
  <p id="status" role="status">Starting SQLite/WASM…</p>
98
  <div class="controls">
 
93
  </nav>
94
  </section>
95
 
96
+ <section class="development-process" aria-labelledby="development-process-title">
97
+ <div class="development-process-heading">
98
+ <div>
99
+ <p class="section-index" data-i18n="developmentProcess">00 / DEVELOPMENT PROCESS</p>
100
+ <h2 id="development-process-title" data-i18n="developmentProcessTitle">From one domain model to executable evidence.</h2>
101
+ </div>
102
+ <div class="development-process-intro">
103
+ <p data-i18n="developmentProcessIntro">TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.</p>
104
+ <div class="development-process-links">
105
+ <a class="source-link source-link-primary" href="https://github.com/teaql/teaql-ts/blob/main/examples/browser-sqlite/order-model.xml" target="_blank" rel="noreferrer">
106
+ <span data-i18n="modelSource">MODEL SOURCE</span>
107
+ <strong data-i18n="viewOrderModel">View order-model.xml</strong>
108
+ </a>
109
+ <a class="source-link" href="https://github.com/teaql/teaql-ts/tree/main/examples/browser-sqlite/assist" target="_blank" rel="noreferrer">
110
+ <span data-i18n="scopedGuidance">SCOPED GUIDANCE</span>
111
+ <strong data-i18n="viewModelAssist">View model-aware Assist</strong>
112
+ </a>
113
+ </div>
114
+ </div>
115
+ </div>
116
+
117
+ <ol class="development-process-flow">
118
+ <li>
119
+ <span class="development-step">01</span>
120
+ <strong data-i18n="processModelTitle">Model the domain</strong>
121
+ <p data-i18n="processModelBody">Define entities, fields, relationships, constant objects, and constraints in one model file.</p>
122
+ <code>order-model.xml</code>
123
+ </li>
124
+ <li>
125
+ <span class="development-step">02</span>
126
+ <strong data-i18n="processGenerateTitle">Generate the working surface</strong>
127
+ <p data-i18n="processGenerateBody">Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.</p>
128
+ <code>Q · E · Schema · Assist</code>
129
+ </li>
130
+ <li>
131
+ <span class="development-step">03</span>
132
+ <strong data-i18n="processQueryTitle">Build one bounded Q request</strong>
133
+ <p data-i18n="processQueryBody">Application code selects only what the page needs and attaches a readable comment and purpose.</p>
134
+ <code>comment · purpose · execute</code>
135
+ </li>
136
+ <li>
137
+ <span class="development-step">04</span>
138
+ <strong data-i18n="processEvidenceTitle">Run and retain evidence</strong>
139
+ <p data-i18n="processEvidenceBody">The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.</p>
140
+ <code>Result · TraceChain · SQL</code>
141
+ </li>
142
+ </ol>
143
+
144
+ <div class="context-efficiency">
145
+ <div>
146
+ <p class="section-index" data-i18n="contextEfficiency">CONTEXT EFFICIENCY</p>
147
+ <h3 data-i18n="contextEfficiencyTitle">Spend context on the business change.</h3>
148
+ </div>
149
+ <p data-i18n="contextEfficiencyBody">Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.</p>
150
+ </div>
151
+ </section>
152
+
153
  <section class="runtime-bar" aria-label="Runtime settings">
154
  <p id="status" role="status">Starting SQLite/WASM…</p>
155
  <div class="controls">
source/teaql-ts/examples/browser-sqlite/orders-lib/current-generator-fixture.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "teaql.typescript-current-example-fixture/v1",
3
+ "modelSha256": "44d20c0d236de9c79f767054deba773e11aa6ae4eaed1ede98cf7c6ed8d18495",
4
+ "scope": "typescript-lib-core",
5
+ "producerReceiptSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d",
6
+ "producerSource": {
7
+ "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08",
8
+ "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937"
9
+ },
10
+ "files": {
11
+ "src/generated/Q.ts": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f",
12
+ "src/generated/requests/PlatformRequest.ts": "77760c1213a1012c98601dfced364ecf5fa5636e8f04a0186150fe7744cbcc22",
13
+ "src/generated/requests/OrderStatusRequest.ts": "fa9c36b305a410b16cd87f84a3932efb425f53fe6537f447d15824f39d186b77",
14
+ "src/generated/requests/CustomerRequest.ts": "5b8bd3ec2b080a3134e2f53a8ac8392b1307dec49f6acea42b4377931697f4bf",
15
+ "src/generated/requests/CustomerOrderRequest.ts": "5090c29d8a539b08f3abbf2bcff98f5aa354240c990df4f89c28d06e96285244",
16
+ "src/generated/requests/OrderItemRequest.ts": "4a40a7eb45166b69110af8413c0ad5353acff1cc7b927444fba117a72598db9b",
17
+ "src/generated/E.ts": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983",
18
+ "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814",
19
+ "src/generated-search-models.ts": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3",
20
+ "src/teaql-schemas.ts": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3",
21
+ "src/runtime-module.ts": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b",
22
+ "src/generated-bootstrap.ts": "2c1ebd40196256d590417568ff08bc883e2d65c9663ef649f3665a502c77b76c",
23
+ "src/generated/models/Platform.ts": "f8107a5bac9a98bb867f89c1c80969b9c3e978b5b28291722c0be8c558a11415",
24
+ "src/generated/models/OrderStatus.ts": "a9e0b751597f2e8ba881184d397679a9fc3968ef34efbab5158796e7e335a04e",
25
+ "src/generated/models/Customer.ts": "0169ad722f34c8a9e5a30eab390ed4bd83a84c46fe4410d7178cf136edb0e28a",
26
+ "src/generated/models/CustomerOrder.ts": "0510b3ce7c628bae67699d37e35e758882b6c4fa718c4f4a527dba80b055758c",
27
+ "src/generated/models/OrderItem.ts": "4363421c144d79ca76fd11fbe11115186f3193e19b8bffd1671b92817e4e8f64"
28
+ },
29
+ "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709",
30
+ "previousFixtureManifestSha256": "8faee6961c8802d2952be9d228012ac260843234301260b798917428ad09dfb7",
31
+ "previousSourceGuard": {
32
+ "accepted": true,
33
+ "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29",
34
+ "differences": []
35
+ }
36
+ }
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { UserContext } from './teaql-ts';
2
  import { Q } from './generated/Q';
3
  import { Platform } from './generated/models/Platform';
4
  import { OrderStatus } from './generated/models/OrderStatus';
@@ -7,14 +7,14 @@ import { OrderStatus } from './generated/models/OrderStatus';
7
  export async function ensureGeneratedBootstrap(context: UserContext): Promise<void> {
8
  let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
9
  if (!domainRoot) {
10
- domainRoot = Platform.teaqlBootstrapNew('1');
11
  domainRoot.updateName("Commerce Test Platform");
12
  await domainRoot.auditAs('create generated Domain Root Platform').save(context);
13
  }
14
  context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! });
15
  let constantOrderStatus1001 = (await Q.orderStatuses().withIdIs("1001").comment('what: locate generated constant OrderStatus(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
16
  if (!constantOrderStatus1001) {
17
- constantOrderStatus1001 = OrderStatus.teaqlBootstrapNew("1001");
18
  constantOrderStatus1001.updatePlatform(domainRoot);
19
  constantOrderStatus1001.updateName("New");
20
  constantOrderStatus1001.updateCode("NEW");
@@ -32,7 +32,7 @@ export async function ensureGeneratedBootstrap(context: UserContext): Promise<vo
32
  }
33
  let constantOrderStatus1002 = (await Q.orderStatuses().withIdIs("1002").comment('what: locate generated constant OrderStatus(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
34
  if (!constantOrderStatus1002) {
35
- constantOrderStatus1002 = OrderStatus.teaqlBootstrapNew("1002");
36
  constantOrderStatus1002.updatePlatform(domainRoot);
37
  constantOrderStatus1002.updateName("Paid");
38
  constantOrderStatus1002.updateCode("PAID");
@@ -50,7 +50,7 @@ export async function ensureGeneratedBootstrap(context: UserContext): Promise<vo
50
  }
51
  let constantOrderStatus1003 = (await Q.orderStatuses().withIdIs("1003").comment('what: locate generated constant OrderStatus(1003)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
52
  if (!constantOrderStatus1003) {
53
- constantOrderStatus1003 = OrderStatus.teaqlBootstrapNew("1003");
54
  constantOrderStatus1003.updatePlatform(domainRoot);
55
  constantOrderStatus1003.updateName("Cancelled");
56
  constantOrderStatus1003.updateCode("CANCELLED");
 
1
+ import { UserContext, decimal, long, localTime } from './teaql-ts';
2
  import { Q } from './generated/Q';
3
  import { Platform } from './generated/models/Platform';
4
  import { OrderStatus } from './generated/models/OrderStatus';
 
7
  export async function ensureGeneratedBootstrap(context: UserContext): Promise<void> {
8
  let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
9
  if (!domainRoot) {
10
+ domainRoot = Platform.teaqlBootstrapNew(context, '1');
11
  domainRoot.updateName("Commerce Test Platform");
12
  await domainRoot.auditAs('create generated Domain Root Platform').save(context);
13
  }
14
  context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! });
15
  let constantOrderStatus1001 = (await Q.orderStatuses().withIdIs("1001").comment('what: locate generated constant OrderStatus(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
16
  if (!constantOrderStatus1001) {
17
+ constantOrderStatus1001 = OrderStatus.teaqlBootstrapNew(context, "1001");
18
  constantOrderStatus1001.updatePlatform(domainRoot);
19
  constantOrderStatus1001.updateName("New");
20
  constantOrderStatus1001.updateCode("NEW");
 
32
  }
33
  let constantOrderStatus1002 = (await Q.orderStatuses().withIdIs("1002").comment('what: locate generated constant OrderStatus(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
34
  if (!constantOrderStatus1002) {
35
+ constantOrderStatus1002 = OrderStatus.teaqlBootstrapNew(context, "1002");
36
  constantOrderStatus1002.updatePlatform(domainRoot);
37
  constantOrderStatus1002.updateName("Paid");
38
  constantOrderStatus1002.updateCode("PAID");
 
50
  }
51
  let constantOrderStatus1003 = (await Q.orderStatuses().withIdIs("1003").comment('what: locate generated constant OrderStatus(1003)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
52
  if (!constantOrderStatus1003) {
53
+ constantOrderStatus1003 = OrderStatus.teaqlBootstrapNew(context, "1003");
54
  constantOrderStatus1003.updatePlatform(domainRoot);
55
  constantOrderStatus1003.updateName("Cancelled");
56
  constantOrderStatus1003.updateCode("CANCELLED");
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/E.ts CHANGED
@@ -1,43 +1,18 @@
 
1
  import { Platform } from './models/Platform';
2
  import { OrderStatus } from './models/OrderStatus';
3
  import { Customer } from './models/Customer';
4
  import { CustomerOrder } from './models/CustomerOrder';
5
  import { OrderItem } from './models/OrderItem';
6
-
7
- export class TeaQLNotLoadedError extends Error {
8
- readonly details: Record<string, unknown>;
9
-
10
- constructor(
11
- readonly root: string,
12
- readonly accessPath: string,
13
- readonly breakPoint: string,
14
- ) {
15
- const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`;
16
- const details = {
17
- error: 'TeaQLNotLoadedError',
18
- root,
19
- accessPath: accessPath.split('.'),
20
- breakPoint,
21
- missingPreload: [breakPoint],
22
- suggestedFix,
23
- severity: 'error',
24
- humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`,
25
- };
26
- super(JSON.stringify(details));
27
- this.name = 'TeaQLNotLoadedError';
28
- this.details = details;
29
- }
30
- }
31
-
32
- function expressionPath(prefix: string, field: string): string {
33
- return prefix ? `${prefix}.${field}` : field;
34
- }
35
 
36
  export class ValueExpression<T> {
37
  constructor(
38
  private readonly value: T | null | undefined,
39
  private readonly present = true,
40
  private readonly notLoaded?: TeaQLNotLoadedError,
 
41
  ) {}
42
 
43
  static missing<T>(): ValueExpression<T> {
@@ -48,18 +23,26 @@ export class ValueExpression<T> {
48
  return new ValueExpression<T>(undefined, false, error);
49
  }
50
 
 
 
 
 
51
  eval(): T | null | undefined {
52
- if (this.notLoaded) throw this.notLoaded;
 
53
  return this.present ? this.value : undefined;
54
  }
55
 
56
  isPresent(): boolean {
57
- if (this.notLoaded) throw this.notLoaded;
 
58
  return this.present;
59
  }
60
 
61
  orElse(fallback: T): T {
62
- const value = this.eval();
 
 
63
  return this.present && value != null ? value : fallback;
64
  }
65
  }
@@ -68,62 +51,62 @@ export class PlatformExpression {
68
  constructor(
69
  private readonly value: Platform | null | undefined,
70
  private readonly root = 'Platform(null)',
71
- private readonly path = '',
72
  private readonly notLoaded?: TeaQLNotLoadedError,
73
  ) {}
74
 
75
  eval(): Platform | null | undefined {
76
- if (this.notLoaded) throw this.notLoaded;
77
  return this.value;
78
  }
79
 
80
  id(): ValueExpression<string> {
81
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
82
  if (!this.value) return ValueExpression.missing<string>();
83
- const path = expressionPath(this.path, 'id');
84
  if (!this.value.isLoaded('id')) {
85
  return ValueExpression.notLoaded<string>(
86
- new TeaQLNotLoadedError(this.root, path, 'id'),
87
  );
88
  }
89
  return new ValueExpression<string>(this.value.id);
90
  }
91
 
92
  name(): ValueExpression<string> {
93
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
94
  if (!this.value) return ValueExpression.missing<string>();
95
- const path = expressionPath(this.path, 'name');
96
  if (!this.value.isLoaded('name')) {
97
  return ValueExpression.notLoaded<string>(
98
- new TeaQLNotLoadedError(this.root, path, 'name'),
99
  );
100
  }
101
  return new ValueExpression<string>(this.value.name);
102
  }
103
 
104
- version(): ValueExpression<number> {
105
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
106
- if (!this.value) return ValueExpression.missing<number>();
107
- const path = expressionPath(this.path, 'version');
108
  if (!this.value.isLoaded('version')) {
109
- return ValueExpression.notLoaded<number>(
110
- new TeaQLNotLoadedError(this.root, path, 'version'),
111
  );
112
  }
113
- return new ValueExpression<number>(this.value.version);
114
  }
115
 
116
 
117
 
118
  orderStatusList(): OrderStatusListExpression {
119
- const path = expressionPath(this.path, 'orderStatusList');
120
  if (this.notLoaded) {
121
- return new OrderStatusListExpression([], this.root, path, false, this.notLoaded);
122
  }
123
  if (!this.value) return OrderStatusListExpression.missing(this.root, path);
124
  if (!this.value.isLoaded('orderStatusList')) {
125
  return new OrderStatusListExpression([], this.root, path, false,
126
- new TeaQLNotLoadedError(this.root, path, 'orderStatusList'));
127
  }
128
  return new OrderStatusListExpression(
129
  this.value.orderStatusList(), this.root, path,
@@ -131,14 +114,14 @@ export class PlatformExpression {
131
  }
132
 
133
  customerList(): CustomerListExpression {
134
- const path = expressionPath(this.path, 'customerList');
135
  if (this.notLoaded) {
136
- return new CustomerListExpression([], this.root, path, false, this.notLoaded);
137
  }
138
  if (!this.value) return CustomerListExpression.missing(this.root, path);
139
  if (!this.value.isLoaded('customerList')) {
140
  return new CustomerListExpression([], this.root, path, false,
141
- new TeaQLNotLoadedError(this.root, path, 'customerList'));
142
  }
143
  return new CustomerListExpression(
144
  this.value.customerList(), this.root, path,
@@ -150,94 +133,96 @@ export class OrderStatusExpression {
150
  constructor(
151
  private readonly value: OrderStatus | null | undefined,
152
  private readonly root = 'OrderStatus(null)',
153
- private readonly path = '',
154
  private readonly notLoaded?: TeaQLNotLoadedError,
155
  ) {}
156
 
157
  eval(): OrderStatus | null | undefined {
158
- if (this.notLoaded) throw this.notLoaded;
159
  return this.value;
160
  }
161
 
162
  id(): ValueExpression<string> {
163
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
164
  if (!this.value) return ValueExpression.missing<string>();
165
- const path = expressionPath(this.path, 'id');
166
  if (!this.value.isLoaded('id')) {
167
  return ValueExpression.notLoaded<string>(
168
- new TeaQLNotLoadedError(this.root, path, 'id'),
169
  );
170
  }
171
  return new ValueExpression<string>(this.value.id);
172
  }
173
 
174
  name(): ValueExpression<string> {
175
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
176
  if (!this.value) return ValueExpression.missing<string>();
177
- const path = expressionPath(this.path, 'name');
178
  if (!this.value.isLoaded('name')) {
179
  return ValueExpression.notLoaded<string>(
180
- new TeaQLNotLoadedError(this.root, path, 'name'),
181
  );
182
  }
183
  return new ValueExpression<string>(this.value.name);
184
  }
185
 
186
  code(): ValueExpression<string> {
187
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
188
  if (!this.value) return ValueExpression.missing<string>();
189
- const path = expressionPath(this.path, 'code');
190
  if (!this.value.isLoaded('code')) {
191
  return ValueExpression.notLoaded<string>(
192
- new TeaQLNotLoadedError(this.root, path, 'code'),
193
  );
194
  }
195
  return new ValueExpression<string>(this.value.code);
196
  }
197
 
198
  color(): ValueExpression<string> {
199
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
200
  if (!this.value) return ValueExpression.missing<string>();
201
- const path = expressionPath(this.path, 'color');
202
  if (!this.value.isLoaded('color')) {
203
  return ValueExpression.notLoaded<string>(
204
- new TeaQLNotLoadedError(this.root, path, 'color'),
205
  );
206
  }
207
  return new ValueExpression<string>(this.value.color);
208
  }
209
 
210
  displayOrder(): ValueExpression<number> {
211
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
 
212
  if (!this.value) return ValueExpression.missing<number>();
213
- const path = expressionPath(this.path, 'displayOrder');
214
  if (!this.value.isLoaded('displayOrder')) {
215
  return ValueExpression.notLoaded<number>(
216
- new TeaQLNotLoadedError(this.root, path, 'displayOrder'),
217
  );
218
  }
 
 
219
  return new ValueExpression<number>(this.value.displayOrder);
220
  }
221
 
222
- version(): ValueExpression<number> {
223
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
224
- if (!this.value) return ValueExpression.missing<number>();
225
- const path = expressionPath(this.path, 'version');
226
  if (!this.value.isLoaded('version')) {
227
- return ValueExpression.notLoaded<number>(
228
- new TeaQLNotLoadedError(this.root, path, 'version'),
229
  );
230
  }
231
- return new ValueExpression<number>(this.value.version);
232
  }
233
 
234
  platformId(): ValueExpression<string | number> {
235
- if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
 
236
  if (!this.value) return ValueExpression.missing<string | number>();
237
- const path = expressionPath(this.path, 'platform');
238
  if (!this.value.isLoaded('platform')) {
239
  return ValueExpression.notLoaded<string | number>(
240
- new TeaQLNotLoadedError(this.root, path, 'platform'),
241
  );
242
  }
243
  const reference = this.value.platform;
@@ -248,33 +233,35 @@ export class OrderStatusExpression {
248
  }
249
 
250
  platform(): PlatformExpression {
251
- const path = expressionPath(this.path, 'platform');
252
  if (this.notLoaded) {
253
- return new PlatformExpression(undefined, this.root, path, this.notLoaded);
254
  }
255
  if (!this.value) return new PlatformExpression(undefined, this.root, path);
256
  if (!this.value.isLoaded('platform')) {
257
  return new PlatformExpression(undefined, this.root, path,
258
- new TeaQLNotLoadedError(this.root, path, 'platform'));
259
  }
260
  const relation = this.value.platform;
261
- const target = relation == null
262
- ? undefined
263
- : relation instanceof Platform
264
- ? relation
265
- : Platform.fromRecord({ id: relation });
 
 
266
  return new PlatformExpression(target, this.root, path);
267
  }
268
 
269
  customerOrderList(): CustomerOrderListExpression {
270
- const path = expressionPath(this.path, 'customerOrderList');
271
  if (this.notLoaded) {
272
- return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded);
273
  }
274
  if (!this.value) return CustomerOrderListExpression.missing(this.root, path);
275
  if (!this.value.isLoaded('customerOrderList')) {
276
  return new CustomerOrderListExpression([], this.root, path, false,
277
- new TeaQLNotLoadedError(this.root, path, 'customerOrderList'));
278
  }
279
  return new CustomerOrderListExpression(
280
  this.value.customerOrderList(), this.root, path,
@@ -286,58 +273,58 @@ export class CustomerExpression {
286
  constructor(
287
  private readonly value: Customer | null | undefined,
288
  private readonly root = 'Customer(null)',
289
- private readonly path = '',
290
  private readonly notLoaded?: TeaQLNotLoadedError,
291
  ) {}
292
 
293
  eval(): Customer | null | undefined {
294
- if (this.notLoaded) throw this.notLoaded;
295
  return this.value;
296
  }
297
 
298
  id(): ValueExpression<string> {
299
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
300
  if (!this.value) return ValueExpression.missing<string>();
301
- const path = expressionPath(this.path, 'id');
302
  if (!this.value.isLoaded('id')) {
303
  return ValueExpression.notLoaded<string>(
304
- new TeaQLNotLoadedError(this.root, path, 'id'),
305
  );
306
  }
307
  return new ValueExpression<string>(this.value.id);
308
  }
309
 
310
  name(): ValueExpression<string> {
311
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
312
  if (!this.value) return ValueExpression.missing<string>();
313
- const path = expressionPath(this.path, 'name');
314
  if (!this.value.isLoaded('name')) {
315
  return ValueExpression.notLoaded<string>(
316
- new TeaQLNotLoadedError(this.root, path, 'name'),
317
  );
318
  }
319
  return new ValueExpression<string>(this.value.name);
320
  }
321
 
322
- version(): ValueExpression<number> {
323
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
324
- if (!this.value) return ValueExpression.missing<number>();
325
- const path = expressionPath(this.path, 'version');
326
  if (!this.value.isLoaded('version')) {
327
- return ValueExpression.notLoaded<number>(
328
- new TeaQLNotLoadedError(this.root, path, 'version'),
329
  );
330
  }
331
- return new ValueExpression<number>(this.value.version);
332
  }
333
 
334
  platformId(): ValueExpression<string | number> {
335
- if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
 
336
  if (!this.value) return ValueExpression.missing<string | number>();
337
- const path = expressionPath(this.path, 'platform');
338
  if (!this.value.isLoaded('platform')) {
339
  return ValueExpression.notLoaded<string | number>(
340
- new TeaQLNotLoadedError(this.root, path, 'platform'),
341
  );
342
  }
343
  const reference = this.value.platform;
@@ -348,33 +335,35 @@ export class CustomerExpression {
348
  }
349
 
350
  platform(): PlatformExpression {
351
- const path = expressionPath(this.path, 'platform');
352
  if (this.notLoaded) {
353
- return new PlatformExpression(undefined, this.root, path, this.notLoaded);
354
  }
355
  if (!this.value) return new PlatformExpression(undefined, this.root, path);
356
  if (!this.value.isLoaded('platform')) {
357
  return new PlatformExpression(undefined, this.root, path,
358
- new TeaQLNotLoadedError(this.root, path, 'platform'));
359
  }
360
  const relation = this.value.platform;
361
- const target = relation == null
362
- ? undefined
363
- : relation instanceof Platform
364
- ? relation
365
- : Platform.fromRecord({ id: relation });
 
 
366
  return new PlatformExpression(target, this.root, path);
367
  }
368
 
369
  customerOrderList(): CustomerOrderListExpression {
370
- const path = expressionPath(this.path, 'customerOrderList');
371
  if (this.notLoaded) {
372
- return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded);
373
  }
374
  if (!this.value) return CustomerOrderListExpression.missing(this.root, path);
375
  if (!this.value.isLoaded('customerOrderList')) {
376
  return new CustomerOrderListExpression([], this.root, path, false,
377
- new TeaQLNotLoadedError(this.root, path, 'customerOrderList'));
378
  }
379
  return new CustomerOrderListExpression(
380
  this.value.customerOrderList(), this.root, path,
@@ -386,82 +375,82 @@ export class CustomerOrderExpression {
386
  constructor(
387
  private readonly value: CustomerOrder | null | undefined,
388
  private readonly root = 'CustomerOrder(null)',
389
- private readonly path = '',
390
  private readonly notLoaded?: TeaQLNotLoadedError,
391
  ) {}
392
 
393
  eval(): CustomerOrder | null | undefined {
394
- if (this.notLoaded) throw this.notLoaded;
395
  return this.value;
396
  }
397
 
398
  id(): ValueExpression<string> {
399
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
400
  if (!this.value) return ValueExpression.missing<string>();
401
- const path = expressionPath(this.path, 'id');
402
  if (!this.value.isLoaded('id')) {
403
  return ValueExpression.notLoaded<string>(
404
- new TeaQLNotLoadedError(this.root, path, 'id'),
405
  );
406
  }
407
  return new ValueExpression<string>(this.value.id);
408
  }
409
 
410
  orderNumber(): ValueExpression<string> {
411
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
412
  if (!this.value) return ValueExpression.missing<string>();
413
- const path = expressionPath(this.path, 'orderNumber');
414
  if (!this.value.isLoaded('orderNumber')) {
415
  return ValueExpression.notLoaded<string>(
416
- new TeaQLNotLoadedError(this.root, path, 'orderNumber'),
417
  );
418
  }
419
  return new ValueExpression<string>(this.value.orderNumber);
420
  }
421
 
422
  orderDate(): ValueExpression<string> {
423
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
424
  if (!this.value) return ValueExpression.missing<string>();
425
- const path = expressionPath(this.path, 'orderDate');
426
  if (!this.value.isLoaded('orderDate')) {
427
  return ValueExpression.notLoaded<string>(
428
- new TeaQLNotLoadedError(this.root, path, 'orderDate'),
429
  );
430
  }
431
  return new ValueExpression<string>(this.value.orderDate);
432
  }
433
 
434
- totalAmount(): ValueExpression<number> {
435
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
436
- if (!this.value) return ValueExpression.missing<number>();
437
- const path = expressionPath(this.path, 'totalAmount');
438
  if (!this.value.isLoaded('totalAmount')) {
439
- return ValueExpression.notLoaded<number>(
440
- new TeaQLNotLoadedError(this.root, path, 'totalAmount'),
441
  );
442
  }
443
- return new ValueExpression<number>(this.value.totalAmount);
444
  }
445
 
446
- version(): ValueExpression<number> {
447
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
448
- if (!this.value) return ValueExpression.missing<number>();
449
- const path = expressionPath(this.path, 'version');
450
  if (!this.value.isLoaded('version')) {
451
- return ValueExpression.notLoaded<number>(
452
- new TeaQLNotLoadedError(this.root, path, 'version'),
453
  );
454
  }
455
- return new ValueExpression<number>(this.value.version);
456
  }
457
 
458
  customerId(): ValueExpression<string | number> {
459
- if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
 
460
  if (!this.value) return ValueExpression.missing<string | number>();
461
- const path = expressionPath(this.path, 'customer');
462
  if (!this.value.isLoaded('customer')) {
463
  return ValueExpression.notLoaded<string | number>(
464
- new TeaQLNotLoadedError(this.root, path, 'customer'),
465
  );
466
  }
467
  const reference = this.value.customer;
@@ -472,12 +461,12 @@ export class CustomerOrderExpression {
472
  }
473
 
474
  statusId(): ValueExpression<string | number> {
475
- if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
 
476
  if (!this.value) return ValueExpression.missing<string | number>();
477
- const path = expressionPath(this.path, 'status');
478
  if (!this.value.isLoaded('status')) {
479
  return ValueExpression.notLoaded<string | number>(
480
- new TeaQLNotLoadedError(this.root, path, 'status'),
481
  );
482
  }
483
  const reference = this.value.status;
@@ -488,52 +477,56 @@ export class CustomerOrderExpression {
488
  }
489
 
490
  customer(): CustomerExpression {
491
- const path = expressionPath(this.path, 'customer');
492
  if (this.notLoaded) {
493
- return new CustomerExpression(undefined, this.root, path, this.notLoaded);
494
  }
495
  if (!this.value) return new CustomerExpression(undefined, this.root, path);
496
  if (!this.value.isLoaded('customer')) {
497
  return new CustomerExpression(undefined, this.root, path,
498
- new TeaQLNotLoadedError(this.root, path, 'customer'));
499
  }
500
  const relation = this.value.customer;
501
- const target = relation == null
502
- ? undefined
503
- : relation instanceof Customer
504
- ? relation
505
- : Customer.fromRecord({ id: relation });
 
 
506
  return new CustomerExpression(target, this.root, path);
507
  }
508
 
509
  status(): OrderStatusExpression {
510
- const path = expressionPath(this.path, 'status');
511
  if (this.notLoaded) {
512
- return new OrderStatusExpression(undefined, this.root, path, this.notLoaded);
513
  }
514
  if (!this.value) return new OrderStatusExpression(undefined, this.root, path);
515
  if (!this.value.isLoaded('status')) {
516
  return new OrderStatusExpression(undefined, this.root, path,
517
- new TeaQLNotLoadedError(this.root, path, 'status'));
518
  }
519
  const relation = this.value.status;
520
- const target = relation == null
521
- ? undefined
522
- : relation instanceof OrderStatus
523
- ? relation
524
- : OrderStatus.fromRecord({ id: relation });
 
 
525
  return new OrderStatusExpression(target, this.root, path);
526
  }
527
 
528
  orderItemList(): OrderItemListExpression {
529
- const path = expressionPath(this.path, 'orderItemList');
530
  if (this.notLoaded) {
531
- return new OrderItemListExpression([], this.root, path, false, this.notLoaded);
532
  }
533
  if (!this.value) return OrderItemListExpression.missing(this.root, path);
534
  if (!this.value.isLoaded('orderItemList')) {
535
  return new OrderItemListExpression([], this.root, path, false,
536
- new TeaQLNotLoadedError(this.root, path, 'orderItemList'));
537
  }
538
  return new OrderItemListExpression(
539
  this.value.orderItemList(), this.root, path,
@@ -545,82 +538,84 @@ export class OrderItemExpression {
545
  constructor(
546
  private readonly value: OrderItem | null | undefined,
547
  private readonly root = 'OrderItem(null)',
548
- private readonly path = '',
549
  private readonly notLoaded?: TeaQLNotLoadedError,
550
  ) {}
551
 
552
  eval(): OrderItem | null | undefined {
553
- if (this.notLoaded) throw this.notLoaded;
554
  return this.value;
555
  }
556
 
557
  id(): ValueExpression<string> {
558
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
559
  if (!this.value) return ValueExpression.missing<string>();
560
- const path = expressionPath(this.path, 'id');
561
  if (!this.value.isLoaded('id')) {
562
  return ValueExpression.notLoaded<string>(
563
- new TeaQLNotLoadedError(this.root, path, 'id'),
564
  );
565
  }
566
  return new ValueExpression<string>(this.value.id);
567
  }
568
 
569
  productName(): ValueExpression<string> {
570
- if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
 
571
  if (!this.value) return ValueExpression.missing<string>();
572
- const path = expressionPath(this.path, 'productName');
573
  if (!this.value.isLoaded('productName')) {
574
  return ValueExpression.notLoaded<string>(
575
- new TeaQLNotLoadedError(this.root, path, 'productName'),
576
  );
577
  }
578
  return new ValueExpression<string>(this.value.productName);
579
  }
580
 
581
  quantity(): ValueExpression<number> {
582
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
 
583
  if (!this.value) return ValueExpression.missing<number>();
584
- const path = expressionPath(this.path, 'quantity');
585
  if (!this.value.isLoaded('quantity')) {
586
  return ValueExpression.notLoaded<number>(
587
- new TeaQLNotLoadedError(this.root, path, 'quantity'),
588
  );
589
  }
 
 
590
  return new ValueExpression<number>(this.value.quantity);
591
  }
592
 
593
- unitPrice(): ValueExpression<number> {
594
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
595
- if (!this.value) return ValueExpression.missing<number>();
596
- const path = expressionPath(this.path, 'unitPrice');
597
  if (!this.value.isLoaded('unitPrice')) {
598
- return ValueExpression.notLoaded<number>(
599
- new TeaQLNotLoadedError(this.root, path, 'unitPrice'),
600
  );
601
  }
602
- return new ValueExpression<number>(this.value.unitPrice);
603
  }
604
 
605
- version(): ValueExpression<number> {
606
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
607
- if (!this.value) return ValueExpression.missing<number>();
608
- const path = expressionPath(this.path, 'version');
609
  if (!this.value.isLoaded('version')) {
610
- return ValueExpression.notLoaded<number>(
611
- new TeaQLNotLoadedError(this.root, path, 'version'),
612
  );
613
  }
614
- return new ValueExpression<number>(this.value.version);
615
  }
616
 
617
  customerOrderId(): ValueExpression<string | number> {
618
- if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
 
619
  if (!this.value) return ValueExpression.missing<string | number>();
620
- const path = expressionPath(this.path, 'customerOrder');
621
  if (!this.value.isLoaded('customerOrder')) {
622
  return ValueExpression.notLoaded<string | number>(
623
- new TeaQLNotLoadedError(this.root, path, 'customerOrder'),
624
  );
625
  }
626
  const reference = this.value.customerOrder;
@@ -631,21 +626,23 @@ export class OrderItemExpression {
631
  }
632
 
633
  customerOrder(): CustomerOrderExpression {
634
- const path = expressionPath(this.path, 'customerOrder');
635
  if (this.notLoaded) {
636
- return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded);
637
  }
638
  if (!this.value) return new CustomerOrderExpression(undefined, this.root, path);
639
  if (!this.value.isLoaded('customerOrder')) {
640
  return new CustomerOrderExpression(undefined, this.root, path,
641
- new TeaQLNotLoadedError(this.root, path, 'customerOrder'));
642
  }
643
  const relation = this.value.customerOrder;
644
- const target = relation == null
645
- ? undefined
646
- : relation instanceof CustomerOrder
647
- ? relation
648
- : CustomerOrder.fromRecord({ id: relation });
 
 
649
  return new CustomerOrderExpression(target, this.root, path);
650
  }
651
 
@@ -655,30 +652,34 @@ export class PlatformListExpression {
655
  constructor(
656
  private readonly items: readonly Platform[],
657
  private readonly root = 'Platform(null)',
658
- private readonly path = '',
659
  private readonly present = true,
660
  private readonly notLoaded?: TeaQLNotLoadedError,
661
  ) {}
662
 
663
- static missing(root?: string, path = ''): PlatformListExpression {
664
  return new PlatformListExpression([], root, path, false);
665
  }
666
 
667
  size(): ValueExpression<number> {
668
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
669
  return this.present
670
  ? new ValueExpression<number>(this.items.length)
671
  : ValueExpression.missing<number>();
672
  }
673
 
674
  first(): PlatformExpression {
675
- return this.get(0);
676
  }
677
 
678
  get(index: number): PlatformExpression {
679
- const itemPath = expressionPath(this.path, `get(${index})`);
 
 
 
 
680
  if (this.notLoaded) {
681
- return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded);
682
  }
683
  return !this.present || index < 0 || index >= this.items.length
684
  ? new PlatformExpression(undefined, this.root, itemPath)
@@ -690,30 +691,34 @@ export class OrderStatusListExpression {
690
  constructor(
691
  private readonly items: readonly OrderStatus[],
692
  private readonly root = 'OrderStatus(null)',
693
- private readonly path = '',
694
  private readonly present = true,
695
  private readonly notLoaded?: TeaQLNotLoadedError,
696
  ) {}
697
 
698
- static missing(root?: string, path = ''): OrderStatusListExpression {
699
  return new OrderStatusListExpression([], root, path, false);
700
  }
701
 
702
  size(): ValueExpression<number> {
703
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
704
  return this.present
705
  ? new ValueExpression<number>(this.items.length)
706
  : ValueExpression.missing<number>();
707
  }
708
 
709
  first(): OrderStatusExpression {
710
- return this.get(0);
711
  }
712
 
713
  get(index: number): OrderStatusExpression {
714
- const itemPath = expressionPath(this.path, `get(${index})`);
 
 
 
 
715
  if (this.notLoaded) {
716
- return new OrderStatusExpression(undefined, this.root, itemPath, this.notLoaded);
717
  }
718
  return !this.present || index < 0 || index >= this.items.length
719
  ? new OrderStatusExpression(undefined, this.root, itemPath)
@@ -725,30 +730,34 @@ export class CustomerListExpression {
725
  constructor(
726
  private readonly items: readonly Customer[],
727
  private readonly root = 'Customer(null)',
728
- private readonly path = '',
729
  private readonly present = true,
730
  private readonly notLoaded?: TeaQLNotLoadedError,
731
  ) {}
732
 
733
- static missing(root?: string, path = ''): CustomerListExpression {
734
  return new CustomerListExpression([], root, path, false);
735
  }
736
 
737
  size(): ValueExpression<number> {
738
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
739
  return this.present
740
  ? new ValueExpression<number>(this.items.length)
741
  : ValueExpression.missing<number>();
742
  }
743
 
744
  first(): CustomerExpression {
745
- return this.get(0);
746
  }
747
 
748
  get(index: number): CustomerExpression {
749
- const itemPath = expressionPath(this.path, `get(${index})`);
 
 
 
 
750
  if (this.notLoaded) {
751
- return new CustomerExpression(undefined, this.root, itemPath, this.notLoaded);
752
  }
753
  return !this.present || index < 0 || index >= this.items.length
754
  ? new CustomerExpression(undefined, this.root, itemPath)
@@ -760,30 +769,34 @@ export class CustomerOrderListExpression {
760
  constructor(
761
  private readonly items: readonly CustomerOrder[],
762
  private readonly root = 'CustomerOrder(null)',
763
- private readonly path = '',
764
  private readonly present = true,
765
  private readonly notLoaded?: TeaQLNotLoadedError,
766
  ) {}
767
 
768
- static missing(root?: string, path = ''): CustomerOrderListExpression {
769
  return new CustomerOrderListExpression([], root, path, false);
770
  }
771
 
772
  size(): ValueExpression<number> {
773
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
774
  return this.present
775
  ? new ValueExpression<number>(this.items.length)
776
  : ValueExpression.missing<number>();
777
  }
778
 
779
  first(): CustomerOrderExpression {
780
- return this.get(0);
781
  }
782
 
783
  get(index: number): CustomerOrderExpression {
784
- const itemPath = expressionPath(this.path, `get(${index})`);
 
 
 
 
785
  if (this.notLoaded) {
786
- return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded);
787
  }
788
  return !this.present || index < 0 || index >= this.items.length
789
  ? new CustomerOrderExpression(undefined, this.root, itemPath)
@@ -795,30 +808,34 @@ export class OrderItemListExpression {
795
  constructor(
796
  private readonly items: readonly OrderItem[],
797
  private readonly root = 'OrderItem(null)',
798
- private readonly path = '',
799
  private readonly present = true,
800
  private readonly notLoaded?: TeaQLNotLoadedError,
801
  ) {}
802
 
803
- static missing(root?: string, path = ''): OrderItemListExpression {
804
  return new OrderItemListExpression([], root, path, false);
805
  }
806
 
807
  size(): ValueExpression<number> {
808
- if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
809
  return this.present
810
  ? new ValueExpression<number>(this.items.length)
811
  : ValueExpression.missing<number>();
812
  }
813
 
814
  first(): OrderItemExpression {
815
- return this.get(0);
816
  }
817
 
818
  get(index: number): OrderItemExpression {
819
- const itemPath = expressionPath(this.path, `get(${index})`);
 
 
 
 
820
  if (this.notLoaded) {
821
- return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded);
822
  }
823
  return !this.present || index < 0 || index >= this.items.length
824
  ? new OrderItemExpression(undefined, this.root, itemPath)
@@ -831,7 +848,7 @@ export class E {
831
  value: Platform | null | undefined,
832
  ): PlatformExpression {
833
  return new PlatformExpression(
834
- value, `Platform(id=${value?.id ?? 'null'})`,
835
  );
836
  }
837
 
@@ -839,7 +856,7 @@ export class E {
839
  value: OrderStatus | null | undefined,
840
  ): OrderStatusExpression {
841
  return new OrderStatusExpression(
842
- value, `OrderStatus(id=${value?.id ?? 'null'})`,
843
  );
844
  }
845
 
@@ -847,7 +864,7 @@ export class E {
847
  value: Customer | null | undefined,
848
  ): CustomerExpression {
849
  return new CustomerExpression(
850
- value, `Customer(id=${value?.id ?? 'null'})`,
851
  );
852
  }
853
 
@@ -855,7 +872,7 @@ export class E {
855
  value: CustomerOrder | null | undefined,
856
  ): CustomerOrderExpression {
857
  return new CustomerOrderExpression(
858
- value, `CustomerOrder(id=${value?.id ?? 'null'})`,
859
  );
860
  }
861
 
@@ -863,7 +880,7 @@ export class E {
863
  value: OrderItem | null | undefined,
864
  ): OrderItemExpression {
865
  return new OrderItemExpression(
866
- value, `OrderItem(id=${value?.id ?? 'null'})`,
867
  );
868
  }
869
  }
 
1
+ import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts';
2
  import { Platform } from './models/Platform';
3
  import { OrderStatus } from './models/OrderStatus';
4
  import { Customer } from './models/Customer';
5
  import { CustomerOrder } from './models/CustomerOrder';
6
  import { OrderItem } from './models/OrderItem';
7
+ import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts';
8
+ export { TeaQLNotLoadedError } from '../teaql-ts';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  export class ValueExpression<T> {
11
  constructor(
12
  private readonly value: T | null | undefined,
13
  private readonly present = true,
14
  private readonly notLoaded?: TeaQLNotLoadedError,
15
+ private readonly invalidValue?: CheckException,
16
  ) {}
17
 
18
  static missing<T>(): ValueExpression<T> {
 
23
  return new ValueExpression<T>(undefined, false, error);
24
  }
25
 
26
+ static invalid<T>(error: CheckException): ValueExpression<T> {
27
+ return new ValueExpression<T>(undefined, false, undefined, error);
28
+ }
29
+
30
  eval(): T | null | undefined {
31
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
32
+ if (this.invalidValue) throw this.invalidValue;
33
  return this.present ? this.value : undefined;
34
  }
35
 
36
  isPresent(): boolean {
37
+ if (this.notLoaded) throw this.notLoaded.terminal('isPresent()');
38
+ if (this.invalidValue) throw this.invalidValue;
39
  return this.present;
40
  }
41
 
42
  orElse(fallback: T): T {
43
+ if (this.notLoaded) throw this.notLoaded.terminal('orElse(<fallback>)');
44
+ if (this.invalidValue) throw this.invalidValue;
45
+ const value = this.value;
46
  return this.present && value != null ? value : fallback;
47
  }
48
  }
 
51
  constructor(
52
  private readonly value: Platform | null | undefined,
53
  private readonly root = 'Platform(null)',
54
+ private readonly path = ExpressionPath.root('E.platform(<root>)', 'camelCase'),
55
  private readonly notLoaded?: TeaQLNotLoadedError,
56
  ) {}
57
 
58
  eval(): Platform | null | undefined {
59
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
60
  return this.value;
61
  }
62
 
63
  id(): ValueExpression<string> {
64
+ const path = this.path.member('id', 'id');
65
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
66
  if (!this.value) return ValueExpression.missing<string>();
 
67
  if (!this.value.isLoaded('id')) {
68
  return ValueExpression.notLoaded<string>(
69
+ new TeaQLNotLoadedError(path.markMissing(), 'id'),
70
  );
71
  }
72
  return new ValueExpression<string>(this.value.id);
73
  }
74
 
75
  name(): ValueExpression<string> {
76
+ const path = this.path.member('name', 'name');
77
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
78
  if (!this.value) return ValueExpression.missing<string>();
 
79
  if (!this.value.isLoaded('name')) {
80
  return ValueExpression.notLoaded<string>(
81
+ new TeaQLNotLoadedError(path.markMissing(), 'name'),
82
  );
83
  }
84
  return new ValueExpression<string>(this.value.name);
85
  }
86
 
87
+ version(): ValueExpression<EntityVersion> {
88
+ const path = this.path.member('version', 'version');
89
+ if (this.notLoaded) return ValueExpression.notLoaded<EntityVersion>(this.notLoaded.withPath(path));
90
+ if (!this.value) return ValueExpression.missing<EntityVersion>();
91
  if (!this.value.isLoaded('version')) {
92
+ return ValueExpression.notLoaded<EntityVersion>(
93
+ new TeaQLNotLoadedError(path.markMissing(), 'version'),
94
  );
95
  }
96
+ return new ValueExpression<EntityVersion>(this.value.version);
97
  }
98
 
99
 
100
 
101
  orderStatusList(): OrderStatusListExpression {
102
+ const path = this.path.member('order_status_list', 'orderStatusList');
103
  if (this.notLoaded) {
104
+ return new OrderStatusListExpression([], this.root, path, false, this.notLoaded.withPath(path));
105
  }
106
  if (!this.value) return OrderStatusListExpression.missing(this.root, path);
107
  if (!this.value.isLoaded('orderStatusList')) {
108
  return new OrderStatusListExpression([], this.root, path, false,
109
+ new TeaQLNotLoadedError(path.markMissing(), 'order_status_list'));
110
  }
111
  return new OrderStatusListExpression(
112
  this.value.orderStatusList(), this.root, path,
 
114
  }
115
 
116
  customerList(): CustomerListExpression {
117
+ const path = this.path.member('customer_list', 'customerList');
118
  if (this.notLoaded) {
119
+ return new CustomerListExpression([], this.root, path, false, this.notLoaded.withPath(path));
120
  }
121
  if (!this.value) return CustomerListExpression.missing(this.root, path);
122
  if (!this.value.isLoaded('customerList')) {
123
  return new CustomerListExpression([], this.root, path, false,
124
+ new TeaQLNotLoadedError(path.markMissing(), 'customer_list'));
125
  }
126
  return new CustomerListExpression(
127
  this.value.customerList(), this.root, path,
 
133
  constructor(
134
  private readonly value: OrderStatus | null | undefined,
135
  private readonly root = 'OrderStatus(null)',
136
+ private readonly path = ExpressionPath.root('E.orderStatus(<root>)', 'camelCase'),
137
  private readonly notLoaded?: TeaQLNotLoadedError,
138
  ) {}
139
 
140
  eval(): OrderStatus | null | undefined {
141
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
142
  return this.value;
143
  }
144
 
145
  id(): ValueExpression<string> {
146
+ const path = this.path.member('id', 'id');
147
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
148
  if (!this.value) return ValueExpression.missing<string>();
 
149
  if (!this.value.isLoaded('id')) {
150
  return ValueExpression.notLoaded<string>(
151
+ new TeaQLNotLoadedError(path.markMissing(), 'id'),
152
  );
153
  }
154
  return new ValueExpression<string>(this.value.id);
155
  }
156
 
157
  name(): ValueExpression<string> {
158
+ const path = this.path.member('name', 'name');
159
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
160
  if (!this.value) return ValueExpression.missing<string>();
 
161
  if (!this.value.isLoaded('name')) {
162
  return ValueExpression.notLoaded<string>(
163
+ new TeaQLNotLoadedError(path.markMissing(), 'name'),
164
  );
165
  }
166
  return new ValueExpression<string>(this.value.name);
167
  }
168
 
169
  code(): ValueExpression<string> {
170
+ const path = this.path.member('code', 'code');
171
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
172
  if (!this.value) return ValueExpression.missing<string>();
 
173
  if (!this.value.isLoaded('code')) {
174
  return ValueExpression.notLoaded<string>(
175
+ new TeaQLNotLoadedError(path.markMissing(), 'code'),
176
  );
177
  }
178
  return new ValueExpression<string>(this.value.code);
179
  }
180
 
181
  color(): ValueExpression<string> {
182
+ const path = this.path.member('color', 'color');
183
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
184
  if (!this.value) return ValueExpression.missing<string>();
 
185
  if (!this.value.isLoaded('color')) {
186
  return ValueExpression.notLoaded<string>(
187
+ new TeaQLNotLoadedError(path.markMissing(), 'color'),
188
  );
189
  }
190
  return new ValueExpression<string>(this.value.color);
191
  }
192
 
193
  displayOrder(): ValueExpression<number> {
194
+ const path = this.path.member('display_order', 'displayOrder');
195
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(path));
196
  if (!this.value) return ValueExpression.missing<number>();
 
197
  if (!this.value.isLoaded('displayOrder')) {
198
  return ValueExpression.notLoaded<number>(
199
+ new TeaQLNotLoadedError(path.markMissing(), 'display_order'),
200
  );
201
  }
202
+ const error = integer32Error(this.value.displayOrder, 'OrderStatus', 'display_order');
203
+ if (error) return ValueExpression.invalid<number>(error);
204
  return new ValueExpression<number>(this.value.displayOrder);
205
  }
206
 
207
+ version(): ValueExpression<EntityVersion> {
208
+ const path = this.path.member('version', 'version');
209
+ if (this.notLoaded) return ValueExpression.notLoaded<EntityVersion>(this.notLoaded.withPath(path));
210
+ if (!this.value) return ValueExpression.missing<EntityVersion>();
211
  if (!this.value.isLoaded('version')) {
212
+ return ValueExpression.notLoaded<EntityVersion>(
213
+ new TeaQLNotLoadedError(path.markMissing(), 'version'),
214
  );
215
  }
216
+ return new ValueExpression<EntityVersion>(this.value.version);
217
  }
218
 
219
  platformId(): ValueExpression<string | number> {
220
+ const path = this.path.member('platform', 'platformId');
221
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded.withPath(path));
222
  if (!this.value) return ValueExpression.missing<string | number>();
 
223
  if (!this.value.isLoaded('platform')) {
224
  return ValueExpression.notLoaded<string | number>(
225
+ new TeaQLNotLoadedError(path.markMissing(), 'platform'),
226
  );
227
  }
228
  const reference = this.value.platform;
 
233
  }
234
 
235
  platform(): PlatformExpression {
236
+ const path = this.path.member('platform', 'platform');
237
  if (this.notLoaded) {
238
+ return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path));
239
  }
240
  if (!this.value) return new PlatformExpression(undefined, this.root, path);
241
  if (!this.value.isLoaded('platform')) {
242
  return new PlatformExpression(undefined, this.root, path,
243
+ new TeaQLNotLoadedError(path.markMissing(), 'platform'));
244
  }
245
  const relation = this.value.platform;
246
+ // An available FK is not an eagerly loaded relation. Keep the FK
247
+ // readable through the Id accessor, without fabricating a child object.
248
+ if (relation != null && !(relation instanceof Platform)) {
249
+ return new PlatformExpression(undefined, this.root, path,
250
+ new TeaQLNotLoadedError(path.markMissing(), 'platform'));
251
+ }
252
+ const target = relation instanceof Platform ? relation : undefined;
253
  return new PlatformExpression(target, this.root, path);
254
  }
255
 
256
  customerOrderList(): CustomerOrderListExpression {
257
+ const path = this.path.member('customer_order_list', 'customerOrderList');
258
  if (this.notLoaded) {
259
+ return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path));
260
  }
261
  if (!this.value) return CustomerOrderListExpression.missing(this.root, path);
262
  if (!this.value.isLoaded('customerOrderList')) {
263
  return new CustomerOrderListExpression([], this.root, path, false,
264
+ new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list'));
265
  }
266
  return new CustomerOrderListExpression(
267
  this.value.customerOrderList(), this.root, path,
 
273
  constructor(
274
  private readonly value: Customer | null | undefined,
275
  private readonly root = 'Customer(null)',
276
+ private readonly path = ExpressionPath.root('E.customer(<root>)', 'camelCase'),
277
  private readonly notLoaded?: TeaQLNotLoadedError,
278
  ) {}
279
 
280
  eval(): Customer | null | undefined {
281
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
282
  return this.value;
283
  }
284
 
285
  id(): ValueExpression<string> {
286
+ const path = this.path.member('id', 'id');
287
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
288
  if (!this.value) return ValueExpression.missing<string>();
 
289
  if (!this.value.isLoaded('id')) {
290
  return ValueExpression.notLoaded<string>(
291
+ new TeaQLNotLoadedError(path.markMissing(), 'id'),
292
  );
293
  }
294
  return new ValueExpression<string>(this.value.id);
295
  }
296
 
297
  name(): ValueExpression<string> {
298
+ const path = this.path.member('name', 'name');
299
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
300
  if (!this.value) return ValueExpression.missing<string>();
 
301
  if (!this.value.isLoaded('name')) {
302
  return ValueExpression.notLoaded<string>(
303
+ new TeaQLNotLoadedError(path.markMissing(), 'name'),
304
  );
305
  }
306
  return new ValueExpression<string>(this.value.name);
307
  }
308
 
309
+ version(): ValueExpression<EntityVersion> {
310
+ const path = this.path.member('version', 'version');
311
+ if (this.notLoaded) return ValueExpression.notLoaded<EntityVersion>(this.notLoaded.withPath(path));
312
+ if (!this.value) return ValueExpression.missing<EntityVersion>();
313
  if (!this.value.isLoaded('version')) {
314
+ return ValueExpression.notLoaded<EntityVersion>(
315
+ new TeaQLNotLoadedError(path.markMissing(), 'version'),
316
  );
317
  }
318
+ return new ValueExpression<EntityVersion>(this.value.version);
319
  }
320
 
321
  platformId(): ValueExpression<string | number> {
322
+ const path = this.path.member('platform', 'platformId');
323
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded.withPath(path));
324
  if (!this.value) return ValueExpression.missing<string | number>();
 
325
  if (!this.value.isLoaded('platform')) {
326
  return ValueExpression.notLoaded<string | number>(
327
+ new TeaQLNotLoadedError(path.markMissing(), 'platform'),
328
  );
329
  }
330
  const reference = this.value.platform;
 
335
  }
336
 
337
  platform(): PlatformExpression {
338
+ const path = this.path.member('platform', 'platform');
339
  if (this.notLoaded) {
340
+ return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path));
341
  }
342
  if (!this.value) return new PlatformExpression(undefined, this.root, path);
343
  if (!this.value.isLoaded('platform')) {
344
  return new PlatformExpression(undefined, this.root, path,
345
+ new TeaQLNotLoadedError(path.markMissing(), 'platform'));
346
  }
347
  const relation = this.value.platform;
348
+ // An available FK is not an eagerly loaded relation. Keep the FK
349
+ // readable through the Id accessor, without fabricating a child object.
350
+ if (relation != null && !(relation instanceof Platform)) {
351
+ return new PlatformExpression(undefined, this.root, path,
352
+ new TeaQLNotLoadedError(path.markMissing(), 'platform'));
353
+ }
354
+ const target = relation instanceof Platform ? relation : undefined;
355
  return new PlatformExpression(target, this.root, path);
356
  }
357
 
358
  customerOrderList(): CustomerOrderListExpression {
359
+ const path = this.path.member('customer_order_list', 'customerOrderList');
360
  if (this.notLoaded) {
361
+ return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path));
362
  }
363
  if (!this.value) return CustomerOrderListExpression.missing(this.root, path);
364
  if (!this.value.isLoaded('customerOrderList')) {
365
  return new CustomerOrderListExpression([], this.root, path, false,
366
+ new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list'));
367
  }
368
  return new CustomerOrderListExpression(
369
  this.value.customerOrderList(), this.root, path,
 
375
  constructor(
376
  private readonly value: CustomerOrder | null | undefined,
377
  private readonly root = 'CustomerOrder(null)',
378
+ private readonly path = ExpressionPath.root('E.customerOrder(<root>)', 'camelCase'),
379
  private readonly notLoaded?: TeaQLNotLoadedError,
380
  ) {}
381
 
382
  eval(): CustomerOrder | null | undefined {
383
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
384
  return this.value;
385
  }
386
 
387
  id(): ValueExpression<string> {
388
+ const path = this.path.member('id', 'id');
389
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
390
  if (!this.value) return ValueExpression.missing<string>();
 
391
  if (!this.value.isLoaded('id')) {
392
  return ValueExpression.notLoaded<string>(
393
+ new TeaQLNotLoadedError(path.markMissing(), 'id'),
394
  );
395
  }
396
  return new ValueExpression<string>(this.value.id);
397
  }
398
 
399
  orderNumber(): ValueExpression<string> {
400
+ const path = this.path.member('order_number', 'orderNumber');
401
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
402
  if (!this.value) return ValueExpression.missing<string>();
 
403
  if (!this.value.isLoaded('orderNumber')) {
404
  return ValueExpression.notLoaded<string>(
405
+ new TeaQLNotLoadedError(path.markMissing(), 'order_number'),
406
  );
407
  }
408
  return new ValueExpression<string>(this.value.orderNumber);
409
  }
410
 
411
  orderDate(): ValueExpression<string> {
412
+ const path = this.path.member('order_date', 'orderDate');
413
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
414
  if (!this.value) return ValueExpression.missing<string>();
 
415
  if (!this.value.isLoaded('orderDate')) {
416
  return ValueExpression.notLoaded<string>(
417
+ new TeaQLNotLoadedError(path.markMissing(), 'order_date'),
418
  );
419
  }
420
  return new ValueExpression<string>(this.value.orderDate);
421
  }
422
 
423
+ totalAmount(): ValueExpression<Decimal> {
424
+ const path = this.path.member('total_amount', 'totalAmount');
425
+ if (this.notLoaded) return ValueExpression.notLoaded<Decimal>(this.notLoaded.withPath(path));
426
+ if (!this.value) return ValueExpression.missing<Decimal>();
427
  if (!this.value.isLoaded('totalAmount')) {
428
+ return ValueExpression.notLoaded<Decimal>(
429
+ new TeaQLNotLoadedError(path.markMissing(), 'total_amount'),
430
  );
431
  }
432
+ return new ValueExpression<Decimal>(this.value.totalAmount);
433
  }
434
 
435
+ version(): ValueExpression<EntityVersion> {
436
+ const path = this.path.member('version', 'version');
437
+ if (this.notLoaded) return ValueExpression.notLoaded<EntityVersion>(this.notLoaded.withPath(path));
438
+ if (!this.value) return ValueExpression.missing<EntityVersion>();
439
  if (!this.value.isLoaded('version')) {
440
+ return ValueExpression.notLoaded<EntityVersion>(
441
+ new TeaQLNotLoadedError(path.markMissing(), 'version'),
442
  );
443
  }
444
+ return new ValueExpression<EntityVersion>(this.value.version);
445
  }
446
 
447
  customerId(): ValueExpression<string | number> {
448
+ const path = this.path.member('customer', 'customerId');
449
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded.withPath(path));
450
  if (!this.value) return ValueExpression.missing<string | number>();
 
451
  if (!this.value.isLoaded('customer')) {
452
  return ValueExpression.notLoaded<string | number>(
453
+ new TeaQLNotLoadedError(path.markMissing(), 'customer'),
454
  );
455
  }
456
  const reference = this.value.customer;
 
461
  }
462
 
463
  statusId(): ValueExpression<string | number> {
464
+ const path = this.path.member('status', 'statusId');
465
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded.withPath(path));
466
  if (!this.value) return ValueExpression.missing<string | number>();
 
467
  if (!this.value.isLoaded('status')) {
468
  return ValueExpression.notLoaded<string | number>(
469
+ new TeaQLNotLoadedError(path.markMissing(), 'status'),
470
  );
471
  }
472
  const reference = this.value.status;
 
477
  }
478
 
479
  customer(): CustomerExpression {
480
+ const path = this.path.member('customer', 'customer');
481
  if (this.notLoaded) {
482
+ return new CustomerExpression(undefined, this.root, path, this.notLoaded.withPath(path));
483
  }
484
  if (!this.value) return new CustomerExpression(undefined, this.root, path);
485
  if (!this.value.isLoaded('customer')) {
486
  return new CustomerExpression(undefined, this.root, path,
487
+ new TeaQLNotLoadedError(path.markMissing(), 'customer'));
488
  }
489
  const relation = this.value.customer;
490
+ // An available FK is not an eagerly loaded relation. Keep the FK
491
+ // readable through the Id accessor, without fabricating a child object.
492
+ if (relation != null && !(relation instanceof Customer)) {
493
+ return new CustomerExpression(undefined, this.root, path,
494
+ new TeaQLNotLoadedError(path.markMissing(), 'customer'));
495
+ }
496
+ const target = relation instanceof Customer ? relation : undefined;
497
  return new CustomerExpression(target, this.root, path);
498
  }
499
 
500
  status(): OrderStatusExpression {
501
+ const path = this.path.member('status', 'status');
502
  if (this.notLoaded) {
503
+ return new OrderStatusExpression(undefined, this.root, path, this.notLoaded.withPath(path));
504
  }
505
  if (!this.value) return new OrderStatusExpression(undefined, this.root, path);
506
  if (!this.value.isLoaded('status')) {
507
  return new OrderStatusExpression(undefined, this.root, path,
508
+ new TeaQLNotLoadedError(path.markMissing(), 'status'));
509
  }
510
  const relation = this.value.status;
511
+ // An available FK is not an eagerly loaded relation. Keep the FK
512
+ // readable through the Id accessor, without fabricating a child object.
513
+ if (relation != null && !(relation instanceof OrderStatus)) {
514
+ return new OrderStatusExpression(undefined, this.root, path,
515
+ new TeaQLNotLoadedError(path.markMissing(), 'status'));
516
+ }
517
+ const target = relation instanceof OrderStatus ? relation : undefined;
518
  return new OrderStatusExpression(target, this.root, path);
519
  }
520
 
521
  orderItemList(): OrderItemListExpression {
522
+ const path = this.path.member('order_item_list', 'orderItemList');
523
  if (this.notLoaded) {
524
+ return new OrderItemListExpression([], this.root, path, false, this.notLoaded.withPath(path));
525
  }
526
  if (!this.value) return OrderItemListExpression.missing(this.root, path);
527
  if (!this.value.isLoaded('orderItemList')) {
528
  return new OrderItemListExpression([], this.root, path, false,
529
+ new TeaQLNotLoadedError(path.markMissing(), 'order_item_list'));
530
  }
531
  return new OrderItemListExpression(
532
  this.value.orderItemList(), this.root, path,
 
538
  constructor(
539
  private readonly value: OrderItem | null | undefined,
540
  private readonly root = 'OrderItem(null)',
541
+ private readonly path = ExpressionPath.root('E.orderItem(<root>)', 'camelCase'),
542
  private readonly notLoaded?: TeaQLNotLoadedError,
543
  ) {}
544
 
545
  eval(): OrderItem | null | undefined {
546
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
547
  return this.value;
548
  }
549
 
550
  id(): ValueExpression<string> {
551
+ const path = this.path.member('id', 'id');
552
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
553
  if (!this.value) return ValueExpression.missing<string>();
 
554
  if (!this.value.isLoaded('id')) {
555
  return ValueExpression.notLoaded<string>(
556
+ new TeaQLNotLoadedError(path.markMissing(), 'id'),
557
  );
558
  }
559
  return new ValueExpression<string>(this.value.id);
560
  }
561
 
562
  productName(): ValueExpression<string> {
563
+ const path = this.path.member('product_name', 'productName');
564
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
565
  if (!this.value) return ValueExpression.missing<string>();
 
566
  if (!this.value.isLoaded('productName')) {
567
  return ValueExpression.notLoaded<string>(
568
+ new TeaQLNotLoadedError(path.markMissing(), 'product_name'),
569
  );
570
  }
571
  return new ValueExpression<string>(this.value.productName);
572
  }
573
 
574
  quantity(): ValueExpression<number> {
575
+ const path = this.path.member('quantity', 'quantity');
576
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(path));
577
  if (!this.value) return ValueExpression.missing<number>();
 
578
  if (!this.value.isLoaded('quantity')) {
579
  return ValueExpression.notLoaded<number>(
580
+ new TeaQLNotLoadedError(path.markMissing(), 'quantity'),
581
  );
582
  }
583
+ const error = integer32Error(this.value.quantity, 'OrderItem', 'quantity');
584
+ if (error) return ValueExpression.invalid<number>(error);
585
  return new ValueExpression<number>(this.value.quantity);
586
  }
587
 
588
+ unitPrice(): ValueExpression<Decimal> {
589
+ const path = this.path.member('unit_price', 'unitPrice');
590
+ if (this.notLoaded) return ValueExpression.notLoaded<Decimal>(this.notLoaded.withPath(path));
591
+ if (!this.value) return ValueExpression.missing<Decimal>();
592
  if (!this.value.isLoaded('unitPrice')) {
593
+ return ValueExpression.notLoaded<Decimal>(
594
+ new TeaQLNotLoadedError(path.markMissing(), 'unit_price'),
595
  );
596
  }
597
+ return new ValueExpression<Decimal>(this.value.unitPrice);
598
  }
599
 
600
+ version(): ValueExpression<EntityVersion> {
601
+ const path = this.path.member('version', 'version');
602
+ if (this.notLoaded) return ValueExpression.notLoaded<EntityVersion>(this.notLoaded.withPath(path));
603
+ if (!this.value) return ValueExpression.missing<EntityVersion>();
604
  if (!this.value.isLoaded('version')) {
605
+ return ValueExpression.notLoaded<EntityVersion>(
606
+ new TeaQLNotLoadedError(path.markMissing(), 'version'),
607
  );
608
  }
609
+ return new ValueExpression<EntityVersion>(this.value.version);
610
  }
611
 
612
  customerOrderId(): ValueExpression<string | number> {
613
+ const path = this.path.member('customer_order', 'customerOrderId');
614
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded.withPath(path));
615
  if (!this.value) return ValueExpression.missing<string | number>();
 
616
  if (!this.value.isLoaded('customerOrder')) {
617
  return ValueExpression.notLoaded<string | number>(
618
+ new TeaQLNotLoadedError(path.markMissing(), 'customer_order'),
619
  );
620
  }
621
  const reference = this.value.customerOrder;
 
626
  }
627
 
628
  customerOrder(): CustomerOrderExpression {
629
+ const path = this.path.member('customer_order', 'customerOrder');
630
  if (this.notLoaded) {
631
+ return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded.withPath(path));
632
  }
633
  if (!this.value) return new CustomerOrderExpression(undefined, this.root, path);
634
  if (!this.value.isLoaded('customerOrder')) {
635
  return new CustomerOrderExpression(undefined, this.root, path,
636
+ new TeaQLNotLoadedError(path.markMissing(), 'customer_order'));
637
  }
638
  const relation = this.value.customerOrder;
639
+ // An available FK is not an eagerly loaded relation. Keep the FK
640
+ // readable through the Id accessor, without fabricating a child object.
641
+ if (relation != null && !(relation instanceof CustomerOrder)) {
642
+ return new CustomerOrderExpression(undefined, this.root, path,
643
+ new TeaQLNotLoadedError(path.markMissing(), 'customer_order'));
644
+ }
645
+ const target = relation instanceof CustomerOrder ? relation : undefined;
646
  return new CustomerOrderExpression(target, this.root, path);
647
  }
648
 
 
652
  constructor(
653
  private readonly items: readonly Platform[],
654
  private readonly root = 'Platform(null)',
655
+ private readonly path = ExpressionPath.root('E.entity(<root>)', 'camelCase'),
656
  private readonly present = true,
657
  private readonly notLoaded?: TeaQLNotLoadedError,
658
  ) {}
659
 
660
+ static missing(root?: string, path = ExpressionPath.root('E.entity(<root>)', 'camelCase')): PlatformListExpression {
661
  return new PlatformListExpression([], root, path, false);
662
  }
663
 
664
  size(): ValueExpression<number> {
665
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(this.path.operation('size()')));
666
  return this.present
667
  ? new ValueExpression<number>(this.items.length)
668
  : ValueExpression.missing<number>();
669
  }
670
 
671
  first(): PlatformExpression {
672
+ return this.item(0, true);
673
  }
674
 
675
  get(index: number): PlatformExpression {
676
+ return this.item(index, false);
677
+ }
678
+
679
+ private item(index: number, first: boolean): PlatformExpression {
680
+ const itemPath = this.path.index(index, first);
681
  if (this.notLoaded) {
682
+ return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath));
683
  }
684
  return !this.present || index < 0 || index >= this.items.length
685
  ? new PlatformExpression(undefined, this.root, itemPath)
 
691
  constructor(
692
  private readonly items: readonly OrderStatus[],
693
  private readonly root = 'OrderStatus(null)',
694
+ private readonly path = ExpressionPath.root('E.entity(<root>)', 'camelCase'),
695
  private readonly present = true,
696
  private readonly notLoaded?: TeaQLNotLoadedError,
697
  ) {}
698
 
699
+ static missing(root?: string, path = ExpressionPath.root('E.entity(<root>)', 'camelCase')): OrderStatusListExpression {
700
  return new OrderStatusListExpression([], root, path, false);
701
  }
702
 
703
  size(): ValueExpression<number> {
704
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(this.path.operation('size()')));
705
  return this.present
706
  ? new ValueExpression<number>(this.items.length)
707
  : ValueExpression.missing<number>();
708
  }
709
 
710
  first(): OrderStatusExpression {
711
+ return this.item(0, true);
712
  }
713
 
714
  get(index: number): OrderStatusExpression {
715
+ return this.item(index, false);
716
+ }
717
+
718
+ private item(index: number, first: boolean): OrderStatusExpression {
719
+ const itemPath = this.path.index(index, first);
720
  if (this.notLoaded) {
721
+ return new OrderStatusExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath));
722
  }
723
  return !this.present || index < 0 || index >= this.items.length
724
  ? new OrderStatusExpression(undefined, this.root, itemPath)
 
730
  constructor(
731
  private readonly items: readonly Customer[],
732
  private readonly root = 'Customer(null)',
733
+ private readonly path = ExpressionPath.root('E.entity(<root>)', 'camelCase'),
734
  private readonly present = true,
735
  private readonly notLoaded?: TeaQLNotLoadedError,
736
  ) {}
737
 
738
+ static missing(root?: string, path = ExpressionPath.root('E.entity(<root>)', 'camelCase')): CustomerListExpression {
739
  return new CustomerListExpression([], root, path, false);
740
  }
741
 
742
  size(): ValueExpression<number> {
743
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(this.path.operation('size()')));
744
  return this.present
745
  ? new ValueExpression<number>(this.items.length)
746
  : ValueExpression.missing<number>();
747
  }
748
 
749
  first(): CustomerExpression {
750
+ return this.item(0, true);
751
  }
752
 
753
  get(index: number): CustomerExpression {
754
+ return this.item(index, false);
755
+ }
756
+
757
+ private item(index: number, first: boolean): CustomerExpression {
758
+ const itemPath = this.path.index(index, first);
759
  if (this.notLoaded) {
760
+ return new CustomerExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath));
761
  }
762
  return !this.present || index < 0 || index >= this.items.length
763
  ? new CustomerExpression(undefined, this.root, itemPath)
 
769
  constructor(
770
  private readonly items: readonly CustomerOrder[],
771
  private readonly root = 'CustomerOrder(null)',
772
+ private readonly path = ExpressionPath.root('E.entity(<root>)', 'camelCase'),
773
  private readonly present = true,
774
  private readonly notLoaded?: TeaQLNotLoadedError,
775
  ) {}
776
 
777
+ static missing(root?: string, path = ExpressionPath.root('E.entity(<root>)', 'camelCase')): CustomerOrderListExpression {
778
  return new CustomerOrderListExpression([], root, path, false);
779
  }
780
 
781
  size(): ValueExpression<number> {
782
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(this.path.operation('size()')));
783
  return this.present
784
  ? new ValueExpression<number>(this.items.length)
785
  : ValueExpression.missing<number>();
786
  }
787
 
788
  first(): CustomerOrderExpression {
789
+ return this.item(0, true);
790
  }
791
 
792
  get(index: number): CustomerOrderExpression {
793
+ return this.item(index, false);
794
+ }
795
+
796
+ private item(index: number, first: boolean): CustomerOrderExpression {
797
+ const itemPath = this.path.index(index, first);
798
  if (this.notLoaded) {
799
+ return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath));
800
  }
801
  return !this.present || index < 0 || index >= this.items.length
802
  ? new CustomerOrderExpression(undefined, this.root, itemPath)
 
808
  constructor(
809
  private readonly items: readonly OrderItem[],
810
  private readonly root = 'OrderItem(null)',
811
+ private readonly path = ExpressionPath.root('E.entity(<root>)', 'camelCase'),
812
  private readonly present = true,
813
  private readonly notLoaded?: TeaQLNotLoadedError,
814
  ) {}
815
 
816
+ static missing(root?: string, path = ExpressionPath.root('E.entity(<root>)', 'camelCase')): OrderItemListExpression {
817
  return new OrderItemListExpression([], root, path, false);
818
  }
819
 
820
  size(): ValueExpression<number> {
821
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(this.path.operation('size()')));
822
  return this.present
823
  ? new ValueExpression<number>(this.items.length)
824
  : ValueExpression.missing<number>();
825
  }
826
 
827
  first(): OrderItemExpression {
828
+ return this.item(0, true);
829
  }
830
 
831
  get(index: number): OrderItemExpression {
832
+ return this.item(index, false);
833
+ }
834
+
835
+ private item(index: number, first: boolean): OrderItemExpression {
836
+ const itemPath = this.path.index(index, first);
837
  if (this.notLoaded) {
838
+ return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath));
839
  }
840
  return !this.present || index < 0 || index >= this.items.length
841
  ? new OrderItemExpression(undefined, this.root, itemPath)
 
848
  value: Platform | null | undefined,
849
  ): PlatformExpression {
850
  return new PlatformExpression(
851
+ value, 'Platform', ExpressionPath.root('E.platform(<root>)', 'camelCase'),
852
  );
853
  }
854
 
 
856
  value: OrderStatus | null | undefined,
857
  ): OrderStatusExpression {
858
  return new OrderStatusExpression(
859
+ value, 'OrderStatus', ExpressionPath.root('E.orderStatus(<root>)', 'camelCase'),
860
  );
861
  }
862
 
 
864
  value: Customer | null | undefined,
865
  ): CustomerExpression {
866
  return new CustomerExpression(
867
+ value, 'Customer', ExpressionPath.root('E.customer(<root>)', 'camelCase'),
868
  );
869
  }
870
 
 
872
  value: CustomerOrder | null | undefined,
873
  ): CustomerOrderExpression {
874
  return new CustomerOrderExpression(
875
+ value, 'CustomerOrder', ExpressionPath.root('E.customerOrder(<root>)', 'camelCase'),
876
  );
877
  }
878
 
 
880
  value: OrderItem | null | undefined,
881
  ): OrderItemExpression {
882
  return new OrderItemExpression(
883
+ value, 'OrderItem', ExpressionPath.root('E.orderItem(<root>)', 'camelCase'),
884
  );
885
  }
886
  }
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts CHANGED
@@ -1,24 +1,30 @@
1
- import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { Platform } from './Platform';
3
  import { CustomerOrder } from './CustomerOrder';
4
 
 
 
5
  export class Customer {
6
  private static teaqlTemporaryId = 0;
 
 
7
  id?: string;
8
  platform?: Platform | string;
9
  name?: string;
10
- version?: number;
11
 
12
- constructor(init?: Partial<Customer>) {
13
- Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
 
14
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
15
- Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
16
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
17
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
18
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Customer.teaqlTemporaryId, writable: true, enumerable: false });
19
- Object.defineProperty(this, "_customerOrderList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false });
20
  if (init) {
21
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
 
22
  delete fields["customerOrderList"];
23
  Object.assign(this, fields);
24
  if ((init as any).platform && typeof (init as any).platform === "object") {
@@ -39,24 +45,32 @@ export class Customer {
39
  }
40
  }
41
  const key = this.teaqlEntityKey();
 
42
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
43
- else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
44
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
 
45
  }
46
 
47
  private teaqlEntityKey(): EntityKey { return { entity: "Customer", id: (this as any)._ledgerId }; }
48
- private teaqlAttachRoot(root: EntityRoot): this {
49
  if ((this as any)._root !== root) {
50
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
51
  (this as any)._root = root;
52
  }
53
- for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root);
54
  return this;
55
  }
56
 
57
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Customer {
58
- const entity = new Customer(record as Partial<Customer>);
59
- return root ? entity.teaqlAttachRoot(root) : entity;
 
 
 
 
 
 
60
  }
61
 
62
  isLoaded(field: string): boolean {
@@ -75,12 +89,19 @@ export class Customer {
75
  }
76
 
77
  static refer(id: string | number): Customer {
78
- return new Customer({ id: String(id) } as Partial<Customer>);
79
  }
80
 
81
  /** @internal Generated Runtime Module fixed-ID construction capability. */
82
- static teaqlBootstrapNew(id: string | number): Customer {
83
- return new Customer().updateId(String(id));
 
 
 
 
 
 
 
84
  }
85
 
86
  markForDeletion(): this {
@@ -90,23 +111,127 @@ export class Customer {
90
  }
91
 
92
  auditAs(comment: string): this {
93
- new MutationIntent(comment);
94
- (this as any)._comment = comment;
95
  return this;
96
  }
97
 
98
  async save(context: UserContext): Promise<Customer> {
 
 
 
99
  const service = context.requireResource<TeaQLDataService>("dataService");
100
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
101
- this.teaqlPreflightGraph(context, service, graph);
102
  return this.teaqlSaveWithinGraph(context, service, graph);
 
 
 
 
 
 
 
 
 
 
 
103
  });
104
  }
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  /** @internal Validates and fixes the complete graph before its first mutation. */
107
- teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
108
  if (!parent) new MutationIntent((this as any)._comment);
 
 
109
  const action = (this as any)._action;
 
 
110
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
111
  if (action === "Update" && pending) {
112
  const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]
@@ -114,6 +239,7 @@ export class Customer {
114
  if (notLoaded) {
115
  throw new CheckException([{
116
  ruleId: "invalid_type",
 
117
  location: ObjectLocation.property(notLoaded.canonical),
118
  message: "Mutation requires a fully loaded entity",
119
  }]);
@@ -124,7 +250,8 @@ export class Customer {
124
  payload: action === "Update"
125
  ? (this as any)._root.change(this.teaqlEntityKey())
126
  : this.teaqlMutationPayload(),
127
- id: (this as any).id, version: (this as any).version,
 
128
  comment: (this as any)._comment,
129
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
130
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
@@ -133,22 +260,25 @@ export class Customer {
133
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
134
  child.teaqlAttachRoot((this as any)._root);
135
  const currentParent = child.customer;
136
- if (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null
137
- ? currentParent.id : currentParent) !== this.id) child.updateCustomer(this);
138
- try { child.teaqlPreflightGraph(context, service, graph, scope); }
 
139
  catch (error) {
140
  if (!(error instanceof CheckException)) throw error;
141
  const prefix = ObjectLocation.property("customer_order_list").index(index);
142
- throw new CheckException(error.violations.map(violation => ({
143
  ...violation, location: violation.location.prefixedBy(prefix),
144
- })));
145
  }
146
  }
147
  }
148
 
149
  /** @internal Used by generated relation cascades inside the root graph transaction. */
150
- async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<Customer> {
151
  if (!parent) new MutationIntent((this as any)._comment);
 
 
152
  const action = (this as any)._action;
153
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
154
  const mutation = {
@@ -156,7 +286,7 @@ export class Customer {
156
  action: (this as any)._action,
157
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
158
  id: (this as any).id,
159
- version: (this as any).version,
160
  comment: (this as any)._comment
161
  ,ledgerKey: this.teaqlEntityKey()
162
  ,ledgerRoot: (this as any)._root
@@ -168,28 +298,27 @@ export class Customer {
168
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
169
  child.teaqlAttachRoot((this as any)._root);
170
  const currentParent = child.customer;
171
- if (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null
172
- ? currentParent.id : currentParent) !== this.id) child.updateCustomer(this);
173
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
174
  catch (error) {
175
  if (!(error instanceof CheckException)) throw error;
176
  const prefix = ObjectLocation.property("customer_order_list").index(index);
177
- throw new CheckException(error.violations.map(violation => ({
178
  ...violation, location: violation.location.prefixedBy(prefix),
179
- })));
180
  }
181
  }
182
  return this;
183
  }
184
  const result = await service.executeMutation(request);
185
- for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
186
- if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
187
- }
188
  if (!result.persistedRecord) {
189
  throw new Error("Mutation did not return the authoritative persisted record");
190
  }
191
  const rollbackState = {
192
- payload: this.teaqlMutationPayload(),
193
  ledgerId: (this as any)._ledgerId,
194
  action: (this as any)._action,
195
  loadedFields: new Set((this as any)._loadedFields),
@@ -198,12 +327,16 @@ export class Customer {
198
  };
199
  const oldKey = this.teaqlEntityKey();
200
  Object.assign(this, result.persistedRecord);
201
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
202
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
203
  const newKey = this.teaqlEntityKey();
204
  (this as any)._root.rekey(oldKey, newKey);
 
 
205
  service.afterGraphRollback(() => {
206
- Object.assign(this, rollbackState.payload);
 
 
 
207
  (this as any)._ledgerId = rollbackState.ledgerId;
208
  (this as any)._action = rollbackState.action;
209
  (this as any)._loadedFields = rollbackState.loadedFields;
@@ -214,24 +347,29 @@ export class Customer {
214
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
215
  (this as any)._fullyLoaded = false;
216
  if (mutation.action !== "Delete") (this as any)._action = "Update";
 
217
  const scope = request.scopeFor(newKey);
218
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
219
  child.teaqlAttachRoot((this as any)._root);
220
  const currentParent = child.customer;
221
- if (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null
222
- ? currentParent.id : currentParent) !== this.id) child.updateCustomer(this);
223
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
224
  catch (error) {
225
  if (!(error instanceof CheckException)) throw error;
226
  const prefix = ObjectLocation.property("customer_order_list").index(index);
227
- throw new CheckException(error.violations.map(violation => ({
228
  ...violation, location: violation.location.prefixedBy(prefix),
229
- })));
230
  }
231
  }
232
  service.afterGraphCommit(() => {
 
 
233
  (this as any)._root.clearEntity(newKey);
234
- if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
 
235
  });
236
  return this;
237
  }
@@ -245,6 +383,10 @@ export class Customer {
245
  };
246
  }
247
 
 
 
 
 
248
  updateId(value: string): this {
249
  this.id = value;
250
  this.markLoaded("id");
@@ -259,7 +401,7 @@ export class Customer {
259
  return this;
260
  }
261
 
262
- updateVersion(value: number): this {
263
  this.version = value;
264
  this.markLoaded("version");
265
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
 
1
+ import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { Platform } from './Platform';
3
  import { CustomerOrder } from './CustomerOrder';
4
 
5
+ const teaqlConstruction = Symbol("managed entity construction");
6
+
7
  export class Customer {
8
  private static teaqlTemporaryId = 0;
9
+ private static readonly teaqlMutationFields = new MutationFieldLayout("Customer",
10
+ ["id", "platform", "name", "version"], { id: "immutable_field", version: "immutable_field" });
11
  id?: string;
12
  platform?: Platform | string;
13
  name?: string;
14
+ version?: EntityVersion;
15
 
16
+ private constructor(init?: Partial<Customer>, token?: symbol, creation = false) {
17
+ if (token !== teaqlConstruction) throw new EntityCreationError();
18
+ Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false });
19
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
20
+ Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false });
21
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
22
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
23
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Customer.teaqlTemporaryId, writable: true, enumerable: false });
24
+ Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false });
25
  if (init) {
26
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
27
+ for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key];
28
  delete fields["customerOrderList"];
29
  Object.assign(this, fields);
30
  if ((init as any).platform && typeof (init as any).platform === "object") {
 
45
  }
46
  }
47
  const key = this.teaqlEntityKey();
48
+ if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version);
49
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
50
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version);
51
+ LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version,
52
+ creation ? "creationBaseline" : "hydrated");
53
  }
54
 
55
  private teaqlEntityKey(): EntityKey { return { entity: "Customer", id: (this as any)._ledgerId }; }
56
+ private teaqlAttachRoot(root: EntityRoot, hydration = false): this {
57
  if ((this as any)._root !== root) {
58
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
59
  (this as any)._root = root;
60
  }
61
+ for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration);
62
  return this;
63
  }
64
 
65
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Customer {
66
+ const entity = EntityCreation.hydrated(new Customer(record as Partial<Customer>, teaqlConstruction));
67
+ return root ? entity.teaqlAttachRoot(root, true) : entity;
68
+ }
69
+
70
+ toJSON(): Record<string, unknown> {
71
+ const result = Object.fromEntries(Object.entries(this));
72
+ if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList;
73
+ return result;
74
  }
75
 
76
  isLoaded(field: string): boolean {
 
89
  }
90
 
91
  static refer(id: string | number): Customer {
92
+ return Customer.fromRecord({ id: String(id) });
93
  }
94
 
95
  /** @internal Generated Runtime Module fixed-ID construction capability. */
96
+ static teaqlBootstrapNew(context: UserContext, id: string | number): Customer {
97
+ return EntityCreation.bootstrap(context, "Customer", id,
98
+ reserved => new Customer({id: reserved} as Partial<Customer>, teaqlConstruction, true));
99
+ }
100
+
101
+ /** @internal Q owns the awaited public creation entry point. */
102
+ static teaqlCreate(context: UserContext): Promise<Customer> {
103
+ return EntityCreation.create(context, "Customer",
104
+ reserved => new Customer({id: reserved} as Partial<Customer>, teaqlConstruction, true));
105
  }
106
 
107
  markForDeletion(): this {
 
111
  }
112
 
113
  auditAs(comment: string): this {
114
+ (this as any)._comment = new MutationIntent(comment).comment;
 
115
  return this;
116
  }
117
 
118
  async save(context: UserContext): Promise<Customer> {
119
+ const intent = new MutationIntent((this as any)._comment);
120
+ this.teaqlValidateLoadedIdentities();
121
+ if (!this.teaqlValidateMutationOrigins()) return this;
122
  const service = context.requireResource<TeaQLDataService>("dataService");
123
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
 
124
  return this.teaqlSaveWithinGraph(context, service, graph);
125
+ }, (graph) => {
126
+ this.teaqlPreflightGraph(context, service, graph);
127
+ this.teaqlValidateLoadedIdentities();
128
+ this.teaqlAdmitGraph();
129
+ graph.sealPreparedGraph();
130
+ }, (graph) => {
131
+ this.teaqlValidateLoadedIdentities();
132
+ this.teaqlDiscardRestoredGraph(graph);
133
+ this.teaqlAdmitGraph();
134
+ this.teaqlNormalizeGraph(graph);
135
+ return this.teaqlAdmitGraph();
136
  });
137
  }
138
 
139
+ /** @internal Pure provenance pass before resolving any Context resources. */
140
+ private teaqlValidateMutationOrigins(seen = new Set<object>()): boolean {
141
+ if (seen.has(this)) return false;
142
+ seen.add(this);
143
+ const action = (this as any)._action;
144
+ let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
145
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
146
+ for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending;
147
+ return pending;
148
+ }
149
+
150
+ /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */
151
+ private teaqlValidateLoadedIdentities(seen = new Set<object>()): void {
152
+ if (seen.has(this)) return;
153
+ seen.add(this);
154
+ LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version);
155
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
156
+ try { child.teaqlValidateLoadedIdentities(seen); }
157
+ catch (error) {
158
+ if (!(error instanceof CheckException)) throw error;
159
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
160
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
161
+ }
162
+ }
163
+ }
164
+
165
+ /** @internal Cancel known no-ops across the graph before any derived FK edits. */
166
+ private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
167
+ if (seen.has(this)) return;
168
+ seen.add(this);
169
+ graph.discardRestoredFields(Customer.teaqlMutationFields,
170
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
171
+ for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen);
172
+ }
173
+
174
+ /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */
175
+ private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
176
+ if (seen.has(this)) return;
177
+ seen.add(this);
178
+ graph.discardRestoredFields(Customer.teaqlMutationFields,
179
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
180
+ graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), {
181
+ "platform": "Platform"
182
+ }, () => ({ ...this.teaqlMutationPayload(),
183
+ __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action,
184
+ __teaql_comment: (this as any)._comment,
185
+ __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()},
186
+ "customer_order_list": graph.sourceMembers((this as any)._customerOrderList)
187
+ }));
188
+ for (const child of (this as any)._customerOrderList) {
189
+ child.teaqlAttachRoot((this as any)._root);
190
+ const currentParent = child.customer;
191
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
192
+ && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null
193
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this);
194
+ child.teaqlNormalizeGraph(graph, seen);
195
+ }
196
+ }
197
+
198
+ /** @internal Whole-input version/completeness pass; does not use Context or Fix. */
199
+ private teaqlAdmitGraph(seen = new Set<object>()): boolean {
200
+ if (seen.has(this)) return false;
201
+ seen.add(this);
202
+ const action = (this as any)._action;
203
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
204
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
205
+ LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey());
206
+ Customer.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update");
207
+ if (pending) {
208
+ nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion);
209
+ if (action === "Update") {
210
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member));
211
+ if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Customer", location: ObjectLocation.property(notLoaded.canonical),
212
+ message: "Mutation requires a fully loaded entity"}]);
213
+ }
214
+ }
215
+ let graphPending = pending;
216
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
217
+ try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; }
218
+ catch (error) {
219
+ if (!(error instanceof CheckException)) throw error;
220
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
221
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
222
+ }
223
+ }
224
+ return graphPending;
225
+ }
226
+
227
  /** @internal Validates and fixes the complete graph before its first mutation. */
228
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): void {
229
  if (!parent) new MutationIntent((this as any)._comment);
230
+ if (seen.has(this)) return;
231
+ seen.add(this);
232
  const action = (this as any)._action;
233
+ graph.discardRestoredFields(Customer.teaqlMutationFields,
234
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
235
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
236
  if (action === "Update" && pending) {
237
  const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]
 
239
  if (notLoaded) {
240
  throw new CheckException([{
241
  ruleId: "invalid_type",
242
+ entityType: "Customer",
243
  location: ObjectLocation.property(notLoaded.canonical),
244
  message: "Mutation requires a fully loaded entity",
245
  }]);
 
250
  payload: action === "Update"
251
  ? (this as any)._root.change(this.teaqlEntityKey())
252
  : this.teaqlMutationPayload(),
253
+ id: (this as any).id,
254
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
255
  comment: (this as any)._comment,
256
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
257
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
 
260
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
261
  child.teaqlAttachRoot((this as any)._root);
262
  const currentParent = child.customer;
263
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
264
+ && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null
265
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this);
266
+ try { child.teaqlPreflightGraph(context, service, graph, scope, seen); }
267
  catch (error) {
268
  if (!(error instanceof CheckException)) throw error;
269
  const prefix = ObjectLocation.property("customer_order_list").index(index);
270
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
271
  ...violation, location: violation.location.prefixedBy(prefix),
272
+ }))));
273
  }
274
  }
275
  }
276
 
277
  /** @internal Used by generated relation cascades inside the root graph transaction. */
278
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): Promise<Customer> {
279
  if (!parent) new MutationIntent((this as any)._comment);
280
+ if (seen.has(this)) return this;
281
+ seen.add(this);
282
  const action = (this as any)._action;
283
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
284
  const mutation = {
 
286
  action: (this as any)._action,
287
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
288
  id: (this as any).id,
289
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
290
  comment: (this as any)._comment
291
  ,ledgerKey: this.teaqlEntityKey()
292
  ,ledgerRoot: (this as any)._root
 
298
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
299
  child.teaqlAttachRoot((this as any)._root);
300
  const currentParent = child.customer;
301
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
302
+ && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null
303
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this);
304
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
305
  catch (error) {
306
  if (!(error instanceof CheckException)) throw error;
307
  const prefix = ObjectLocation.property("customer_order_list").index(index);
308
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
309
  ...violation, location: violation.location.prefixedBy(prefix),
310
+ }))));
311
  }
312
  }
313
  return this;
314
  }
315
  const result = await service.executeMutation(request);
316
+ graph.validatePreparedSources();
 
 
317
  if (!result.persistedRecord) {
318
  throw new Error("Mutation did not return the authoritative persisted record");
319
  }
320
  const rollbackState = {
321
+ ownProperties: Object.getOwnPropertyDescriptors(this),
322
  ledgerId: (this as any)._ledgerId,
323
  action: (this as any)._action,
324
  loadedFields: new Set((this as any)._loadedFields),
 
327
  };
328
  const oldKey = this.teaqlEntityKey();
329
  Object.assign(this, result.persistedRecord);
 
330
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
331
  const newKey = this.teaqlEntityKey();
332
  (this as any)._root.rekey(oldKey, newKey);
333
+ const committedSnapshot = this.teaqlScalarSnapshot();
334
+ const activeScope = request.scopeFor(newKey);
335
  service.afterGraphRollback(() => {
336
+ for (const name of Object.getOwnPropertyNames(this)) {
337
+ if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name];
338
+ }
339
+ Object.defineProperties(this, rollbackState.ownProperties);
340
  (this as any)._ledgerId = rollbackState.ledgerId;
341
  (this as any)._action = rollbackState.action;
342
  (this as any)._loadedFields = rollbackState.loadedFields;
 
347
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
348
  (this as any)._fullyLoaded = false;
349
  if (mutation.action !== "Delete") (this as any)._action = "Update";
350
+ graph.acceptPreparedResult((this as any)._root, oldKey, newKey);
351
  const scope = request.scopeFor(newKey);
352
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
353
  child.teaqlAttachRoot((this as any)._root);
354
  const currentParent = child.customer;
355
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
356
+ && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null
357
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this);
358
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
359
  catch (error) {
360
  if (!(error instanceof CheckException)) throw error;
361
  const prefix = ObjectLocation.property("customer_order_list").index(index);
362
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
363
  ...violation, location: violation.location.prefixedBy(prefix),
364
+ }))));
365
  }
366
  }
367
  service.afterGraphCommit(() => {
368
+ graph.validatePreparedSources();
369
+ LoadedScalarSnapshot.restoreFor(this, committedSnapshot);
370
  (this as any)._root.clearEntity(newKey);
371
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version);
372
+ graph.finishPreparedCommit((this as any)._root, newKey);
373
  });
374
  return this;
375
  }
 
383
  };
384
  }
385
 
386
+ private teaqlScalarSnapshot(): LoadedScalarSnapshot {
387
+ return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version);
388
+ }
389
+
390
  updateId(value: string): this {
391
  this.id = value;
392
  this.markLoaded("id");
 
401
  return this;
402
  }
403
 
404
+ updateVersion(value: EntityVersion): this {
405
  this.version = value;
406
  this.markLoaded("version");
407
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts CHANGED
@@ -1,28 +1,34 @@
1
- import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { Customer } from './Customer';
3
  import { OrderStatus } from './OrderStatus';
4
  import { OrderItem } from './OrderItem';
5
 
 
 
6
  export class CustomerOrder {
7
  private static teaqlTemporaryId = 0;
 
 
8
  id?: string;
9
  customer?: Customer | string;
10
  status?: OrderStatus | string;
11
  orderNumber?: string;
12
  orderDate?: string;
13
- totalAmount?: number;
14
- version?: number;
15
 
16
- constructor(init?: Partial<CustomerOrder>) {
17
- Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
 
18
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
19
- Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
20
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
21
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
22
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --CustomerOrder.teaqlTemporaryId, writable: true, enumerable: false });
23
- Object.defineProperty(this, "_orderItemList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false });
24
  if (init) {
25
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
 
26
  delete fields["orderItemList"];
27
  Object.assign(this, fields);
28
  if ((init as any).customer && typeof (init as any).customer === "object") {
@@ -49,24 +55,32 @@ export class CustomerOrder {
49
  }
50
  }
51
  const key = this.teaqlEntityKey();
 
52
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
53
- else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
54
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
 
55
  }
56
 
57
  private teaqlEntityKey(): EntityKey { return { entity: "CustomerOrder", id: (this as any)._ledgerId }; }
58
- private teaqlAttachRoot(root: EntityRoot): this {
59
  if ((this as any)._root !== root) {
60
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
61
  (this as any)._root = root;
62
  }
63
- for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root);
64
  return this;
65
  }
66
 
67
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): CustomerOrder {
68
- const entity = new CustomerOrder(record as Partial<CustomerOrder>);
69
- return root ? entity.teaqlAttachRoot(root) : entity;
 
 
 
 
 
 
70
  }
71
 
72
  isLoaded(field: string): boolean {
@@ -85,12 +99,19 @@ export class CustomerOrder {
85
  }
86
 
87
  static refer(id: string | number): CustomerOrder {
88
- return new CustomerOrder({ id: String(id) } as Partial<CustomerOrder>);
89
  }
90
 
91
  /** @internal Generated Runtime Module fixed-ID construction capability. */
92
- static teaqlBootstrapNew(id: string | number): CustomerOrder {
93
- return new CustomerOrder().updateId(String(id));
 
 
 
 
 
 
 
94
  }
95
 
96
  markForDeletion(): this {
@@ -100,23 +121,128 @@ export class CustomerOrder {
100
  }
101
 
102
  auditAs(comment: string): this {
103
- new MutationIntent(comment);
104
- (this as any)._comment = comment;
105
  return this;
106
  }
107
 
108
  async save(context: UserContext): Promise<CustomerOrder> {
 
 
 
109
  const service = context.requireResource<TeaQLDataService>("dataService");
110
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
111
- this.teaqlPreflightGraph(context, service, graph);
112
  return this.teaqlSaveWithinGraph(context, service, graph);
 
 
 
 
 
 
 
 
 
 
 
113
  });
114
  }
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  /** @internal Validates and fixes the complete graph before its first mutation. */
117
- teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
118
  if (!parent) new MutationIntent((this as any)._comment);
 
 
119
  const action = (this as any)._action;
 
 
120
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
121
  if (action === "Update" && pending) {
122
  const notLoaded = [{ 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" }]
@@ -124,6 +250,7 @@ export class CustomerOrder {
124
  if (notLoaded) {
125
  throw new CheckException([{
126
  ruleId: "invalid_type",
 
127
  location: ObjectLocation.property(notLoaded.canonical),
128
  message: "Mutation requires a fully loaded entity",
129
  }]);
@@ -134,7 +261,8 @@ export class CustomerOrder {
134
  payload: action === "Update"
135
  ? (this as any)._root.change(this.teaqlEntityKey())
136
  : this.teaqlMutationPayload(),
137
- id: (this as any).id, version: (this as any).version,
 
138
  comment: (this as any)._comment,
139
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
140
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
@@ -143,22 +271,25 @@ export class CustomerOrder {
143
  for (const [index, child] of (this as any)._orderItemList.entries()) {
144
  child.teaqlAttachRoot((this as any)._root);
145
  const currentParent = child.customerOrder;
146
- if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null
147
- ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this);
148
- try { child.teaqlPreflightGraph(context, service, graph, scope); }
 
149
  catch (error) {
150
  if (!(error instanceof CheckException)) throw error;
151
  const prefix = ObjectLocation.property("order_item_list").index(index);
152
- throw new CheckException(error.violations.map(violation => ({
153
  ...violation, location: violation.location.prefixedBy(prefix),
154
- })));
155
  }
156
  }
157
  }
158
 
159
  /** @internal Used by generated relation cascades inside the root graph transaction. */
160
- async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<CustomerOrder> {
161
  if (!parent) new MutationIntent((this as any)._comment);
 
 
162
  const action = (this as any)._action;
163
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
164
  const mutation = {
@@ -166,7 +297,7 @@ export class CustomerOrder {
166
  action: (this as any)._action,
167
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
168
  id: (this as any).id,
169
- version: (this as any).version,
170
  comment: (this as any)._comment
171
  ,ledgerKey: this.teaqlEntityKey()
172
  ,ledgerRoot: (this as any)._root
@@ -178,28 +309,27 @@ export class CustomerOrder {
178
  for (const [index, child] of (this as any)._orderItemList.entries()) {
179
  child.teaqlAttachRoot((this as any)._root);
180
  const currentParent = child.customerOrder;
181
- if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null
182
- ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this);
183
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
184
  catch (error) {
185
  if (!(error instanceof CheckException)) throw error;
186
  const prefix = ObjectLocation.property("order_item_list").index(index);
187
- throw new CheckException(error.violations.map(violation => ({
188
  ...violation, location: violation.location.prefixedBy(prefix),
189
- })));
190
  }
191
  }
192
  return this;
193
  }
194
  const result = await service.executeMutation(request);
195
- for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
196
- if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
197
- }
198
  if (!result.persistedRecord) {
199
  throw new Error("Mutation did not return the authoritative persisted record");
200
  }
201
  const rollbackState = {
202
- payload: this.teaqlMutationPayload(),
203
  ledgerId: (this as any)._ledgerId,
204
  action: (this as any)._action,
205
  loadedFields: new Set((this as any)._loadedFields),
@@ -208,12 +338,16 @@ export class CustomerOrder {
208
  };
209
  const oldKey = this.teaqlEntityKey();
210
  Object.assign(this, result.persistedRecord);
211
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
212
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
213
  const newKey = this.teaqlEntityKey();
214
  (this as any)._root.rekey(oldKey, newKey);
 
 
215
  service.afterGraphRollback(() => {
216
- Object.assign(this, rollbackState.payload);
 
 
 
217
  (this as any)._ledgerId = rollbackState.ledgerId;
218
  (this as any)._action = rollbackState.action;
219
  (this as any)._loadedFields = rollbackState.loadedFields;
@@ -224,24 +358,29 @@ export class CustomerOrder {
224
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
225
  (this as any)._fullyLoaded = false;
226
  if (mutation.action !== "Delete") (this as any)._action = "Update";
 
227
  const scope = request.scopeFor(newKey);
228
  for (const [index, child] of (this as any)._orderItemList.entries()) {
229
  child.teaqlAttachRoot((this as any)._root);
230
  const currentParent = child.customerOrder;
231
- if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null
232
- ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this);
233
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
234
  catch (error) {
235
  if (!(error instanceof CheckException)) throw error;
236
  const prefix = ObjectLocation.property("order_item_list").index(index);
237
- throw new CheckException(error.violations.map(violation => ({
238
  ...violation, location: violation.location.prefixedBy(prefix),
239
- })));
240
  }
241
  }
242
  service.afterGraphCommit(() => {
 
 
243
  (this as any)._root.clearEntity(newKey);
244
- if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
 
245
  });
246
  return this;
247
  }
@@ -258,6 +397,10 @@ export class CustomerOrder {
258
  };
259
  }
260
 
 
 
 
 
261
  updateId(value: string): this {
262
  this.id = value;
263
  this.markLoaded("id");
@@ -279,14 +422,15 @@ export class CustomerOrder {
279
  return this;
280
  }
281
 
282
- updateTotalAmount(value: number): this {
 
283
  this.totalAmount = value;
284
  this.markLoaded("totalAmount");
285
  (this as any)._root.set(this.teaqlEntityKey(), "total_amount", value);
286
  return this;
287
  }
288
 
289
- updateVersion(value: number): this {
290
  this.version = value;
291
  this.markLoaded("version");
292
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
 
1
+ import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { Customer } from './Customer';
3
  import { OrderStatus } from './OrderStatus';
4
  import { OrderItem } from './OrderItem';
5
 
6
+ const teaqlConstruction = Symbol("managed entity construction");
7
+
8
  export class CustomerOrder {
9
  private static teaqlTemporaryId = 0;
10
+ private static readonly teaqlMutationFields = new MutationFieldLayout("CustomerOrder",
11
+ ["id", "customer", "status", "order_number", "order_date", "total_amount", "version"], { id: "immutable_field", version: "immutable_field" });
12
  id?: string;
13
  customer?: Customer | string;
14
  status?: OrderStatus | string;
15
  orderNumber?: string;
16
  orderDate?: string;
17
+ totalAmount?: Decimal;
18
+ version?: EntityVersion;
19
 
20
+ private constructor(init?: Partial<CustomerOrder>, token?: symbol, creation = false) {
21
+ if (token !== teaqlConstruction) throw new EntityCreationError();
22
+ Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false });
23
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
24
+ Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false });
25
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
26
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
27
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --CustomerOrder.teaqlTemporaryId, writable: true, enumerable: false });
28
+ Object.defineProperty(this, "_orderItemList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false });
29
  if (init) {
30
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
31
+ for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key];
32
  delete fields["orderItemList"];
33
  Object.assign(this, fields);
34
  if ((init as any).customer && typeof (init as any).customer === "object") {
 
55
  }
56
  }
57
  const key = this.teaqlEntityKey();
58
+ if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version);
59
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
60
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version);
61
+ LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version,
62
+ creation ? "creationBaseline" : "hydrated");
63
  }
64
 
65
  private teaqlEntityKey(): EntityKey { return { entity: "CustomerOrder", id: (this as any)._ledgerId }; }
66
+ private teaqlAttachRoot(root: EntityRoot, hydration = false): this {
67
  if ((this as any)._root !== root) {
68
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
69
  (this as any)._root = root;
70
  }
71
+ for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root, hydration);
72
  return this;
73
  }
74
 
75
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): CustomerOrder {
76
+ const entity = EntityCreation.hydrated(new CustomerOrder(record as Partial<CustomerOrder>, teaqlConstruction));
77
+ return root ? entity.teaqlAttachRoot(root, true) : entity;
78
+ }
79
+
80
+ toJSON(): Record<string, unknown> {
81
+ const result = Object.fromEntries(Object.entries(this));
82
+ if (this.isLoaded("orderItemList")) result["orderItemList"] = (this as any)._orderItemList;
83
+ return result;
84
  }
85
 
86
  isLoaded(field: string): boolean {
 
99
  }
100
 
101
  static refer(id: string | number): CustomerOrder {
102
+ return CustomerOrder.fromRecord({ id: String(id) });
103
  }
104
 
105
  /** @internal Generated Runtime Module fixed-ID construction capability. */
106
+ static teaqlBootstrapNew(context: UserContext, id: string | number): CustomerOrder {
107
+ return EntityCreation.bootstrap(context, "CustomerOrder", id,
108
+ reserved => new CustomerOrder({id: reserved} as Partial<CustomerOrder>, teaqlConstruction, true));
109
+ }
110
+
111
+ /** @internal Q owns the awaited public creation entry point. */
112
+ static teaqlCreate(context: UserContext): Promise<CustomerOrder> {
113
+ return EntityCreation.create(context, "CustomerOrder",
114
+ reserved => new CustomerOrder({id: reserved} as Partial<CustomerOrder>, teaqlConstruction, true));
115
  }
116
 
117
  markForDeletion(): this {
 
121
  }
122
 
123
  auditAs(comment: string): this {
124
+ (this as any)._comment = new MutationIntent(comment).comment;
 
125
  return this;
126
  }
127
 
128
  async save(context: UserContext): Promise<CustomerOrder> {
129
+ const intent = new MutationIntent((this as any)._comment);
130
+ this.teaqlValidateLoadedIdentities();
131
+ if (!this.teaqlValidateMutationOrigins()) return this;
132
  const service = context.requireResource<TeaQLDataService>("dataService");
133
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
 
134
  return this.teaqlSaveWithinGraph(context, service, graph);
135
+ }, (graph) => {
136
+ this.teaqlPreflightGraph(context, service, graph);
137
+ this.teaqlValidateLoadedIdentities();
138
+ this.teaqlAdmitGraph();
139
+ graph.sealPreparedGraph();
140
+ }, (graph) => {
141
+ this.teaqlValidateLoadedIdentities();
142
+ this.teaqlDiscardRestoredGraph(graph);
143
+ this.teaqlAdmitGraph();
144
+ this.teaqlNormalizeGraph(graph);
145
+ return this.teaqlAdmitGraph();
146
  });
147
  }
148
 
149
+ /** @internal Pure provenance pass before resolving any Context resources. */
150
+ private teaqlValidateMutationOrigins(seen = new Set<object>()): boolean {
151
+ if (seen.has(this)) return false;
152
+ seen.add(this);
153
+ const action = (this as any)._action;
154
+ let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
155
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
156
+ for (const child of (this as any)._orderItemList) pending = child.teaqlValidateMutationOrigins(seen) || pending;
157
+ return pending;
158
+ }
159
+
160
+ /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */
161
+ private teaqlValidateLoadedIdentities(seen = new Set<object>()): void {
162
+ if (seen.has(this)) return;
163
+ seen.add(this);
164
+ LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version);
165
+ for (const [index, child] of (this as any)._orderItemList.entries()) {
166
+ try { child.teaqlValidateLoadedIdentities(seen); }
167
+ catch (error) {
168
+ if (!(error instanceof CheckException)) throw error;
169
+ const prefix = ObjectLocation.property("order_item_list").index(index);
170
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
171
+ }
172
+ }
173
+ }
174
+
175
+ /** @internal Cancel known no-ops across the graph before any derived FK edits. */
176
+ private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
177
+ if (seen.has(this)) return;
178
+ seen.add(this);
179
+ graph.discardRestoredFields(CustomerOrder.teaqlMutationFields,
180
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
181
+ for (const child of (this as any)._orderItemList) child.teaqlDiscardRestoredGraph(graph, seen);
182
+ }
183
+
184
+ /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */
185
+ private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
186
+ if (seen.has(this)) return;
187
+ seen.add(this);
188
+ graph.discardRestoredFields(CustomerOrder.teaqlMutationFields,
189
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
190
+ graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), {
191
+ "customer": "Customer",
192
+ "status": "OrderStatus"
193
+ }, () => ({ ...this.teaqlMutationPayload(),
194
+ __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action,
195
+ __teaql_comment: (this as any)._comment,
196
+ __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()},
197
+ "order_item_list": graph.sourceMembers((this as any)._orderItemList)
198
+ }));
199
+ for (const child of (this as any)._orderItemList) {
200
+ child.teaqlAttachRoot((this as any)._root);
201
+ const currentParent = child.customerOrder;
202
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
203
+ && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null
204
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this);
205
+ child.teaqlNormalizeGraph(graph, seen);
206
+ }
207
+ }
208
+
209
+ /** @internal Whole-input version/completeness pass; does not use Context or Fix. */
210
+ private teaqlAdmitGraph(seen = new Set<object>()): boolean {
211
+ if (seen.has(this)) return false;
212
+ seen.add(this);
213
+ const action = (this as any)._action;
214
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
215
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
216
+ LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey());
217
+ CustomerOrder.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update");
218
+ if (pending) {
219
+ nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion);
220
+ if (action === "Update") {
221
+ const notLoaded = [{ 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(field => !this.isLoaded(field.member));
222
+ if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "CustomerOrder", location: ObjectLocation.property(notLoaded.canonical),
223
+ message: "Mutation requires a fully loaded entity"}]);
224
+ }
225
+ }
226
+ let graphPending = pending;
227
+ for (const [index, child] of (this as any)._orderItemList.entries()) {
228
+ try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; }
229
+ catch (error) {
230
+ if (!(error instanceof CheckException)) throw error;
231
+ const prefix = ObjectLocation.property("order_item_list").index(index);
232
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
233
+ }
234
+ }
235
+ return graphPending;
236
+ }
237
+
238
  /** @internal Validates and fixes the complete graph before its first mutation. */
239
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): void {
240
  if (!parent) new MutationIntent((this as any)._comment);
241
+ if (seen.has(this)) return;
242
+ seen.add(this);
243
  const action = (this as any)._action;
244
+ graph.discardRestoredFields(CustomerOrder.teaqlMutationFields,
245
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
246
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
247
  if (action === "Update" && pending) {
248
  const notLoaded = [{ 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" }]
 
250
  if (notLoaded) {
251
  throw new CheckException([{
252
  ruleId: "invalid_type",
253
+ entityType: "CustomerOrder",
254
  location: ObjectLocation.property(notLoaded.canonical),
255
  message: "Mutation requires a fully loaded entity",
256
  }]);
 
261
  payload: action === "Update"
262
  ? (this as any)._root.change(this.teaqlEntityKey())
263
  : this.teaqlMutationPayload(),
264
+ id: (this as any).id,
265
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
266
  comment: (this as any)._comment,
267
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
268
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
 
271
  for (const [index, child] of (this as any)._orderItemList.entries()) {
272
  child.teaqlAttachRoot((this as any)._root);
273
  const currentParent = child.customerOrder;
274
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
275
+ && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null
276
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this);
277
+ try { child.teaqlPreflightGraph(context, service, graph, scope, seen); }
278
  catch (error) {
279
  if (!(error instanceof CheckException)) throw error;
280
  const prefix = ObjectLocation.property("order_item_list").index(index);
281
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
282
  ...violation, location: violation.location.prefixedBy(prefix),
283
+ }))));
284
  }
285
  }
286
  }
287
 
288
  /** @internal Used by generated relation cascades inside the root graph transaction. */
289
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): Promise<CustomerOrder> {
290
  if (!parent) new MutationIntent((this as any)._comment);
291
+ if (seen.has(this)) return this;
292
+ seen.add(this);
293
  const action = (this as any)._action;
294
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
295
  const mutation = {
 
297
  action: (this as any)._action,
298
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
299
  id: (this as any).id,
300
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
301
  comment: (this as any)._comment
302
  ,ledgerKey: this.teaqlEntityKey()
303
  ,ledgerRoot: (this as any)._root
 
309
  for (const [index, child] of (this as any)._orderItemList.entries()) {
310
  child.teaqlAttachRoot((this as any)._root);
311
  const currentParent = child.customerOrder;
312
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
313
+ && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null
314
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this);
315
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
316
  catch (error) {
317
  if (!(error instanceof CheckException)) throw error;
318
  const prefix = ObjectLocation.property("order_item_list").index(index);
319
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
320
  ...violation, location: violation.location.prefixedBy(prefix),
321
+ }))));
322
  }
323
  }
324
  return this;
325
  }
326
  const result = await service.executeMutation(request);
327
+ graph.validatePreparedSources();
 
 
328
  if (!result.persistedRecord) {
329
  throw new Error("Mutation did not return the authoritative persisted record");
330
  }
331
  const rollbackState = {
332
+ ownProperties: Object.getOwnPropertyDescriptors(this),
333
  ledgerId: (this as any)._ledgerId,
334
  action: (this as any)._action,
335
  loadedFields: new Set((this as any)._loadedFields),
 
338
  };
339
  const oldKey = this.teaqlEntityKey();
340
  Object.assign(this, result.persistedRecord);
 
341
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
342
  const newKey = this.teaqlEntityKey();
343
  (this as any)._root.rekey(oldKey, newKey);
344
+ const committedSnapshot = this.teaqlScalarSnapshot();
345
+ const activeScope = request.scopeFor(newKey);
346
  service.afterGraphRollback(() => {
347
+ for (const name of Object.getOwnPropertyNames(this)) {
348
+ if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name];
349
+ }
350
+ Object.defineProperties(this, rollbackState.ownProperties);
351
  (this as any)._ledgerId = rollbackState.ledgerId;
352
  (this as any)._action = rollbackState.action;
353
  (this as any)._loadedFields = rollbackState.loadedFields;
 
358
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
359
  (this as any)._fullyLoaded = false;
360
  if (mutation.action !== "Delete") (this as any)._action = "Update";
361
+ graph.acceptPreparedResult((this as any)._root, oldKey, newKey);
362
  const scope = request.scopeFor(newKey);
363
  for (const [index, child] of (this as any)._orderItemList.entries()) {
364
  child.teaqlAttachRoot((this as any)._root);
365
  const currentParent = child.customerOrder;
366
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
367
+ && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null
368
+ ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this);
369
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
370
  catch (error) {
371
  if (!(error instanceof CheckException)) throw error;
372
  const prefix = ObjectLocation.property("order_item_list").index(index);
373
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
374
  ...violation, location: violation.location.prefixedBy(prefix),
375
+ }))));
376
  }
377
  }
378
  service.afterGraphCommit(() => {
379
+ graph.validatePreparedSources();
380
+ LoadedScalarSnapshot.restoreFor(this, committedSnapshot);
381
  (this as any)._root.clearEntity(newKey);
382
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version);
383
+ graph.finishPreparedCommit((this as any)._root, newKey);
384
  });
385
  return this;
386
  }
 
397
  };
398
  }
399
 
400
+ private teaqlScalarSnapshot(): LoadedScalarSnapshot {
401
+ return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version);
402
+ }
403
+
404
  updateId(value: string): this {
405
  this.id = value;
406
  this.markLoaded("id");
 
422
  return this;
423
  }
424
 
425
+ updateTotalAmount(value: Decimal): this {
426
+ if (value != null) value = decimal(value);
427
  this.totalAmount = value;
428
  this.markLoaded("totalAmount");
429
  (this as any)._root.set(this.teaqlEntityKey(), "total_amount", value);
430
  return this;
431
  }
432
 
433
+ updateVersion(value: EntityVersion): this {
434
  this.version = value;
435
  this.markLoaded("version");
436
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts CHANGED
@@ -1,24 +1,34 @@
1
- import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { CustomerOrder } from './CustomerOrder';
3
 
 
 
4
  export class OrderItem {
5
  private static teaqlTemporaryId = 0;
 
 
6
  id?: string;
7
  customerOrder?: CustomerOrder | string;
8
  productName?: string;
9
  quantity?: number;
10
- unitPrice?: number;
11
- version?: number;
 
 
 
 
 
12
 
13
- constructor(init?: Partial<OrderItem>) {
14
- Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
15
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
16
- Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
17
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
18
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
19
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderItem.teaqlTemporaryId, writable: true, enumerable: false });
20
  if (init) {
21
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
 
22
  Object.assign(this, fields);
23
  if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") {
24
  this.customerOrder = (init as any).customerOrder instanceof CustomerOrder
@@ -28,13 +38,15 @@ export class OrderItem {
28
  }
29
  }
30
  const key = this.teaqlEntityKey();
 
31
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
32
- else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
33
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
 
34
  }
35
 
36
  private teaqlEntityKey(): EntityKey { return { entity: "OrderItem", id: (this as any)._ledgerId }; }
37
- private teaqlAttachRoot(root: EntityRoot): this {
38
  if ((this as any)._root !== root) {
39
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
40
  (this as any)._root = root;
@@ -43,8 +55,17 @@ export class OrderItem {
43
  }
44
 
45
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): OrderItem {
46
- const entity = new OrderItem(record as Partial<OrderItem>);
47
- return root ? entity.teaqlAttachRoot(root) : entity;
 
 
 
 
 
 
 
 
 
48
  }
49
 
50
  isLoaded(field: string): boolean {
@@ -63,12 +84,19 @@ export class OrderItem {
63
  }
64
 
65
  static refer(id: string | number): OrderItem {
66
- return new OrderItem({ id: String(id) } as Partial<OrderItem>);
67
  }
68
 
69
  /** @internal Generated Runtime Module fixed-ID construction capability. */
70
- static teaqlBootstrapNew(id: string | number): OrderItem {
71
- return new OrderItem().updateId(String(id));
 
 
 
 
 
 
 
72
  }
73
 
74
  markForDeletion(): this {
@@ -78,23 +106,100 @@ export class OrderItem {
78
  }
79
 
80
  auditAs(comment: string): this {
81
- new MutationIntent(comment);
82
- (this as any)._comment = comment;
83
  return this;
84
  }
85
 
86
  async save(context: UserContext): Promise<OrderItem> {
 
 
 
87
  const service = context.requireResource<TeaQLDataService>("dataService");
88
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
89
- this.teaqlPreflightGraph(context, service, graph);
90
  return this.teaqlSaveWithinGraph(context, service, graph);
 
 
 
 
 
 
 
 
 
 
 
91
  });
92
  }
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  /** @internal Validates and fixes the complete graph before its first mutation. */
95
- teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
96
  if (!parent) new MutationIntent((this as any)._comment);
 
 
97
  const action = (this as any)._action;
 
 
98
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
99
  if (action === "Update" && pending) {
100
  const notLoaded = [{ 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" }]
@@ -102,6 +207,7 @@ export class OrderItem {
102
  if (notLoaded) {
103
  throw new CheckException([{
104
  ruleId: "invalid_type",
 
105
  location: ObjectLocation.property(notLoaded.canonical),
106
  message: "Mutation requires a fully loaded entity",
107
  }]);
@@ -112,7 +218,8 @@ export class OrderItem {
112
  payload: action === "Update"
113
  ? (this as any)._root.change(this.teaqlEntityKey())
114
  : this.teaqlMutationPayload(),
115
- id: (this as any).id, version: (this as any).version,
 
116
  comment: (this as any)._comment,
117
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
118
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
@@ -121,8 +228,10 @@ export class OrderItem {
121
  }
122
 
123
  /** @internal Used by generated relation cascades inside the root graph transaction. */
124
- async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<OrderItem> {
125
  if (!parent) new MutationIntent((this as any)._comment);
 
 
126
  const action = (this as any)._action;
127
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
128
  const mutation = {
@@ -130,7 +239,7 @@ export class OrderItem {
130
  action: (this as any)._action,
131
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
132
  id: (this as any).id,
133
- version: (this as any).version,
134
  comment: (this as any)._comment
135
  ,ledgerKey: this.teaqlEntityKey()
136
  ,ledgerRoot: (this as any)._root
@@ -142,14 +251,12 @@ export class OrderItem {
142
  return this;
143
  }
144
  const result = await service.executeMutation(request);
145
- for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
146
- if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
147
- }
148
  if (!result.persistedRecord) {
149
  throw new Error("Mutation did not return the authoritative persisted record");
150
  }
151
  const rollbackState = {
152
- payload: this.teaqlMutationPayload(),
153
  ledgerId: (this as any)._ledgerId,
154
  action: (this as any)._action,
155
  loadedFields: new Set((this as any)._loadedFields),
@@ -158,12 +265,16 @@ export class OrderItem {
158
  };
159
  const oldKey = this.teaqlEntityKey();
160
  Object.assign(this, result.persistedRecord);
161
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
162
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
163
  const newKey = this.teaqlEntityKey();
164
  (this as any)._root.rekey(oldKey, newKey);
 
 
165
  service.afterGraphRollback(() => {
166
- Object.assign(this, rollbackState.payload);
 
 
 
167
  (this as any)._ledgerId = rollbackState.ledgerId;
168
  (this as any)._action = rollbackState.action;
169
  (this as any)._loadedFields = rollbackState.loadedFields;
@@ -174,10 +285,14 @@ export class OrderItem {
174
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
175
  (this as any)._fullyLoaded = false;
176
  if (mutation.action !== "Delete") (this as any)._action = "Update";
 
177
  const scope = request.scopeFor(newKey);
178
  service.afterGraphCommit(() => {
 
 
179
  (this as any)._root.clearEntity(newKey);
180
- if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
 
181
  });
182
  return this;
183
  }
@@ -193,6 +308,10 @@ export class OrderItem {
193
  };
194
  }
195
 
 
 
 
 
196
  updateId(value: string): this {
197
  this.id = value;
198
  this.markLoaded("id");
@@ -214,14 +333,15 @@ export class OrderItem {
214
  return this;
215
  }
216
 
217
- updateUnitPrice(value: number): this {
 
218
  this.unitPrice = value;
219
  this.markLoaded("unitPrice");
220
  (this as any)._root.set(this.teaqlEntityKey(), "unit_price", value);
221
  return this;
222
  }
223
 
224
- updateVersion(value: number): this {
225
  this.version = value;
226
  this.markLoaded("version");
227
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
 
1
+ import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { CustomerOrder } from './CustomerOrder';
3
 
4
+ const teaqlConstruction = Symbol("managed entity construction");
5
+
6
  export class OrderItem {
7
  private static teaqlTemporaryId = 0;
8
+ private static readonly teaqlMutationFields = new MutationFieldLayout("OrderItem",
9
+ ["id", "customer_order", "product_name", "quantity", "unit_price", "version"], { id: "immutable_field", version: "immutable_field" });
10
  id?: string;
11
  customerOrder?: CustomerOrder | string;
12
  productName?: string;
13
  quantity?: number;
14
+ unitPrice?: Decimal;
15
+ version?: EntityVersion;
16
+
17
+ private constructor(init?: Partial<OrderItem>, token?: symbol, creation = false) {
18
+ if (token !== teaqlConstruction) throw new EntityCreationError();
19
+ { const error = integer32Error(init?.quantity, "OrderItem", "quantity"); if (error) throw error; }
20
+
21
 
22
+
23
+ Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false });
24
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
25
+ Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false });
26
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
27
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
28
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderItem.teaqlTemporaryId, writable: true, enumerable: false });
29
  if (init) {
30
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
31
+ for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key];
32
  Object.assign(this, fields);
33
  if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") {
34
  this.customerOrder = (init as any).customerOrder instanceof CustomerOrder
 
38
  }
39
  }
40
  const key = this.teaqlEntityKey();
41
+ if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version);
42
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
43
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version);
44
+ LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version,
45
+ creation ? "creationBaseline" : "hydrated");
46
  }
47
 
48
  private teaqlEntityKey(): EntityKey { return { entity: "OrderItem", id: (this as any)._ledgerId }; }
49
+ private teaqlAttachRoot(root: EntityRoot, hydration = false): this {
50
  if ((this as any)._root !== root) {
51
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
52
  (this as any)._root = root;
 
55
  }
56
 
57
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): OrderItem {
58
+ const entity = EntityCreation.hydrated(new OrderItem(record as Partial<OrderItem>, teaqlConstruction));
59
+ return root ? entity.teaqlAttachRoot(root, true) : entity;
60
+ }
61
+
62
+ toJSON(): Record<string, unknown> {
63
+ { const error = integer32Error(this.quantity, "OrderItem", "quantity"); if (error) throw error; }
64
+
65
+
66
+
67
+ const result = Object.fromEntries(Object.entries(this));
68
+ return result;
69
  }
70
 
71
  isLoaded(field: string): boolean {
 
84
  }
85
 
86
  static refer(id: string | number): OrderItem {
87
+ return OrderItem.fromRecord({ id: String(id) });
88
  }
89
 
90
  /** @internal Generated Runtime Module fixed-ID construction capability. */
91
+ static teaqlBootstrapNew(context: UserContext, id: string | number): OrderItem {
92
+ return EntityCreation.bootstrap(context, "OrderItem", id,
93
+ reserved => new OrderItem({id: reserved} as Partial<OrderItem>, teaqlConstruction, true));
94
+ }
95
+
96
+ /** @internal Q owns the awaited public creation entry point. */
97
+ static teaqlCreate(context: UserContext): Promise<OrderItem> {
98
+ return EntityCreation.create(context, "OrderItem",
99
+ reserved => new OrderItem({id: reserved} as Partial<OrderItem>, teaqlConstruction, true));
100
  }
101
 
102
  markForDeletion(): this {
 
106
  }
107
 
108
  auditAs(comment: string): this {
109
+ (this as any)._comment = new MutationIntent(comment).comment;
 
110
  return this;
111
  }
112
 
113
  async save(context: UserContext): Promise<OrderItem> {
114
+ const intent = new MutationIntent((this as any)._comment);
115
+ this.teaqlValidateLoadedIdentities();
116
+ if (!this.teaqlValidateMutationOrigins()) return this;
117
  const service = context.requireResource<TeaQLDataService>("dataService");
118
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
 
119
  return this.teaqlSaveWithinGraph(context, service, graph);
120
+ }, (graph) => {
121
+ this.teaqlPreflightGraph(context, service, graph);
122
+ this.teaqlValidateLoadedIdentities();
123
+ this.teaqlAdmitGraph();
124
+ graph.sealPreparedGraph();
125
+ }, (graph) => {
126
+ this.teaqlValidateLoadedIdentities();
127
+ this.teaqlDiscardRestoredGraph(graph);
128
+ this.teaqlAdmitGraph();
129
+ this.teaqlNormalizeGraph(graph);
130
+ return this.teaqlAdmitGraph();
131
  });
132
  }
133
 
134
+ /** @internal Pure provenance pass before resolving any Context resources. */
135
+ private teaqlValidateMutationOrigins(seen = new Set<object>()): boolean {
136
+ if (seen.has(this)) return false;
137
+ seen.add(this);
138
+ const action = (this as any)._action;
139
+ let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
140
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
141
+ return pending;
142
+ }
143
+
144
+ /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */
145
+ private teaqlValidateLoadedIdentities(seen = new Set<object>()): void {
146
+ if (seen.has(this)) return;
147
+ seen.add(this);
148
+ LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version);
149
+ }
150
+
151
+ /** @internal Cancel known no-ops across the graph before any derived FK edits. */
152
+ private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
153
+ if (seen.has(this)) return;
154
+ seen.add(this);
155
+ graph.discardRestoredFields(OrderItem.teaqlMutationFields,
156
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
157
+ }
158
+
159
+ /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */
160
+ private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
161
+ if (seen.has(this)) return;
162
+ seen.add(this);
163
+ graph.discardRestoredFields(OrderItem.teaqlMutationFields,
164
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
165
+ graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), {
166
+ "customer_order": "CustomerOrder"
167
+ }, () => ({ ...this.teaqlMutationPayload(),
168
+ __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action,
169
+ __teaql_comment: (this as any)._comment,
170
+ __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()},
171
+ }));
172
+ }
173
+
174
+ /** @internal Whole-input version/completeness pass; does not use Context or Fix. */
175
+ private teaqlAdmitGraph(seen = new Set<object>()): boolean {
176
+ if (seen.has(this)) return false;
177
+ seen.add(this);
178
+ const action = (this as any)._action;
179
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
180
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
181
+ LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey());
182
+ OrderItem.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update");
183
+ if (pending) {
184
+ nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion);
185
+ if (action === "Update") {
186
+ const notLoaded = [{ 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(field => !this.isLoaded(field.member));
187
+ if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderItem", location: ObjectLocation.property(notLoaded.canonical),
188
+ message: "Mutation requires a fully loaded entity"}]);
189
+ }
190
+ }
191
+ let graphPending = pending;
192
+ return graphPending;
193
+ }
194
+
195
  /** @internal Validates and fixes the complete graph before its first mutation. */
196
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): void {
197
  if (!parent) new MutationIntent((this as any)._comment);
198
+ if (seen.has(this)) return;
199
+ seen.add(this);
200
  const action = (this as any)._action;
201
+ graph.discardRestoredFields(OrderItem.teaqlMutationFields,
202
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
203
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
204
  if (action === "Update" && pending) {
205
  const notLoaded = [{ 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" }]
 
207
  if (notLoaded) {
208
  throw new CheckException([{
209
  ruleId: "invalid_type",
210
+ entityType: "OrderItem",
211
  location: ObjectLocation.property(notLoaded.canonical),
212
  message: "Mutation requires a fully loaded entity",
213
  }]);
 
218
  payload: action === "Update"
219
  ? (this as any)._root.change(this.teaqlEntityKey())
220
  : this.teaqlMutationPayload(),
221
+ id: (this as any).id,
222
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
223
  comment: (this as any)._comment,
224
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
225
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
 
228
  }
229
 
230
  /** @internal Used by generated relation cascades inside the root graph transaction. */
231
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): Promise<OrderItem> {
232
  if (!parent) new MutationIntent((this as any)._comment);
233
+ if (seen.has(this)) return this;
234
+ seen.add(this);
235
  const action = (this as any)._action;
236
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
237
  const mutation = {
 
239
  action: (this as any)._action,
240
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
241
  id: (this as any).id,
242
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
243
  comment: (this as any)._comment
244
  ,ledgerKey: this.teaqlEntityKey()
245
  ,ledgerRoot: (this as any)._root
 
251
  return this;
252
  }
253
  const result = await service.executeMutation(request);
254
+ graph.validatePreparedSources();
 
 
255
  if (!result.persistedRecord) {
256
  throw new Error("Mutation did not return the authoritative persisted record");
257
  }
258
  const rollbackState = {
259
+ ownProperties: Object.getOwnPropertyDescriptors(this),
260
  ledgerId: (this as any)._ledgerId,
261
  action: (this as any)._action,
262
  loadedFields: new Set((this as any)._loadedFields),
 
265
  };
266
  const oldKey = this.teaqlEntityKey();
267
  Object.assign(this, result.persistedRecord);
 
268
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
269
  const newKey = this.teaqlEntityKey();
270
  (this as any)._root.rekey(oldKey, newKey);
271
+ const committedSnapshot = this.teaqlScalarSnapshot();
272
+ const activeScope = request.scopeFor(newKey);
273
  service.afterGraphRollback(() => {
274
+ for (const name of Object.getOwnPropertyNames(this)) {
275
+ if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name];
276
+ }
277
+ Object.defineProperties(this, rollbackState.ownProperties);
278
  (this as any)._ledgerId = rollbackState.ledgerId;
279
  (this as any)._action = rollbackState.action;
280
  (this as any)._loadedFields = rollbackState.loadedFields;
 
285
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
286
  (this as any)._fullyLoaded = false;
287
  if (mutation.action !== "Delete") (this as any)._action = "Update";
288
+ graph.acceptPreparedResult((this as any)._root, oldKey, newKey);
289
  const scope = request.scopeFor(newKey);
290
  service.afterGraphCommit(() => {
291
+ graph.validatePreparedSources();
292
+ LoadedScalarSnapshot.restoreFor(this, committedSnapshot);
293
  (this as any)._root.clearEntity(newKey);
294
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version);
295
+ graph.finishPreparedCommit((this as any)._root, newKey);
296
  });
297
  return this;
298
  }
 
308
  };
309
  }
310
 
311
+ private teaqlScalarSnapshot(): LoadedScalarSnapshot {
312
+ return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version);
313
+ }
314
+
315
  updateId(value: string): this {
316
  this.id = value;
317
  this.markLoaded("id");
 
333
  return this;
334
  }
335
 
336
+ updateUnitPrice(value: Decimal): this {
337
+ if (value != null) value = decimal(value);
338
  this.unitPrice = value;
339
  this.markLoaded("unitPrice");
340
  (this as any)._root.set(this.teaqlEntityKey(), "unit_price", value);
341
  return this;
342
  }
343
 
344
+ updateVersion(value: EntityVersion): this {
345
  this.version = value;
346
  this.markLoaded("version");
347
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts CHANGED
@@ -1,27 +1,36 @@
1
- import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { Platform } from './Platform';
3
  import { CustomerOrder } from './CustomerOrder';
4
 
 
 
5
  export class OrderStatus {
6
  private static teaqlTemporaryId = 0;
 
 
7
  platform?: Platform | string;
8
  id?: string;
9
  name?: string;
10
  code?: string;
11
  color?: string;
12
  displayOrder?: number;
13
- version?: number;
 
 
 
 
 
14
 
15
- constructor(init?: Partial<OrderStatus>) {
16
- Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
17
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
18
- Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
19
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
20
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
21
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderStatus.teaqlTemporaryId, writable: true, enumerable: false });
22
- Object.defineProperty(this, "_customerOrderList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false });
23
  if (init) {
24
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
 
25
  delete fields["customerOrderList"];
26
  Object.assign(this, fields);
27
  if ((init as any).platform && typeof (init as any).platform === "object") {
@@ -42,24 +51,35 @@ export class OrderStatus {
42
  }
43
  }
44
  const key = this.teaqlEntityKey();
 
45
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
46
- else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
47
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
 
48
  }
49
 
50
  private teaqlEntityKey(): EntityKey { return { entity: "OrderStatus", id: (this as any)._ledgerId }; }
51
- private teaqlAttachRoot(root: EntityRoot): this {
52
  if ((this as any)._root !== root) {
53
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
54
  (this as any)._root = root;
55
  }
56
- for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root);
57
  return this;
58
  }
59
 
60
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): OrderStatus {
61
- const entity = new OrderStatus(record as Partial<OrderStatus>);
62
- return root ? entity.teaqlAttachRoot(root) : entity;
 
 
 
 
 
 
 
 
 
63
  }
64
 
65
  isLoaded(field: string): boolean {
@@ -78,12 +98,19 @@ export class OrderStatus {
78
  }
79
 
80
  static refer(id: string | number): OrderStatus {
81
- return new OrderStatus({ id: String(id) } as Partial<OrderStatus>);
82
  }
83
 
84
  /** @internal Generated Runtime Module fixed-ID construction capability. */
85
- static teaqlBootstrapNew(id: string | number): OrderStatus {
86
- return new OrderStatus().updateId(String(id));
 
 
 
 
 
 
 
87
  }
88
 
89
  markForDeletion(): this {
@@ -93,23 +120,127 @@ export class OrderStatus {
93
  }
94
 
95
  auditAs(comment: string): this {
96
- new MutationIntent(comment);
97
- (this as any)._comment = comment;
98
  return this;
99
  }
100
 
101
  async save(context: UserContext): Promise<OrderStatus> {
 
 
 
102
  const service = context.requireResource<TeaQLDataService>("dataService");
103
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
104
- this.teaqlPreflightGraph(context, service, graph);
105
  return this.teaqlSaveWithinGraph(context, service, graph);
 
 
 
 
 
 
 
 
 
 
 
106
  });
107
  }
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  /** @internal Validates and fixes the complete graph before its first mutation. */
110
- teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
111
  if (!parent) new MutationIntent((this as any)._comment);
 
 
112
  const action = (this as any)._action;
 
 
113
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
114
  if (action === "Update" && pending) {
115
  const notLoaded = [{ 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" }]
@@ -117,6 +248,7 @@ export class OrderStatus {
117
  if (notLoaded) {
118
  throw new CheckException([{
119
  ruleId: "invalid_type",
 
120
  location: ObjectLocation.property(notLoaded.canonical),
121
  message: "Mutation requires a fully loaded entity",
122
  }]);
@@ -127,7 +259,8 @@ export class OrderStatus {
127
  payload: action === "Update"
128
  ? (this as any)._root.change(this.teaqlEntityKey())
129
  : this.teaqlMutationPayload(),
130
- id: (this as any).id, version: (this as any).version,
 
131
  comment: (this as any)._comment,
132
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
133
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
@@ -136,22 +269,25 @@ export class OrderStatus {
136
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
137
  child.teaqlAttachRoot((this as any)._root);
138
  const currentParent = child.status;
139
- if (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null
140
- ? currentParent.id : currentParent) !== this.id) child.updateStatus(this);
141
- try { child.teaqlPreflightGraph(context, service, graph, scope); }
 
142
  catch (error) {
143
  if (!(error instanceof CheckException)) throw error;
144
  const prefix = ObjectLocation.property("customer_order_list").index(index);
145
- throw new CheckException(error.violations.map(violation => ({
146
  ...violation, location: violation.location.prefixedBy(prefix),
147
- })));
148
  }
149
  }
150
  }
151
 
152
  /** @internal Used by generated relation cascades inside the root graph transaction. */
153
- async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<OrderStatus> {
154
  if (!parent) new MutationIntent((this as any)._comment);
 
 
155
  const action = (this as any)._action;
156
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
157
  const mutation = {
@@ -159,7 +295,7 @@ export class OrderStatus {
159
  action: (this as any)._action,
160
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
161
  id: (this as any).id,
162
- version: (this as any).version,
163
  comment: (this as any)._comment
164
  ,ledgerKey: this.teaqlEntityKey()
165
  ,ledgerRoot: (this as any)._root
@@ -171,28 +307,27 @@ export class OrderStatus {
171
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
172
  child.teaqlAttachRoot((this as any)._root);
173
  const currentParent = child.status;
174
- if (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null
175
- ? currentParent.id : currentParent) !== this.id) child.updateStatus(this);
176
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
177
  catch (error) {
178
  if (!(error instanceof CheckException)) throw error;
179
  const prefix = ObjectLocation.property("customer_order_list").index(index);
180
- throw new CheckException(error.violations.map(violation => ({
181
  ...violation, location: violation.location.prefixedBy(prefix),
182
- })));
183
  }
184
  }
185
  return this;
186
  }
187
  const result = await service.executeMutation(request);
188
- for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
189
- if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
190
- }
191
  if (!result.persistedRecord) {
192
  throw new Error("Mutation did not return the authoritative persisted record");
193
  }
194
  const rollbackState = {
195
- payload: this.teaqlMutationPayload(),
196
  ledgerId: (this as any)._ledgerId,
197
  action: (this as any)._action,
198
  loadedFields: new Set((this as any)._loadedFields),
@@ -201,12 +336,16 @@ export class OrderStatus {
201
  };
202
  const oldKey = this.teaqlEntityKey();
203
  Object.assign(this, result.persistedRecord);
204
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
205
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
206
  const newKey = this.teaqlEntityKey();
207
  (this as any)._root.rekey(oldKey, newKey);
 
 
208
  service.afterGraphRollback(() => {
209
- Object.assign(this, rollbackState.payload);
 
 
 
210
  (this as any)._ledgerId = rollbackState.ledgerId;
211
  (this as any)._action = rollbackState.action;
212
  (this as any)._loadedFields = rollbackState.loadedFields;
@@ -217,24 +356,29 @@ export class OrderStatus {
217
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
218
  (this as any)._fullyLoaded = false;
219
  if (mutation.action !== "Delete") (this as any)._action = "Update";
 
220
  const scope = request.scopeFor(newKey);
221
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
222
  child.teaqlAttachRoot((this as any)._root);
223
  const currentParent = child.status;
224
- if (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null
225
- ? currentParent.id : currentParent) !== this.id) child.updateStatus(this);
226
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
227
  catch (error) {
228
  if (!(error instanceof CheckException)) throw error;
229
  const prefix = ObjectLocation.property("customer_order_list").index(index);
230
- throw new CheckException(error.violations.map(violation => ({
231
  ...violation, location: violation.location.prefixedBy(prefix),
232
- })));
233
  }
234
  }
235
  service.afterGraphCommit(() => {
 
 
236
  (this as any)._root.clearEntity(newKey);
237
- if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
 
238
  });
239
  return this;
240
  }
@@ -251,6 +395,10 @@ export class OrderStatus {
251
  };
252
  }
253
 
 
 
 
 
254
  updateId(value: string): this {
255
  this.id = value;
256
  this.markLoaded("id");
@@ -286,7 +434,7 @@ export class OrderStatus {
286
  return this;
287
  }
288
 
289
- updateVersion(value: number): this {
290
  this.version = value;
291
  this.markLoaded("version");
292
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
 
1
+ import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { Platform } from './Platform';
3
  import { CustomerOrder } from './CustomerOrder';
4
 
5
+ const teaqlConstruction = Symbol("managed entity construction");
6
+
7
  export class OrderStatus {
8
  private static teaqlTemporaryId = 0;
9
+ private static readonly teaqlMutationFields = new MutationFieldLayout("OrderStatus",
10
+ ["platform", "id", "name", "code", "color", "display_order", "version"], { id: "immutable_field", version: "immutable_field" });
11
  platform?: Platform | string;
12
  id?: string;
13
  name?: string;
14
  code?: string;
15
  color?: string;
16
  displayOrder?: number;
17
+ version?: EntityVersion;
18
+
19
+ private constructor(init?: Partial<OrderStatus>, token?: symbol, creation = false) {
20
+ if (token !== teaqlConstruction) throw new EntityCreationError();
21
+ { const error = integer32Error(init?.displayOrder, "OrderStatus", "display_order"); if (error) throw error; }
22
+
23
 
24
+ Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false });
 
25
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
26
+ Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false });
27
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
28
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
29
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderStatus.teaqlTemporaryId, writable: true, enumerable: false });
30
+ Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false });
31
  if (init) {
32
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
33
+ for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key];
34
  delete fields["customerOrderList"];
35
  Object.assign(this, fields);
36
  if ((init as any).platform && typeof (init as any).platform === "object") {
 
51
  }
52
  }
53
  const key = this.teaqlEntityKey();
54
+ if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version);
55
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
56
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version);
57
+ LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version,
58
+ creation ? "creationBaseline" : "hydrated");
59
  }
60
 
61
  private teaqlEntityKey(): EntityKey { return { entity: "OrderStatus", id: (this as any)._ledgerId }; }
62
+ private teaqlAttachRoot(root: EntityRoot, hydration = false): this {
63
  if ((this as any)._root !== root) {
64
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
65
  (this as any)._root = root;
66
  }
67
+ for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration);
68
  return this;
69
  }
70
 
71
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): OrderStatus {
72
+ const entity = EntityCreation.hydrated(new OrderStatus(record as Partial<OrderStatus>, teaqlConstruction));
73
+ return root ? entity.teaqlAttachRoot(root, true) : entity;
74
+ }
75
+
76
+ toJSON(): Record<string, unknown> {
77
+ { const error = integer32Error(this.displayOrder, "OrderStatus", "display_order"); if (error) throw error; }
78
+
79
+
80
+ const result = Object.fromEntries(Object.entries(this));
81
+ if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList;
82
+ return result;
83
  }
84
 
85
  isLoaded(field: string): boolean {
 
98
  }
99
 
100
  static refer(id: string | number): OrderStatus {
101
+ return OrderStatus.fromRecord({ id: String(id) });
102
  }
103
 
104
  /** @internal Generated Runtime Module fixed-ID construction capability. */
105
+ static teaqlBootstrapNew(context: UserContext, id: string | number): OrderStatus {
106
+ return EntityCreation.bootstrap(context, "OrderStatus", id,
107
+ reserved => new OrderStatus({id: reserved} as Partial<OrderStatus>, teaqlConstruction, true));
108
+ }
109
+
110
+ /** @internal Q owns the awaited public creation entry point. */
111
+ static teaqlCreate(context: UserContext): Promise<OrderStatus> {
112
+ return EntityCreation.create(context, "OrderStatus",
113
+ reserved => new OrderStatus({id: reserved} as Partial<OrderStatus>, teaqlConstruction, true));
114
  }
115
 
116
  markForDeletion(): this {
 
120
  }
121
 
122
  auditAs(comment: string): this {
123
+ (this as any)._comment = new MutationIntent(comment).comment;
 
124
  return this;
125
  }
126
 
127
  async save(context: UserContext): Promise<OrderStatus> {
128
+ const intent = new MutationIntent((this as any)._comment);
129
+ this.teaqlValidateLoadedIdentities();
130
+ if (!this.teaqlValidateMutationOrigins()) return this;
131
  const service = context.requireResource<TeaQLDataService>("dataService");
132
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
 
133
  return this.teaqlSaveWithinGraph(context, service, graph);
134
+ }, (graph) => {
135
+ this.teaqlPreflightGraph(context, service, graph);
136
+ this.teaqlValidateLoadedIdentities();
137
+ this.teaqlAdmitGraph();
138
+ graph.sealPreparedGraph();
139
+ }, (graph) => {
140
+ this.teaqlValidateLoadedIdentities();
141
+ this.teaqlDiscardRestoredGraph(graph);
142
+ this.teaqlAdmitGraph();
143
+ this.teaqlNormalizeGraph(graph);
144
+ return this.teaqlAdmitGraph();
145
  });
146
  }
147
 
148
+ /** @internal Pure provenance pass before resolving any Context resources. */
149
+ private teaqlValidateMutationOrigins(seen = new Set<object>()): boolean {
150
+ if (seen.has(this)) return false;
151
+ seen.add(this);
152
+ const action = (this as any)._action;
153
+ let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
154
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
155
+ for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending;
156
+ return pending;
157
+ }
158
+
159
+ /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */
160
+ private teaqlValidateLoadedIdentities(seen = new Set<object>()): void {
161
+ if (seen.has(this)) return;
162
+ seen.add(this);
163
+ LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version);
164
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
165
+ try { child.teaqlValidateLoadedIdentities(seen); }
166
+ catch (error) {
167
+ if (!(error instanceof CheckException)) throw error;
168
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
169
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
170
+ }
171
+ }
172
+ }
173
+
174
+ /** @internal Cancel known no-ops across the graph before any derived FK edits. */
175
+ private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
176
+ if (seen.has(this)) return;
177
+ seen.add(this);
178
+ graph.discardRestoredFields(OrderStatus.teaqlMutationFields,
179
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
180
+ for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen);
181
+ }
182
+
183
+ /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */
184
+ private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
185
+ if (seen.has(this)) return;
186
+ seen.add(this);
187
+ graph.discardRestoredFields(OrderStatus.teaqlMutationFields,
188
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
189
+ graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), {
190
+ "platform": "Platform"
191
+ }, () => ({ ...this.teaqlMutationPayload(),
192
+ __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action,
193
+ __teaql_comment: (this as any)._comment,
194
+ __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()},
195
+ "customer_order_list": graph.sourceMembers((this as any)._customerOrderList)
196
+ }));
197
+ for (const child of (this as any)._customerOrderList) {
198
+ child.teaqlAttachRoot((this as any)._root);
199
+ const currentParent = child.status;
200
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
201
+ && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null
202
+ ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this);
203
+ child.teaqlNormalizeGraph(graph, seen);
204
+ }
205
+ }
206
+
207
+ /** @internal Whole-input version/completeness pass; does not use Context or Fix. */
208
+ private teaqlAdmitGraph(seen = new Set<object>()): boolean {
209
+ if (seen.has(this)) return false;
210
+ seen.add(this);
211
+ const action = (this as any)._action;
212
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
213
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
214
+ LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey());
215
+ OrderStatus.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update");
216
+ if (pending) {
217
+ nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion);
218
+ if (action === "Update") {
219
+ const notLoaded = [{ 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(field => !this.isLoaded(field.member));
220
+ if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderStatus", location: ObjectLocation.property(notLoaded.canonical),
221
+ message: "Mutation requires a fully loaded entity"}]);
222
+ }
223
+ }
224
+ let graphPending = pending;
225
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
226
+ try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; }
227
+ catch (error) {
228
+ if (!(error instanceof CheckException)) throw error;
229
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
230
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
231
+ }
232
+ }
233
+ return graphPending;
234
+ }
235
+
236
  /** @internal Validates and fixes the complete graph before its first mutation. */
237
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): void {
238
  if (!parent) new MutationIntent((this as any)._comment);
239
+ if (seen.has(this)) return;
240
+ seen.add(this);
241
  const action = (this as any)._action;
242
+ graph.discardRestoredFields(OrderStatus.teaqlMutationFields,
243
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
244
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
245
  if (action === "Update" && pending) {
246
  const notLoaded = [{ 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" }]
 
248
  if (notLoaded) {
249
  throw new CheckException([{
250
  ruleId: "invalid_type",
251
+ entityType: "OrderStatus",
252
  location: ObjectLocation.property(notLoaded.canonical),
253
  message: "Mutation requires a fully loaded entity",
254
  }]);
 
259
  payload: action === "Update"
260
  ? (this as any)._root.change(this.teaqlEntityKey())
261
  : this.teaqlMutationPayload(),
262
+ id: (this as any).id,
263
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
264
  comment: (this as any)._comment,
265
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
266
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
 
269
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
270
  child.teaqlAttachRoot((this as any)._root);
271
  const currentParent = child.status;
272
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
273
+ && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null
274
+ ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this);
275
+ try { child.teaqlPreflightGraph(context, service, graph, scope, seen); }
276
  catch (error) {
277
  if (!(error instanceof CheckException)) throw error;
278
  const prefix = ObjectLocation.property("customer_order_list").index(index);
279
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
280
  ...violation, location: violation.location.prefixedBy(prefix),
281
+ }))));
282
  }
283
  }
284
  }
285
 
286
  /** @internal Used by generated relation cascades inside the root graph transaction. */
287
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): Promise<OrderStatus> {
288
  if (!parent) new MutationIntent((this as any)._comment);
289
+ if (seen.has(this)) return this;
290
+ seen.add(this);
291
  const action = (this as any)._action;
292
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
293
  const mutation = {
 
295
  action: (this as any)._action,
296
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
297
  id: (this as any).id,
298
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
299
  comment: (this as any)._comment
300
  ,ledgerKey: this.teaqlEntityKey()
301
  ,ledgerRoot: (this as any)._root
 
307
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
308
  child.teaqlAttachRoot((this as any)._root);
309
  const currentParent = child.status;
310
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
311
+ && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null
312
+ ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this);
313
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
314
  catch (error) {
315
  if (!(error instanceof CheckException)) throw error;
316
  const prefix = ObjectLocation.property("customer_order_list").index(index);
317
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
318
  ...violation, location: violation.location.prefixedBy(prefix),
319
+ }))));
320
  }
321
  }
322
  return this;
323
  }
324
  const result = await service.executeMutation(request);
325
+ graph.validatePreparedSources();
 
 
326
  if (!result.persistedRecord) {
327
  throw new Error("Mutation did not return the authoritative persisted record");
328
  }
329
  const rollbackState = {
330
+ ownProperties: Object.getOwnPropertyDescriptors(this),
331
  ledgerId: (this as any)._ledgerId,
332
  action: (this as any)._action,
333
  loadedFields: new Set((this as any)._loadedFields),
 
336
  };
337
  const oldKey = this.teaqlEntityKey();
338
  Object.assign(this, result.persistedRecord);
 
339
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
340
  const newKey = this.teaqlEntityKey();
341
  (this as any)._root.rekey(oldKey, newKey);
342
+ const committedSnapshot = this.teaqlScalarSnapshot();
343
+ const activeScope = request.scopeFor(newKey);
344
  service.afterGraphRollback(() => {
345
+ for (const name of Object.getOwnPropertyNames(this)) {
346
+ if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name];
347
+ }
348
+ Object.defineProperties(this, rollbackState.ownProperties);
349
  (this as any)._ledgerId = rollbackState.ledgerId;
350
  (this as any)._action = rollbackState.action;
351
  (this as any)._loadedFields = rollbackState.loadedFields;
 
356
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
357
  (this as any)._fullyLoaded = false;
358
  if (mutation.action !== "Delete") (this as any)._action = "Update";
359
+ graph.acceptPreparedResult((this as any)._root, oldKey, newKey);
360
  const scope = request.scopeFor(newKey);
361
  for (const [index, child] of (this as any)._customerOrderList.entries()) {
362
  child.teaqlAttachRoot((this as any)._root);
363
  const currentParent = child.status;
364
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
365
+ && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null
366
+ ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this);
367
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
368
  catch (error) {
369
  if (!(error instanceof CheckException)) throw error;
370
  const prefix = ObjectLocation.property("customer_order_list").index(index);
371
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
372
  ...violation, location: violation.location.prefixedBy(prefix),
373
+ }))));
374
  }
375
  }
376
  service.afterGraphCommit(() => {
377
+ graph.validatePreparedSources();
378
+ LoadedScalarSnapshot.restoreFor(this, committedSnapshot);
379
  (this as any)._root.clearEntity(newKey);
380
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version);
381
+ graph.finishPreparedCommit((this as any)._root, newKey);
382
  });
383
  return this;
384
  }
 
395
  };
396
  }
397
 
398
+ private teaqlScalarSnapshot(): LoadedScalarSnapshot {
399
+ return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version);
400
+ }
401
+
402
  updateId(value: string): this {
403
  this.id = value;
404
  this.markLoaded("id");
 
434
  return this;
435
  }
436
 
437
+ updateVersion(value: EntityVersion): this {
438
  this.version = value;
439
  this.markLoaded("version");
440
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts CHANGED
@@ -1,24 +1,30 @@
1
- import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { OrderStatus } from './OrderStatus';
3
  import { Customer } from './Customer';
4
 
 
 
5
  export class Platform {
6
  private static teaqlTemporaryId = 0;
 
 
7
  id?: string;
8
  name?: string;
9
- version?: number;
10
 
11
- constructor(init?: Partial<Platform>) {
12
- Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
 
13
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
14
- Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
15
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
16
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
17
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false });
18
- Object.defineProperty(this, "_orderStatusList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false });
19
- Object.defineProperty(this, "_customerList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false });
20
  if (init) {
21
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
 
22
  delete fields["orderStatusList"];
23
  delete fields["customerList"];
24
  Object.assign(this, fields);
@@ -44,25 +50,34 @@ export class Platform {
44
  }
45
  }
46
  const key = this.teaqlEntityKey();
 
47
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
48
- else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
49
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
 
50
  }
51
 
52
  private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; }
53
- private teaqlAttachRoot(root: EntityRoot): this {
54
  if ((this as any)._root !== root) {
55
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
56
  (this as any)._root = root;
57
  }
58
- for (const child of (this as any)._orderStatusList) child.teaqlAttachRoot(root);
59
- for (const child of (this as any)._customerList) child.teaqlAttachRoot(root);
60
  return this;
61
  }
62
 
63
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Platform {
64
- const entity = new Platform(record as Partial<Platform>);
65
- return root ? entity.teaqlAttachRoot(root) : entity;
 
 
 
 
 
 
 
66
  }
67
 
68
  isLoaded(field: string): boolean {
@@ -81,12 +96,19 @@ export class Platform {
81
  }
82
 
83
  static refer(id: string | number): Platform {
84
- return new Platform({ id: String(id) } as Partial<Platform>);
85
  }
86
 
87
  /** @internal Generated Runtime Module fixed-ID construction capability. */
88
- static teaqlBootstrapNew(id: string | number): Platform {
89
- return new Platform().updateId(String(id));
 
 
 
 
 
 
 
90
  }
91
 
92
  markForDeletion(): this {
@@ -96,23 +118,153 @@ export class Platform {
96
  }
97
 
98
  auditAs(comment: string): this {
99
- new MutationIntent(comment);
100
- (this as any)._comment = comment;
101
  return this;
102
  }
103
 
104
  async save(context: UserContext): Promise<Platform> {
 
 
 
105
  const service = context.requireResource<TeaQLDataService>("dataService");
106
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
107
- this.teaqlPreflightGraph(context, service, graph);
108
  return this.teaqlSaveWithinGraph(context, service, graph);
 
 
 
 
 
 
 
 
 
 
 
109
  });
110
  }
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  /** @internal Validates and fixes the complete graph before its first mutation. */
113
- teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
114
  if (!parent) new MutationIntent((this as any)._comment);
 
 
115
  const action = (this as any)._action;
 
 
116
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
117
  if (action === "Update" && pending) {
118
  const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]
@@ -120,6 +272,7 @@ export class Platform {
120
  if (notLoaded) {
121
  throw new CheckException([{
122
  ruleId: "invalid_type",
 
123
  location: ObjectLocation.property(notLoaded.canonical),
124
  message: "Mutation requires a fully loaded entity",
125
  }]);
@@ -130,7 +283,8 @@ export class Platform {
130
  payload: action === "Update"
131
  ? (this as any)._root.change(this.teaqlEntityKey())
132
  : this.teaqlMutationPayload(),
133
- id: (this as any).id, version: (this as any).version,
 
134
  comment: (this as any)._comment,
135
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
136
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
@@ -139,36 +293,40 @@ export class Platform {
139
  for (const [index, child] of (this as any)._orderStatusList.entries()) {
140
  child.teaqlAttachRoot((this as any)._root);
141
  const currentParent = child.platform;
142
- if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
143
- ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this);
144
- try { child.teaqlPreflightGraph(context, service, graph, scope); }
 
145
  catch (error) {
146
  if (!(error instanceof CheckException)) throw error;
147
  const prefix = ObjectLocation.property("order_status_list").index(index);
148
- throw new CheckException(error.violations.map(violation => ({
149
  ...violation, location: violation.location.prefixedBy(prefix),
150
- })));
151
  }
152
  }
153
  for (const [index, child] of (this as any)._customerList.entries()) {
154
  child.teaqlAttachRoot((this as any)._root);
155
  const currentParent = child.platform;
156
- if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
157
- ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this);
158
- try { child.teaqlPreflightGraph(context, service, graph, scope); }
 
159
  catch (error) {
160
  if (!(error instanceof CheckException)) throw error;
161
  const prefix = ObjectLocation.property("customer_list").index(index);
162
- throw new CheckException(error.violations.map(violation => ({
163
  ...violation, location: violation.location.prefixedBy(prefix),
164
- })));
165
  }
166
  }
167
  }
168
 
169
  /** @internal Used by generated relation cascades inside the root graph transaction. */
170
- async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<Platform> {
171
  if (!parent) new MutationIntent((this as any)._comment);
 
 
172
  const action = (this as any)._action;
173
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
174
  const mutation = {
@@ -176,7 +334,7 @@ export class Platform {
176
  action: (this as any)._action,
177
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
178
  id: (this as any).id,
179
- version: (this as any).version,
180
  comment: (this as any)._comment
181
  ,ledgerKey: this.teaqlEntityKey()
182
  ,ledgerRoot: (this as any)._root
@@ -188,42 +346,42 @@ export class Platform {
188
  for (const [index, child] of (this as any)._orderStatusList.entries()) {
189
  child.teaqlAttachRoot((this as any)._root);
190
  const currentParent = child.platform;
191
- if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
192
- ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this);
193
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
194
  catch (error) {
195
  if (!(error instanceof CheckException)) throw error;
196
  const prefix = ObjectLocation.property("order_status_list").index(index);
197
- throw new CheckException(error.violations.map(violation => ({
198
  ...violation, location: violation.location.prefixedBy(prefix),
199
- })));
200
  }
201
  }
202
  for (const [index, child] of (this as any)._customerList.entries()) {
203
  child.teaqlAttachRoot((this as any)._root);
204
  const currentParent = child.platform;
205
- if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
206
- ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this);
207
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
208
  catch (error) {
209
  if (!(error instanceof CheckException)) throw error;
210
  const prefix = ObjectLocation.property("customer_list").index(index);
211
- throw new CheckException(error.violations.map(violation => ({
212
  ...violation, location: violation.location.prefixedBy(prefix),
213
- })));
214
  }
215
  }
216
  return this;
217
  }
218
  const result = await service.executeMutation(request);
219
- for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
220
- if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
221
- }
222
  if (!result.persistedRecord) {
223
  throw new Error("Mutation did not return the authoritative persisted record");
224
  }
225
  const rollbackState = {
226
- payload: this.teaqlMutationPayload(),
227
  ledgerId: (this as any)._ledgerId,
228
  action: (this as any)._action,
229
  loadedFields: new Set((this as any)._loadedFields),
@@ -232,12 +390,16 @@ export class Platform {
232
  };
233
  const oldKey = this.teaqlEntityKey();
234
  Object.assign(this, result.persistedRecord);
235
- LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload());
236
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
237
  const newKey = this.teaqlEntityKey();
238
  (this as any)._root.rekey(oldKey, newKey);
 
 
239
  service.afterGraphRollback(() => {
240
- Object.assign(this, rollbackState.payload);
 
 
 
241
  (this as any)._ledgerId = rollbackState.ledgerId;
242
  (this as any)._action = rollbackState.action;
243
  (this as any)._loadedFields = rollbackState.loadedFields;
@@ -248,38 +410,44 @@ export class Platform {
248
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
249
  (this as any)._fullyLoaded = false;
250
  if (mutation.action !== "Delete") (this as any)._action = "Update";
 
251
  const scope = request.scopeFor(newKey);
252
  for (const [index, child] of (this as any)._orderStatusList.entries()) {
253
  child.teaqlAttachRoot((this as any)._root);
254
  const currentParent = child.platform;
255
- if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
256
- ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this);
257
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
258
  catch (error) {
259
  if (!(error instanceof CheckException)) throw error;
260
  const prefix = ObjectLocation.property("order_status_list").index(index);
261
- throw new CheckException(error.violations.map(violation => ({
262
  ...violation, location: violation.location.prefixedBy(prefix),
263
- })));
264
  }
265
  }
266
  for (const [index, child] of (this as any)._customerList.entries()) {
267
  child.teaqlAttachRoot((this as any)._root);
268
  const currentParent = child.platform;
269
- if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
270
- ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this);
271
- try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
 
272
  catch (error) {
273
  if (!(error instanceof CheckException)) throw error;
274
  const prefix = ObjectLocation.property("customer_list").index(index);
275
- throw new CheckException(error.violations.map(violation => ({
276
  ...violation, location: violation.location.prefixedBy(prefix),
277
- })));
278
  }
279
  }
280
  service.afterGraphCommit(() => {
 
 
281
  (this as any)._root.clearEntity(newKey);
282
- if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
 
283
  });
284
  return this;
285
  }
@@ -292,6 +460,10 @@ export class Platform {
292
  };
293
  }
294
 
 
 
 
 
295
  updateId(value: string): this {
296
  this.id = value;
297
  this.markLoaded("id");
@@ -306,7 +478,7 @@ export class Platform {
306
  return this;
307
  }
308
 
309
- updateVersion(value: number): this {
310
  this.version = value;
311
  this.markLoaded("version");
312
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
 
1
+ import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts';
2
  import { OrderStatus } from './OrderStatus';
3
  import { Customer } from './Customer';
4
 
5
+ const teaqlConstruction = Symbol("managed entity construction");
6
+
7
  export class Platform {
8
  private static teaqlTemporaryId = 0;
9
+ private static readonly teaqlMutationFields = new MutationFieldLayout("Platform",
10
+ ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" });
11
  id?: string;
12
  name?: string;
13
+ version?: EntityVersion;
14
 
15
+ private constructor(init?: Partial<Platform>, token?: symbol, creation = false) {
16
+ if (token !== teaqlConstruction) throw new EntityCreationError();
17
+ Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false });
18
  Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false });
20
  Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
21
  Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
22
  Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false });
23
+ Object.defineProperty(this, "_orderStatusList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false });
24
+ Object.defineProperty(this, "_customerList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false });
25
  if (init) {
26
  const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
27
+ for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key];
28
  delete fields["orderStatusList"];
29
  delete fields["customerList"];
30
  Object.assign(this, fields);
 
50
  }
51
  }
52
  const key = this.teaqlEntityKey();
53
+ if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version);
54
  if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
55
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version);
56
+ LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version,
57
+ creation ? "creationBaseline" : "hydrated");
58
  }
59
 
60
  private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; }
61
+ private teaqlAttachRoot(root: EntityRoot, hydration = false): this {
62
  if ((this as any)._root !== root) {
63
  root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
64
  (this as any)._root = root;
65
  }
66
+ for (const child of (this as any)._orderStatusList) child.teaqlAttachRoot(root, hydration);
67
+ for (const child of (this as any)._customerList) child.teaqlAttachRoot(root, hydration);
68
  return this;
69
  }
70
 
71
  static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Platform {
72
+ const entity = EntityCreation.hydrated(new Platform(record as Partial<Platform>, teaqlConstruction));
73
+ return root ? entity.teaqlAttachRoot(root, true) : entity;
74
+ }
75
+
76
+ toJSON(): Record<string, unknown> {
77
+ const result = Object.fromEntries(Object.entries(this));
78
+ if (this.isLoaded("orderStatusList")) result["orderStatusList"] = (this as any)._orderStatusList;
79
+ if (this.isLoaded("customerList")) result["customerList"] = (this as any)._customerList;
80
+ return result;
81
  }
82
 
83
  isLoaded(field: string): boolean {
 
96
  }
97
 
98
  static refer(id: string | number): Platform {
99
+ return Platform.fromRecord({ id: String(id) });
100
  }
101
 
102
  /** @internal Generated Runtime Module fixed-ID construction capability. */
103
+ static teaqlBootstrapNew(context: UserContext, id: string | number): Platform {
104
+ return EntityCreation.bootstrap(context, "Platform", id,
105
+ reserved => new Platform({id: reserved} as Partial<Platform>, teaqlConstruction, true));
106
+ }
107
+
108
+ /** @internal Q owns the awaited public creation entry point. */
109
+ static teaqlCreate(context: UserContext): Promise<Platform> {
110
+ return EntityCreation.create(context, "Platform",
111
+ reserved => new Platform({id: reserved} as Partial<Platform>, teaqlConstruction, true));
112
  }
113
 
114
  markForDeletion(): this {
 
118
  }
119
 
120
  auditAs(comment: string): this {
121
+ (this as any)._comment = new MutationIntent(comment).comment;
 
122
  return this;
123
  }
124
 
125
  async save(context: UserContext): Promise<Platform> {
126
+ const intent = new MutationIntent((this as any)._comment);
127
+ this.teaqlValidateLoadedIdentities();
128
+ if (!this.teaqlValidateMutationOrigins()) return this;
129
  const service = context.requireResource<TeaQLDataService>("dataService");
130
  return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
 
131
  return this.teaqlSaveWithinGraph(context, service, graph);
132
+ }, (graph) => {
133
+ this.teaqlPreflightGraph(context, service, graph);
134
+ this.teaqlValidateLoadedIdentities();
135
+ this.teaqlAdmitGraph();
136
+ graph.sealPreparedGraph();
137
+ }, (graph) => {
138
+ this.teaqlValidateLoadedIdentities();
139
+ this.teaqlDiscardRestoredGraph(graph);
140
+ this.teaqlAdmitGraph();
141
+ this.teaqlNormalizeGraph(graph);
142
+ return this.teaqlAdmitGraph();
143
  });
144
  }
145
 
146
+ /** @internal Pure provenance pass before resolving any Context resources. */
147
+ private teaqlValidateMutationOrigins(seen = new Set<object>()): boolean {
148
+ if (seen.has(this)) return false;
149
+ seen.add(this);
150
+ const action = (this as any)._action;
151
+ let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
152
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
153
+ for (const child of (this as any)._orderStatusList) pending = child.teaqlValidateMutationOrigins(seen) || pending;
154
+ for (const child of (this as any)._customerList) pending = child.teaqlValidateMutationOrigins(seen) || pending;
155
+ return pending;
156
+ }
157
+
158
+ /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */
159
+ private teaqlValidateLoadedIdentities(seen = new Set<object>()): void {
160
+ if (seen.has(this)) return;
161
+ seen.add(this);
162
+ LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version);
163
+ for (const [index, child] of (this as any)._orderStatusList.entries()) {
164
+ try { child.teaqlValidateLoadedIdentities(seen); }
165
+ catch (error) {
166
+ if (!(error instanceof CheckException)) throw error;
167
+ const prefix = ObjectLocation.property("order_status_list").index(index);
168
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
169
+ }
170
+ }
171
+ for (const [index, child] of (this as any)._customerList.entries()) {
172
+ try { child.teaqlValidateLoadedIdentities(seen); }
173
+ catch (error) {
174
+ if (!(error instanceof CheckException)) throw error;
175
+ const prefix = ObjectLocation.property("customer_list").index(index);
176
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
177
+ }
178
+ }
179
+ }
180
+
181
+ /** @internal Cancel known no-ops across the graph before any derived FK edits. */
182
+ private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
183
+ if (seen.has(this)) return;
184
+ seen.add(this);
185
+ graph.discardRestoredFields(Platform.teaqlMutationFields,
186
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
187
+ for (const child of (this as any)._orderStatusList) child.teaqlDiscardRestoredGraph(graph, seen);
188
+ for (const child of (this as any)._customerList) child.teaqlDiscardRestoredGraph(graph, seen);
189
+ }
190
+
191
+ /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */
192
+ private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
193
+ if (seen.has(this)) return;
194
+ seen.add(this);
195
+ graph.discardRestoredFields(Platform.teaqlMutationFields,
196
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
197
+ graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), {
198
+ }, () => ({ ...this.teaqlMutationPayload(),
199
+ __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action,
200
+ __teaql_comment: (this as any)._comment,
201
+ __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()},
202
+ "order_status_list": graph.sourceMembers((this as any)._orderStatusList),
203
+ "customer_list": graph.sourceMembers((this as any)._customerList)
204
+ }));
205
+ for (const child of (this as any)._orderStatusList) {
206
+ child.teaqlAttachRoot((this as any)._root);
207
+ const currentParent = child.platform;
208
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
209
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
210
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
211
+ child.teaqlNormalizeGraph(graph, seen);
212
+ }
213
+ for (const child of (this as any)._customerList) {
214
+ child.teaqlAttachRoot((this as any)._root);
215
+ const currentParent = child.platform;
216
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
217
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
218
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
219
+ child.teaqlNormalizeGraph(graph, seen);
220
+ }
221
+ }
222
+
223
+ /** @internal Whole-input version/completeness pass; does not use Context or Fix. */
224
+ private teaqlAdmitGraph(seen = new Set<object>()): boolean {
225
+ if (seen.has(this)) return false;
226
+ seen.add(this);
227
+ const action = (this as any)._action;
228
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
229
+ EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending);
230
+ LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey());
231
+ Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update");
232
+ if (pending) {
233
+ nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion);
234
+ if (action === "Update") {
235
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member));
236
+ if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical),
237
+ message: "Mutation requires a fully loaded entity"}]);
238
+ }
239
+ }
240
+ let graphPending = pending;
241
+ for (const [index, child] of (this as any)._orderStatusList.entries()) {
242
+ try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; }
243
+ catch (error) {
244
+ if (!(error instanceof CheckException)) throw error;
245
+ const prefix = ObjectLocation.property("order_status_list").index(index);
246
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
247
+ }
248
+ }
249
+ for (const [index, child] of (this as any)._customerList.entries()) {
250
+ try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; }
251
+ catch (error) {
252
+ if (!(error instanceof CheckException)) throw error;
253
+ const prefix = ObjectLocation.property("customer_list").index(index);
254
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
255
+ }
256
+ }
257
+ return graphPending;
258
+ }
259
+
260
  /** @internal Validates and fixes the complete graph before its first mutation. */
261
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): void {
262
  if (!parent) new MutationIntent((this as any)._comment);
263
+ if (seen.has(this)) return;
264
+ seen.add(this);
265
  const action = (this as any)._action;
266
+ graph.discardRestoredFields(Platform.teaqlMutationFields,
267
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
268
  const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
269
  if (action === "Update" && pending) {
270
  const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]
 
272
  if (notLoaded) {
273
  throw new CheckException([{
274
  ruleId: "invalid_type",
275
+ entityType: "Platform",
276
  location: ObjectLocation.property(notLoaded.canonical),
277
  message: "Mutation requires a fully loaded entity",
278
  }]);
 
283
  payload: action === "Update"
284
  ? (this as any)._root.change(this.teaqlEntityKey())
285
  : this.teaqlMutationPayload(),
286
+ id: (this as any).id,
287
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
288
  comment: (this as any)._comment,
289
  ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
290
  }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
 
293
  for (const [index, child] of (this as any)._orderStatusList.entries()) {
294
  child.teaqlAttachRoot((this as any)._root);
295
  const currentParent = child.platform;
296
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
297
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
298
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
299
+ try { child.teaqlPreflightGraph(context, service, graph, scope, seen); }
300
  catch (error) {
301
  if (!(error instanceof CheckException)) throw error;
302
  const prefix = ObjectLocation.property("order_status_list").index(index);
303
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
304
  ...violation, location: violation.location.prefixedBy(prefix),
305
+ }))));
306
  }
307
  }
308
  for (const [index, child] of (this as any)._customerList.entries()) {
309
  child.teaqlAttachRoot((this as any)._root);
310
  const currentParent = child.platform;
311
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
312
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
313
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
314
+ try { child.teaqlPreflightGraph(context, service, graph, scope, seen); }
315
  catch (error) {
316
  if (!(error instanceof CheckException)) throw error;
317
  const prefix = ObjectLocation.property("customer_list").index(index);
318
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
319
  ...violation, location: violation.location.prefixedBy(prefix),
320
+ }))));
321
  }
322
  }
323
  }
324
 
325
  /** @internal Used by generated relation cascades inside the root graph transaction. */
326
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set<object>()): Promise<Platform> {
327
  if (!parent) new MutationIntent((this as any)._comment);
328
+ if (seen.has(this)) return this;
329
+ seen.add(this);
330
  const action = (this as any)._action;
331
  const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
332
  const mutation = {
 
334
  action: (this as any)._action,
335
  payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
336
  id: (this as any).id,
337
+ version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion,
338
  comment: (this as any)._comment
339
  ,ledgerKey: this.teaqlEntityKey()
340
  ,ledgerRoot: (this as any)._root
 
346
  for (const [index, child] of (this as any)._orderStatusList.entries()) {
347
  child.teaqlAttachRoot((this as any)._root);
348
  const currentParent = child.platform;
349
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
350
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
351
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
352
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
353
  catch (error) {
354
  if (!(error instanceof CheckException)) throw error;
355
  const prefix = ObjectLocation.property("order_status_list").index(index);
356
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
357
  ...violation, location: violation.location.prefixedBy(prefix),
358
+ }))));
359
  }
360
  }
361
  for (const [index, child] of (this as any)._customerList.entries()) {
362
  child.teaqlAttachRoot((this as any)._root);
363
  const currentParent = child.platform;
364
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
365
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
366
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
367
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
368
  catch (error) {
369
  if (!(error instanceof CheckException)) throw error;
370
  const prefix = ObjectLocation.property("customer_list").index(index);
371
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
372
  ...violation, location: violation.location.prefixedBy(prefix),
373
+ }))));
374
  }
375
  }
376
  return this;
377
  }
378
  const result = await service.executeMutation(request);
379
+ graph.validatePreparedSources();
 
 
380
  if (!result.persistedRecord) {
381
  throw new Error("Mutation did not return the authoritative persisted record");
382
  }
383
  const rollbackState = {
384
+ ownProperties: Object.getOwnPropertyDescriptors(this),
385
  ledgerId: (this as any)._ledgerId,
386
  action: (this as any)._action,
387
  loadedFields: new Set((this as any)._loadedFields),
 
390
  };
391
  const oldKey = this.teaqlEntityKey();
392
  Object.assign(this, result.persistedRecord);
 
393
  (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
394
  const newKey = this.teaqlEntityKey();
395
  (this as any)._root.rekey(oldKey, newKey);
396
+ const committedSnapshot = this.teaqlScalarSnapshot();
397
+ const activeScope = request.scopeFor(newKey);
398
  service.afterGraphRollback(() => {
399
+ for (const name of Object.getOwnPropertyNames(this)) {
400
+ if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name];
401
+ }
402
+ Object.defineProperties(this, rollbackState.ownProperties);
403
  (this as any)._ledgerId = rollbackState.ledgerId;
404
  (this as any)._action = rollbackState.action;
405
  (this as any)._loadedFields = rollbackState.loadedFields;
 
410
  (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
411
  (this as any)._fullyLoaded = false;
412
  if (mutation.action !== "Delete") (this as any)._action = "Update";
413
+ graph.acceptPreparedResult((this as any)._root, oldKey, newKey);
414
  const scope = request.scopeFor(newKey);
415
  for (const [index, child] of (this as any)._orderStatusList.entries()) {
416
  child.teaqlAttachRoot((this as any)._root);
417
  const currentParent = child.platform;
418
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
419
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
420
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
421
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
422
  catch (error) {
423
  if (!(error instanceof CheckException)) throw error;
424
  const prefix = ObjectLocation.property("order_status_list").index(index);
425
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
426
  ...violation, location: violation.location.prefixedBy(prefix),
427
+ }))));
428
  }
429
  }
430
  for (const [index, child] of (this as any)._customerList.entries()) {
431
  child.teaqlAttachRoot((this as any)._root);
432
  const currentParent = child.platform;
433
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
434
+ && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null
435
+ ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this);
436
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); }
437
  catch (error) {
438
  if (!(error instanceof CheckException)) throw error;
439
  const prefix = ObjectLocation.property("customer_list").index(index);
440
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
441
  ...violation, location: violation.location.prefixedBy(prefix),
442
+ }))));
443
  }
444
  }
445
  service.afterGraphCommit(() => {
446
+ graph.validatePreparedSources();
447
+ LoadedScalarSnapshot.restoreFor(this, committedSnapshot);
448
  (this as any)._root.clearEntity(newKey);
449
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version);
450
+ graph.finishPreparedCommit((this as any)._root, newKey);
451
  });
452
  return this;
453
  }
 
460
  };
461
  }
462
 
463
+ private teaqlScalarSnapshot(): LoadedScalarSnapshot {
464
+ return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version);
465
+ }
466
+
467
  updateId(value: string): this {
468
  this.id = value;
469
  this.markLoaded("id");
 
478
  return this;
479
  }
480
 
481
+ updateVersion(value: EntityVersion): this {
482
  this.version = value;
483
  this.markLoaded("version");
484
  (this as any)._root.set(this.teaqlEntityKey(), "version", value);
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { CustomerOrder } from '../models/CustomerOrder';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
 
4
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
 
6
 
@@ -24,6 +25,10 @@ export class CustomerOrderRequest {
24
  else this.selectSelfFields();
25
  }
26
 
 
 
 
 
27
  comment(c: string): this {
28
  this.query.comment(c);
29
  this._comment = c;
@@ -99,12 +104,14 @@ export class CustomerOrderRequest {
99
  }
100
 
101
  withDeletedRows(): this {
 
102
  this.filters = this.filters.filter(filter => !("version" in filter));
103
  return this;
104
  }
105
 
106
  deletedRowsOnly(): this {
107
  this.withDeletedRows();
 
108
  this.filters.push({ version: { "$lte": -1 } });
109
  return this;
110
  }
@@ -142,14 +149,14 @@ export class CustomerOrderRequest {
142
  }
143
 
144
 
145
- selectCustomerWith(request: { toQuery(): SelectQuery }): this {
146
  this.query.select(["customer"]);
147
  this.query.relationQuery(
148
  "customer", request.toQuery(), "customer", "id", false,
149
  { kind: "relation-select", method: "selectCustomerWith", relation: "customer" });
150
  return this;
151
  }
152
- selectStatusWith(request: { toQuery(): SelectQuery }): this {
153
  this.query.select(["status"]);
154
  this.query.relationQuery(
155
  "status", request.toQuery(), "status", "id", false,
@@ -157,7 +164,7 @@ export class CustomerOrderRequest {
157
  return this;
158
  }
159
 
160
- withCustomerMatching(request: { toQuery(): SelectQuery }): this {
161
  this.filters.push({
162
  "customer": {
163
  "$inSubquery": { query: request.toQuery(), field: "id" },
@@ -166,7 +173,7 @@ export class CustomerOrderRequest {
166
  return this;
167
  }
168
 
169
- withoutCustomerMatching(request: { toQuery(): SelectQuery }): this {
170
  this.filters.push({
171
  "customer": {
172
  "$notInSubquery": { query: request.toQuery(), field: "id" },
@@ -174,7 +181,7 @@ export class CustomerOrderRequest {
174
  });
175
  return this;
176
  }
177
- withStatusMatching(request: { toQuery(): SelectQuery }): this {
178
  this.filters.push({
179
  "status": {
180
  "$inSubquery": { query: request.toQuery(), field: "id" },
@@ -183,7 +190,7 @@ export class CustomerOrderRequest {
183
  return this;
184
  }
185
 
186
- withoutStatusMatching(request: { toQuery(): SelectQuery }): this {
187
  this.filters.push({
188
  "status": {
189
  "$notInSubquery": { query: request.toQuery(), field: "id" },
@@ -192,7 +199,7 @@ export class CustomerOrderRequest {
192
  return this;
193
  }
194
 
195
- selectOrderItemListWith(request: { toQuery(): SelectQuery }): this {
196
  this.query.relationQuery(
197
  "orderItemList", request.toQuery(), "id", "customerOrder", true,
198
  { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" });
@@ -201,17 +208,19 @@ export class CustomerOrderRequest {
201
 
202
  haveOrderItems(): this {
203
  return this.withOrderItemListMatching({
 
204
  toQuery: () => new SelectQuery("OrderItem"),
205
  });
206
  }
207
 
208
  haveNoOrderItems(): this {
209
  return this.withoutOrderItemListMatching({
 
210
  toQuery: () => new SelectQuery("OrderItem"),
211
  });
212
  }
213
 
214
- withOrderItemListMatching(request: { toQuery(): SelectQuery }): this {
215
  this.filters.push({
216
  "id": {
217
  "$inSubquery": {
@@ -222,7 +231,7 @@ export class CustomerOrderRequest {
222
  return this;
223
  }
224
 
225
- withoutOrderItemListMatching(request: { toQuery(): SelectQuery }): this {
226
  this.filters.push({
227
  "id": {
228
  "$notInSubquery": {
@@ -239,13 +248,13 @@ export class CustomerOrderRequest {
239
 
240
  countOrderItemsAs(alias: string): this {
241
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
242
- this.countOrderItemsWith(alias, { toQuery: () => query });
243
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
244
  kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias };
245
  return this;
246
  }
247
 
248
- countOrderItemsWith(alias: string, child: { toQuery(): SelectQuery }): this {
249
  const query = child.toQuery().clone();
250
  query.aggregateItems = [];
251
  query.aggregate("Count", "id", alias);
@@ -257,10 +266,10 @@ export class CustomerOrderRequest {
257
  minQuantityOfOrderItems(): this {
258
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
259
  return this.minQuantityOfOrderItemsAs(
260
- "minOfQuantityOfOrderItems", { toQuery: () => query });
261
  }
262
 
263
- minQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
264
  const query = child.toQuery().clone();
265
  query.aggregateItems = [];
266
  query.aggregate("min", "quantity", alias);
@@ -271,10 +280,10 @@ export class CustomerOrderRequest {
271
  maxQuantityOfOrderItems(): this {
272
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
273
  return this.maxQuantityOfOrderItemsAs(
274
- "maxOfQuantityOfOrderItems", { toQuery: () => query });
275
  }
276
 
277
- maxQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
278
  const query = child.toQuery().clone();
279
  query.aggregateItems = [];
280
  query.aggregate("max", "quantity", alias);
@@ -285,10 +294,10 @@ export class CustomerOrderRequest {
285
  sumQuantityOfOrderItems(): this {
286
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
287
  return this.sumQuantityOfOrderItemsAs(
288
- "sumOfQuantityOfOrderItems", { toQuery: () => query });
289
  }
290
 
291
- sumQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
292
  const query = child.toQuery().clone();
293
  query.aggregateItems = [];
294
  query.aggregate("sum", "quantity", alias);
@@ -299,10 +308,10 @@ export class CustomerOrderRequest {
299
  avgQuantityOfOrderItems(): this {
300
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
301
  return this.avgQuantityOfOrderItemsAs(
302
- "avgOfQuantityOfOrderItems", { toQuery: () => query });
303
  }
304
 
305
- avgQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
306
  const query = child.toQuery().clone();
307
  query.aggregateItems = [];
308
  query.aggregate("avg", "quantity", alias);
@@ -313,10 +322,10 @@ export class CustomerOrderRequest {
313
  standardDeviationQuantityOfOrderItems(): this {
314
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
315
  return this.standardDeviationQuantityOfOrderItemsAs(
316
- "standardDeviationOfQuantityOfOrderItems", { toQuery: () => query });
317
  }
318
 
319
- standardDeviationQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
320
  const query = child.toQuery().clone();
321
  query.aggregateItems = [];
322
  query.aggregate("stddev", "quantity", alias);
@@ -327,10 +336,10 @@ export class CustomerOrderRequest {
327
  squareRootOfPopulationStandardDeviationQuantityOfOrderItems(): this {
328
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
329
  return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(
330
- "squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems", { toQuery: () => query });
331
  }
332
 
333
- squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
334
  const query = child.toQuery().clone();
335
  query.aggregateItems = [];
336
  query.aggregate("stddev_pop", "quantity", alias);
@@ -341,10 +350,10 @@ export class CustomerOrderRequest {
341
  sampleVarianceQuantityOfOrderItems(): this {
342
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
343
  return this.sampleVarianceQuantityOfOrderItemsAs(
344
- "sampleVarianceOfQuantityOfOrderItems", { toQuery: () => query });
345
  }
346
 
347
- sampleVarianceQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
348
  const query = child.toQuery().clone();
349
  query.aggregateItems = [];
350
  query.aggregate("var_samp", "quantity", alias);
@@ -355,10 +364,10 @@ export class CustomerOrderRequest {
355
  samplePopulationVarianceQuantityOfOrderItems(): this {
356
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
357
  return this.samplePopulationVarianceQuantityOfOrderItemsAs(
358
- "samplePopulationVarianceOfQuantityOfOrderItems", { toQuery: () => query });
359
  }
360
 
361
- samplePopulationVarianceQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
362
  const query = child.toQuery().clone();
363
  query.aggregateItems = [];
364
  query.aggregate("var_pop", "quantity", alias);
@@ -369,10 +378,10 @@ export class CustomerOrderRequest {
369
  minUnitPriceOfOrderItems(): this {
370
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
371
  return this.minUnitPriceOfOrderItemsAs(
372
- "minOfUnitPriceOfOrderItems", { toQuery: () => query });
373
  }
374
 
375
- minUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
376
  const query = child.toQuery().clone();
377
  query.aggregateItems = [];
378
  query.aggregate("min", "unitPrice", alias);
@@ -383,10 +392,10 @@ export class CustomerOrderRequest {
383
  maxUnitPriceOfOrderItems(): this {
384
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
385
  return this.maxUnitPriceOfOrderItemsAs(
386
- "maxOfUnitPriceOfOrderItems", { toQuery: () => query });
387
  }
388
 
389
- maxUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
390
  const query = child.toQuery().clone();
391
  query.aggregateItems = [];
392
  query.aggregate("max", "unitPrice", alias);
@@ -397,10 +406,10 @@ export class CustomerOrderRequest {
397
  sumUnitPriceOfOrderItems(): this {
398
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
399
  return this.sumUnitPriceOfOrderItemsAs(
400
- "sumOfUnitPriceOfOrderItems", { toQuery: () => query });
401
  }
402
 
403
- sumUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
404
  const query = child.toQuery().clone();
405
  query.aggregateItems = [];
406
  query.aggregate("sum", "unitPrice", alias);
@@ -411,10 +420,10 @@ export class CustomerOrderRequest {
411
  avgUnitPriceOfOrderItems(): this {
412
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
413
  return this.avgUnitPriceOfOrderItemsAs(
414
- "avgOfUnitPriceOfOrderItems", { toQuery: () => query });
415
  }
416
 
417
- avgUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
418
  const query = child.toQuery().clone();
419
  query.aggregateItems = [];
420
  query.aggregate("avg", "unitPrice", alias);
@@ -425,10 +434,10 @@ export class CustomerOrderRequest {
425
  standardDeviationUnitPriceOfOrderItems(): this {
426
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
427
  return this.standardDeviationUnitPriceOfOrderItemsAs(
428
- "standardDeviationOfUnitPriceOfOrderItems", { toQuery: () => query });
429
  }
430
 
431
- standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
432
  const query = child.toQuery().clone();
433
  query.aggregateItems = [];
434
  query.aggregate("stddev", "unitPrice", alias);
@@ -439,10 +448,10 @@ export class CustomerOrderRequest {
439
  squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this {
440
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
441
  return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(
442
- "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { toQuery: () => query });
443
  }
444
 
445
- squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
446
  const query = child.toQuery().clone();
447
  query.aggregateItems = [];
448
  query.aggregate("stddev_pop", "unitPrice", alias);
@@ -453,10 +462,10 @@ export class CustomerOrderRequest {
453
  sampleVarianceUnitPriceOfOrderItems(): this {
454
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
455
  return this.sampleVarianceUnitPriceOfOrderItemsAs(
456
- "sampleVarianceOfUnitPriceOfOrderItems", { toQuery: () => query });
457
  }
458
 
459
- sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
460
  const query = child.toQuery().clone();
461
  query.aggregateItems = [];
462
  query.aggregate("var_samp", "unitPrice", alias);
@@ -467,10 +476,10 @@ export class CustomerOrderRequest {
467
  samplePopulationVarianceUnitPriceOfOrderItems(): this {
468
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
469
  return this.samplePopulationVarianceUnitPriceOfOrderItemsAs(
470
- "samplePopulationVarianceOfUnitPriceOfOrderItems", { toQuery: () => query });
471
  }
472
 
473
- samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
474
  const query = child.toQuery().clone();
475
  query.aggregateItems = [];
476
  query.aggregate("var_pop", "unitPrice", alias);
@@ -479,47 +488,47 @@ export class CustomerOrderRequest {
479
  return this;
480
  }
481
 
482
- withIdIs(val: any): this {
483
  this.filters.push({ "id": { "$eq": val } });
484
  return this;
485
  }
486
 
487
- withIdIsNot(val: any): this {
488
  this.filters.push({ "id": { "$ne": val } });
489
  return this;
490
  }
491
 
492
- withIdIn(...vals: any[]): this {
493
  this.filters.push({ "id": { "$in": vals } });
494
  return this;
495
  }
496
 
497
- withIdNotIn(...vals: any[]): this {
498
  this.filters.push({ "id": { "$notIn": vals } });
499
  return this;
500
  }
501
 
502
- withIdGreaterThan(val: any): this {
503
  this.filters.push({ "id": { "$gt": val } });
504
  return this;
505
  }
506
 
507
- withIdGreaterThanOrEqualTo(val: any): this {
508
  this.filters.push({ "id": { "$gte": val } });
509
  return this;
510
  }
511
 
512
- withIdLessThan(val: any): this {
513
  this.filters.push({ "id": { "$lt": val } });
514
  return this;
515
  }
516
 
517
- withIdLessThanOrEqualTo(val: any): this {
518
  this.filters.push({ "id": { "$lte": val } });
519
  return this;
520
  }
521
 
522
- withIdBetween(lower: any, upper: any): this {
523
  this.filters.push({ "id": { "$between": [lower, upper] } });
524
  return this;
525
  }
@@ -596,42 +605,42 @@ export class CustomerOrderRequest {
596
  return this;
597
  }
598
 
599
- withOrderNumberIsNot(val: any): this {
600
  this.filters.push({ "orderNumber": { "$ne": val } });
601
  return this;
602
  }
603
 
604
- withOrderNumberIn(...vals: any[]): this {
605
  this.filters.push({ "orderNumber": { "$in": vals } });
606
  return this;
607
  }
608
 
609
- withOrderNumberNotIn(...vals: any[]): this {
610
  this.filters.push({ "orderNumber": { "$notIn": vals } });
611
  return this;
612
  }
613
 
614
- withOrderNumberGreaterThan(val: any): this {
615
  this.filters.push({ "orderNumber": { "$gt": val } });
616
  return this;
617
  }
618
 
619
- withOrderNumberGreaterThanOrEqualTo(val: any): this {
620
  this.filters.push({ "orderNumber": { "$gte": val } });
621
  return this;
622
  }
623
 
624
- withOrderNumberLessThan(val: any): this {
625
  this.filters.push({ "orderNumber": { "$lt": val } });
626
  return this;
627
  }
628
 
629
- withOrderNumberLessThanOrEqualTo(val: any): this {
630
  this.filters.push({ "orderNumber": { "$lte": val } });
631
  return this;
632
  }
633
 
634
- withOrderNumberBetween(lower: any, upper: any): this {
635
  this.filters.push({ "orderNumber": { "$between": [lower, upper] } });
636
  return this;
637
  }
@@ -675,47 +684,47 @@ export class CustomerOrderRequest {
675
  return this;
676
  }
677
 
678
- withOrderDateIs(val: any): this {
679
  this.filters.push({ "orderDate": { "$eq": val } });
680
  return this;
681
  }
682
 
683
- withOrderDateIsNot(val: any): this {
684
  this.filters.push({ "orderDate": { "$ne": val } });
685
  return this;
686
  }
687
 
688
- withOrderDateIn(...vals: any[]): this {
689
  this.filters.push({ "orderDate": { "$in": vals } });
690
  return this;
691
  }
692
 
693
- withOrderDateNotIn(...vals: any[]): this {
694
  this.filters.push({ "orderDate": { "$notIn": vals } });
695
  return this;
696
  }
697
 
698
- withOrderDateGreaterThan(val: any): this {
699
  this.filters.push({ "orderDate": { "$gt": val } });
700
  return this;
701
  }
702
 
703
- withOrderDateGreaterThanOrEqualTo(val: any): this {
704
  this.filters.push({ "orderDate": { "$gte": val } });
705
  return this;
706
  }
707
 
708
- withOrderDateLessThan(val: any): this {
709
  this.filters.push({ "orderDate": { "$lt": val } });
710
  return this;
711
  }
712
 
713
- withOrderDateLessThanOrEqualTo(val: any): this {
714
  this.filters.push({ "orderDate": { "$lte": val } });
715
  return this;
716
  }
717
 
718
- withOrderDateBetween(lower: any, upper: any): this {
719
  this.filters.push({ "orderDate": { "$between": [lower, upper] } });
720
  return this;
721
  }
@@ -730,47 +739,47 @@ export class CustomerOrderRequest {
730
  return this;
731
  }
732
 
733
- withTotalAmountIs(val: any): this {
734
  this.filters.push({ "totalAmount": { "$eq": val } });
735
  return this;
736
  }
737
 
738
- withTotalAmountIsNot(val: any): this {
739
  this.filters.push({ "totalAmount": { "$ne": val } });
740
  return this;
741
  }
742
 
743
- withTotalAmountIn(...vals: any[]): this {
744
  this.filters.push({ "totalAmount": { "$in": vals } });
745
  return this;
746
  }
747
 
748
- withTotalAmountNotIn(...vals: any[]): this {
749
  this.filters.push({ "totalAmount": { "$notIn": vals } });
750
  return this;
751
  }
752
 
753
- withTotalAmountGreaterThan(val: any): this {
754
  this.filters.push({ "totalAmount": { "$gt": val } });
755
  return this;
756
  }
757
 
758
- withTotalAmountGreaterThanOrEqualTo(val: any): this {
759
  this.filters.push({ "totalAmount": { "$gte": val } });
760
  return this;
761
  }
762
 
763
- withTotalAmountLessThan(val: any): this {
764
  this.filters.push({ "totalAmount": { "$lt": val } });
765
  return this;
766
  }
767
 
768
- withTotalAmountLessThanOrEqualTo(val: any): this {
769
  this.filters.push({ "totalAmount": { "$lte": val } });
770
  return this;
771
  }
772
 
773
- withTotalAmountBetween(lower: any, upper: any): this {
774
  this.filters.push({ "totalAmount": { "$between": [lower, upper] } });
775
  return this;
776
  }
@@ -785,47 +794,47 @@ export class CustomerOrderRequest {
785
  return this;
786
  }
787
 
788
- withVersionIs(val: any): this {
789
  this.filters.push({ "version": { "$eq": val } });
790
  return this;
791
  }
792
 
793
- withVersionIsNot(val: any): this {
794
  this.filters.push({ "version": { "$ne": val } });
795
  return this;
796
  }
797
 
798
- withVersionIn(...vals: any[]): this {
799
  this.filters.push({ "version": { "$in": vals } });
800
  return this;
801
  }
802
 
803
- withVersionNotIn(...vals: any[]): this {
804
  this.filters.push({ "version": { "$notIn": vals } });
805
  return this;
806
  }
807
 
808
- withVersionGreaterThan(val: any): this {
809
  this.filters.push({ "version": { "$gt": val } });
810
  return this;
811
  }
812
 
813
- withVersionGreaterThanOrEqualTo(val: any): this {
814
  this.filters.push({ "version": { "$gte": val } });
815
  return this;
816
  }
817
 
818
- withVersionLessThan(val: any): this {
819
  this.filters.push({ "version": { "$lt": val } });
820
  return this;
821
  }
822
 
823
- withVersionLessThanOrEqualTo(val: any): this {
824
  this.filters.push({ "version": { "$lte": val } });
825
  return this;
826
  }
827
 
828
- withVersionBetween(lower: any, upper: any): this {
829
  this.filters.push({ "version": { "$between": [lower, upper] } });
830
  return this;
831
  }
@@ -980,7 +989,7 @@ export class CustomerOrderRequest {
980
  }
981
 
982
  groupByIdAs(retName: string): this {
983
- this.query.groupBy("id"); // In TS we don't alias group by yet natively
984
  return this;
985
  }
986
  groupByCustomer(): this {
@@ -989,7 +998,7 @@ export class CustomerOrderRequest {
989
  }
990
 
991
  groupByCustomerAs(retName: string): this {
992
- this.query.groupBy("customer"); // In TS we don't alias group by yet natively
993
  return this;
994
  }
995
  groupByStatus(): this {
@@ -998,7 +1007,7 @@ export class CustomerOrderRequest {
998
  }
999
 
1000
  groupByStatusAs(retName: string): this {
1001
- this.query.groupBy("status"); // In TS we don't alias group by yet natively
1002
  return this;
1003
  }
1004
  groupByOrderNumber(): this {
@@ -1007,7 +1016,7 @@ export class CustomerOrderRequest {
1007
  }
1008
 
1009
  groupByOrderNumberAs(retName: string): this {
1010
- this.query.groupBy("orderNumber"); // In TS we don't alias group by yet natively
1011
  return this;
1012
  }
1013
  groupByOrderDate(): this {
@@ -1016,7 +1025,7 @@ export class CustomerOrderRequest {
1016
  }
1017
 
1018
  groupByOrderDateAs(retName: string): this {
1019
- this.query.groupBy("orderDate"); // In TS we don't alias group by yet natively
1020
  return this;
1021
  }
1022
  groupByTotalAmount(): this {
@@ -1025,7 +1034,7 @@ export class CustomerOrderRequest {
1025
  }
1026
 
1027
  groupByTotalAmountAs(retName: string): this {
1028
- this.query.groupBy("totalAmount"); // In TS we don't alias group by yet natively
1029
  return this;
1030
  }
1031
  groupByVersion(): this {
@@ -1034,14 +1043,14 @@ export class CustomerOrderRequest {
1034
  }
1035
 
1036
  groupByVersionAs(retName: string): this {
1037
- this.query.groupBy("version"); // In TS we don't alias group by yet natively
1038
  return this;
1039
  }
1040
 
1041
  // --- Facets ---
1042
  facetByCustomerAs(
1043
  facetName: string,
1044
- request: { toQuery(): SelectQuery },
1045
  includeAllFacets = true,
1046
  ): this {
1047
  this.query.facetBy(facetName, "customer", request, includeAllFacets,
@@ -1051,7 +1060,7 @@ export class CustomerOrderRequest {
1051
 
1052
  facetByStatusAs(
1053
  facetName: string,
1054
- request: { toQuery(): SelectQuery },
1055
  includeAllFacets = true,
1056
  ): this {
1057
  this.query.facetBy(facetName, "status", request, includeAllFacets,
@@ -1167,9 +1176,10 @@ export class ExecutableCustomerOrderRequest {
1167
  return this;
1168
  }
1169
 
1170
- newEntity(context: UserContext): CustomerOrder {
1171
  this.ensureIntent();
1172
- return new CustomerOrder();
 
1173
  }
1174
 
1175
  executeForList(context: UserContext): Promise<SmartList<CustomerOrder>> {
 
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { CustomerOrder } from '../models/CustomerOrder';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
 
7
 
 
25
  else this.selectSelfFields();
26
  }
27
 
28
+ get entityName(): "CustomerOrder" {
29
+ return "CustomerOrder";
30
+ }
31
+
32
  comment(c: string): this {
33
  this.query.comment(c);
34
  this._comment = c;
 
104
  }
105
 
106
  withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
  this.filters = this.filters.filter(filter => !("version" in filter));
109
  return this;
110
  }
111
 
112
  deletedRowsOnly(): this {
113
  this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
  this.filters.push({ version: { "$lte": -1 } });
116
  return this;
117
  }
 
149
  }
150
 
151
 
152
+ selectCustomerWith(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this {
153
  this.query.select(["customer"]);
154
  this.query.relationQuery(
155
  "customer", request.toQuery(), "customer", "id", false,
156
  { kind: "relation-select", method: "selectCustomerWith", relation: "customer" });
157
  return this;
158
  }
159
+ selectStatusWith(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
160
  this.query.select(["status"]);
161
  this.query.relationQuery(
162
  "status", request.toQuery(), "status", "id", false,
 
164
  return this;
165
  }
166
 
167
+ withCustomerMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this {
168
  this.filters.push({
169
  "customer": {
170
  "$inSubquery": { query: request.toQuery(), field: "id" },
 
173
  return this;
174
  }
175
 
176
+ withoutCustomerMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this {
177
  this.filters.push({
178
  "customer": {
179
  "$notInSubquery": { query: request.toQuery(), field: "id" },
 
181
  });
182
  return this;
183
  }
184
+ withStatusMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
185
  this.filters.push({
186
  "status": {
187
  "$inSubquery": { query: request.toQuery(), field: "id" },
 
190
  return this;
191
  }
192
 
193
+ withoutStatusMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
194
  this.filters.push({
195
  "status": {
196
  "$notInSubquery": { query: request.toQuery(), field: "id" },
 
199
  return this;
200
  }
201
 
202
+ selectOrderItemListWith(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
203
  this.query.relationQuery(
204
  "orderItemList", request.toQuery(), "id", "customerOrder", true,
205
  { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" });
 
208
 
209
  haveOrderItems(): this {
210
  return this.withOrderItemListMatching({
211
+ entityName: "OrderItem",
212
  toQuery: () => new SelectQuery("OrderItem"),
213
  });
214
  }
215
 
216
  haveNoOrderItems(): this {
217
  return this.withoutOrderItemListMatching({
218
+ entityName: "OrderItem",
219
  toQuery: () => new SelectQuery("OrderItem"),
220
  });
221
  }
222
 
223
+ withOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
224
  this.filters.push({
225
  "id": {
226
  "$inSubquery": {
 
231
  return this;
232
  }
233
 
234
+ withoutOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
235
  this.filters.push({
236
  "id": {
237
  "$notInSubquery": {
 
248
 
249
  countOrderItemsAs(alias: string): this {
250
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
251
+ this.countOrderItemsWith(alias, { entityName: "OrderItem", toQuery: () => query });
252
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
253
  kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias };
254
  return this;
255
  }
256
 
257
+ countOrderItemsWith(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
258
  const query = child.toQuery().clone();
259
  query.aggregateItems = [];
260
  query.aggregate("Count", "id", alias);
 
266
  minQuantityOfOrderItems(): this {
267
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
268
  return this.minQuantityOfOrderItemsAs(
269
+ "minOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
270
  }
271
 
272
+ minQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
273
  const query = child.toQuery().clone();
274
  query.aggregateItems = [];
275
  query.aggregate("min", "quantity", alias);
 
280
  maxQuantityOfOrderItems(): this {
281
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
282
  return this.maxQuantityOfOrderItemsAs(
283
+ "maxOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
284
  }
285
 
286
+ maxQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
287
  const query = child.toQuery().clone();
288
  query.aggregateItems = [];
289
  query.aggregate("max", "quantity", alias);
 
294
  sumQuantityOfOrderItems(): this {
295
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
296
  return this.sumQuantityOfOrderItemsAs(
297
+ "sumOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
298
  }
299
 
300
+ sumQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
301
  const query = child.toQuery().clone();
302
  query.aggregateItems = [];
303
  query.aggregate("sum", "quantity", alias);
 
308
  avgQuantityOfOrderItems(): this {
309
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
310
  return this.avgQuantityOfOrderItemsAs(
311
+ "avgOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
312
  }
313
 
314
+ avgQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
315
  const query = child.toQuery().clone();
316
  query.aggregateItems = [];
317
  query.aggregate("avg", "quantity", alias);
 
322
  standardDeviationQuantityOfOrderItems(): this {
323
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
324
  return this.standardDeviationQuantityOfOrderItemsAs(
325
+ "standardDeviationOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
326
  }
327
 
328
+ standardDeviationQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
329
  const query = child.toQuery().clone();
330
  query.aggregateItems = [];
331
  query.aggregate("stddev", "quantity", alias);
 
336
  squareRootOfPopulationStandardDeviationQuantityOfOrderItems(): this {
337
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
338
  return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(
339
+ "squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
340
  }
341
 
342
+ squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
343
  const query = child.toQuery().clone();
344
  query.aggregateItems = [];
345
  query.aggregate("stddev_pop", "quantity", alias);
 
350
  sampleVarianceQuantityOfOrderItems(): this {
351
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
352
  return this.sampleVarianceQuantityOfOrderItemsAs(
353
+ "sampleVarianceOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
354
  }
355
 
356
+ sampleVarianceQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
357
  const query = child.toQuery().clone();
358
  query.aggregateItems = [];
359
  query.aggregate("var_samp", "quantity", alias);
 
364
  samplePopulationVarianceQuantityOfOrderItems(): this {
365
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
366
  return this.samplePopulationVarianceQuantityOfOrderItemsAs(
367
+ "samplePopulationVarianceOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
368
  }
369
 
370
+ samplePopulationVarianceQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
371
  const query = child.toQuery().clone();
372
  query.aggregateItems = [];
373
  query.aggregate("var_pop", "quantity", alias);
 
378
  minUnitPriceOfOrderItems(): this {
379
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
380
  return this.minUnitPriceOfOrderItemsAs(
381
+ "minOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
382
  }
383
 
384
+ minUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
385
  const query = child.toQuery().clone();
386
  query.aggregateItems = [];
387
  query.aggregate("min", "unitPrice", alias);
 
392
  maxUnitPriceOfOrderItems(): this {
393
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
394
  return this.maxUnitPriceOfOrderItemsAs(
395
+ "maxOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
396
  }
397
 
398
+ maxUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
399
  const query = child.toQuery().clone();
400
  query.aggregateItems = [];
401
  query.aggregate("max", "unitPrice", alias);
 
406
  sumUnitPriceOfOrderItems(): this {
407
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
408
  return this.sumUnitPriceOfOrderItemsAs(
409
+ "sumOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
410
  }
411
 
412
+ sumUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
413
  const query = child.toQuery().clone();
414
  query.aggregateItems = [];
415
  query.aggregate("sum", "unitPrice", alias);
 
420
  avgUnitPriceOfOrderItems(): this {
421
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
422
  return this.avgUnitPriceOfOrderItemsAs(
423
+ "avgOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
424
  }
425
 
426
+ avgUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
427
  const query = child.toQuery().clone();
428
  query.aggregateItems = [];
429
  query.aggregate("avg", "unitPrice", alias);
 
434
  standardDeviationUnitPriceOfOrderItems(): this {
435
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
436
  return this.standardDeviationUnitPriceOfOrderItemsAs(
437
+ "standardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
438
  }
439
 
440
+ standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
441
  const query = child.toQuery().clone();
442
  query.aggregateItems = [];
443
  query.aggregate("stddev", "unitPrice", alias);
 
448
  squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this {
449
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
450
  return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(
451
+ "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
452
  }
453
 
454
+ squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
455
  const query = child.toQuery().clone();
456
  query.aggregateItems = [];
457
  query.aggregate("stddev_pop", "unitPrice", alias);
 
462
  sampleVarianceUnitPriceOfOrderItems(): this {
463
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
464
  return this.sampleVarianceUnitPriceOfOrderItemsAs(
465
+ "sampleVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
466
  }
467
 
468
+ sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
469
  const query = child.toQuery().clone();
470
  query.aggregateItems = [];
471
  query.aggregate("var_samp", "unitPrice", alias);
 
476
  samplePopulationVarianceUnitPriceOfOrderItems(): this {
477
  const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
478
  return this.samplePopulationVarianceUnitPriceOfOrderItemsAs(
479
+ "samplePopulationVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
480
  }
481
 
482
+ samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
483
  const query = child.toQuery().clone();
484
  query.aggregateItems = [];
485
  query.aggregate("var_pop", "unitPrice", alias);
 
488
  return this;
489
  }
490
 
491
+ withIdIs(val: string): this {
492
  this.filters.push({ "id": { "$eq": val } });
493
  return this;
494
  }
495
 
496
+ withIdIsNot(val: string): this {
497
  this.filters.push({ "id": { "$ne": val } });
498
  return this;
499
  }
500
 
501
+ withIdIn(...vals: string[]): this {
502
  this.filters.push({ "id": { "$in": vals } });
503
  return this;
504
  }
505
 
506
+ withIdNotIn(...vals: string[]): this {
507
  this.filters.push({ "id": { "$notIn": vals } });
508
  return this;
509
  }
510
 
511
+ withIdGreaterThan(val: string): this {
512
  this.filters.push({ "id": { "$gt": val } });
513
  return this;
514
  }
515
 
516
+ withIdGreaterThanOrEqualTo(val: string): this {
517
  this.filters.push({ "id": { "$gte": val } });
518
  return this;
519
  }
520
 
521
+ withIdLessThan(val: string): this {
522
  this.filters.push({ "id": { "$lt": val } });
523
  return this;
524
  }
525
 
526
+ withIdLessThanOrEqualTo(val: string): this {
527
  this.filters.push({ "id": { "$lte": val } });
528
  return this;
529
  }
530
 
531
+ withIdBetween(lower: string, upper: string): this {
532
  this.filters.push({ "id": { "$between": [lower, upper] } });
533
  return this;
534
  }
 
605
  return this;
606
  }
607
 
608
+ withOrderNumberIsNot(val: string): this {
609
  this.filters.push({ "orderNumber": { "$ne": val } });
610
  return this;
611
  }
612
 
613
+ withOrderNumberIn(...vals: string[]): this {
614
  this.filters.push({ "orderNumber": { "$in": vals } });
615
  return this;
616
  }
617
 
618
+ withOrderNumberNotIn(...vals: string[]): this {
619
  this.filters.push({ "orderNumber": { "$notIn": vals } });
620
  return this;
621
  }
622
 
623
+ withOrderNumberGreaterThan(val: string): this {
624
  this.filters.push({ "orderNumber": { "$gt": val } });
625
  return this;
626
  }
627
 
628
+ withOrderNumberGreaterThanOrEqualTo(val: string): this {
629
  this.filters.push({ "orderNumber": { "$gte": val } });
630
  return this;
631
  }
632
 
633
+ withOrderNumberLessThan(val: string): this {
634
  this.filters.push({ "orderNumber": { "$lt": val } });
635
  return this;
636
  }
637
 
638
+ withOrderNumberLessThanOrEqualTo(val: string): this {
639
  this.filters.push({ "orderNumber": { "$lte": val } });
640
  return this;
641
  }
642
 
643
+ withOrderNumberBetween(lower: string, upper: string): this {
644
  this.filters.push({ "orderNumber": { "$between": [lower, upper] } });
645
  return this;
646
  }
 
684
  return this;
685
  }
686
 
687
+ withOrderDateIs(val: string): this {
688
  this.filters.push({ "orderDate": { "$eq": val } });
689
  return this;
690
  }
691
 
692
+ withOrderDateIsNot(val: string): this {
693
  this.filters.push({ "orderDate": { "$ne": val } });
694
  return this;
695
  }
696
 
697
+ withOrderDateIn(...vals: string[]): this {
698
  this.filters.push({ "orderDate": { "$in": vals } });
699
  return this;
700
  }
701
 
702
+ withOrderDateNotIn(...vals: string[]): this {
703
  this.filters.push({ "orderDate": { "$notIn": vals } });
704
  return this;
705
  }
706
 
707
+ withOrderDateGreaterThan(val: string): this {
708
  this.filters.push({ "orderDate": { "$gt": val } });
709
  return this;
710
  }
711
 
712
+ withOrderDateGreaterThanOrEqualTo(val: string): this {
713
  this.filters.push({ "orderDate": { "$gte": val } });
714
  return this;
715
  }
716
 
717
+ withOrderDateLessThan(val: string): this {
718
  this.filters.push({ "orderDate": { "$lt": val } });
719
  return this;
720
  }
721
 
722
+ withOrderDateLessThanOrEqualTo(val: string): this {
723
  this.filters.push({ "orderDate": { "$lte": val } });
724
  return this;
725
  }
726
 
727
+ withOrderDateBetween(lower: string, upper: string): this {
728
  this.filters.push({ "orderDate": { "$between": [lower, upper] } });
729
  return this;
730
  }
 
739
  return this;
740
  }
741
 
742
+ withTotalAmountIs(val: Decimal): this {
743
  this.filters.push({ "totalAmount": { "$eq": val } });
744
  return this;
745
  }
746
 
747
+ withTotalAmountIsNot(val: Decimal): this {
748
  this.filters.push({ "totalAmount": { "$ne": val } });
749
  return this;
750
  }
751
 
752
+ withTotalAmountIn(...vals: Decimal[]): this {
753
  this.filters.push({ "totalAmount": { "$in": vals } });
754
  return this;
755
  }
756
 
757
+ withTotalAmountNotIn(...vals: Decimal[]): this {
758
  this.filters.push({ "totalAmount": { "$notIn": vals } });
759
  return this;
760
  }
761
 
762
+ withTotalAmountGreaterThan(val: Decimal): this {
763
  this.filters.push({ "totalAmount": { "$gt": val } });
764
  return this;
765
  }
766
 
767
+ withTotalAmountGreaterThanOrEqualTo(val: Decimal): this {
768
  this.filters.push({ "totalAmount": { "$gte": val } });
769
  return this;
770
  }
771
 
772
+ withTotalAmountLessThan(val: Decimal): this {
773
  this.filters.push({ "totalAmount": { "$lt": val } });
774
  return this;
775
  }
776
 
777
+ withTotalAmountLessThanOrEqualTo(val: Decimal): this {
778
  this.filters.push({ "totalAmount": { "$lte": val } });
779
  return this;
780
  }
781
 
782
+ withTotalAmountBetween(lower: Decimal, upper: Decimal): this {
783
  this.filters.push({ "totalAmount": { "$between": [lower, upper] } });
784
  return this;
785
  }
 
794
  return this;
795
  }
796
 
797
+ withVersionIs(val: unknown): this {
798
  this.filters.push({ "version": { "$eq": val } });
799
  return this;
800
  }
801
 
802
+ withVersionIsNot(val: unknown): this {
803
  this.filters.push({ "version": { "$ne": val } });
804
  return this;
805
  }
806
 
807
+ withVersionIn(...vals: unknown[]): this {
808
  this.filters.push({ "version": { "$in": vals } });
809
  return this;
810
  }
811
 
812
+ withVersionNotIn(...vals: unknown[]): this {
813
  this.filters.push({ "version": { "$notIn": vals } });
814
  return this;
815
  }
816
 
817
+ withVersionGreaterThan(val: unknown): this {
818
  this.filters.push({ "version": { "$gt": val } });
819
  return this;
820
  }
821
 
822
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
823
  this.filters.push({ "version": { "$gte": val } });
824
  return this;
825
  }
826
 
827
+ withVersionLessThan(val: unknown): this {
828
  this.filters.push({ "version": { "$lt": val } });
829
  return this;
830
  }
831
 
832
+ withVersionLessThanOrEqualTo(val: unknown): this {
833
  this.filters.push({ "version": { "$lte": val } });
834
  return this;
835
  }
836
 
837
+ withVersionBetween(lower: unknown, upper: unknown): this {
838
  this.filters.push({ "version": { "$between": [lower, upper] } });
839
  return this;
840
  }
 
989
  }
990
 
991
  groupByIdAs(retName: string): this {
992
+ this.query.groupBy("id", retName);
993
  return this;
994
  }
995
  groupByCustomer(): this {
 
998
  }
999
 
1000
  groupByCustomerAs(retName: string): this {
1001
+ this.query.groupBy("customer", retName);
1002
  return this;
1003
  }
1004
  groupByStatus(): this {
 
1007
  }
1008
 
1009
  groupByStatusAs(retName: string): this {
1010
+ this.query.groupBy("status", retName);
1011
  return this;
1012
  }
1013
  groupByOrderNumber(): this {
 
1016
  }
1017
 
1018
  groupByOrderNumberAs(retName: string): this {
1019
+ this.query.groupBy("orderNumber", retName);
1020
  return this;
1021
  }
1022
  groupByOrderDate(): this {
 
1025
  }
1026
 
1027
  groupByOrderDateAs(retName: string): this {
1028
+ this.query.groupBy("orderDate", retName);
1029
  return this;
1030
  }
1031
  groupByTotalAmount(): this {
 
1034
  }
1035
 
1036
  groupByTotalAmountAs(retName: string): this {
1037
+ this.query.groupBy("totalAmount", retName);
1038
  return this;
1039
  }
1040
  groupByVersion(): this {
 
1043
  }
1044
 
1045
  groupByVersionAs(retName: string): this {
1046
+ this.query.groupBy("version", retName);
1047
  return this;
1048
  }
1049
 
1050
  // --- Facets ---
1051
  facetByCustomerAs(
1052
  facetName: string,
1053
+ request: { readonly entityName: "Customer"; toQuery(): SelectQuery },
1054
  includeAllFacets = true,
1055
  ): this {
1056
  this.query.facetBy(facetName, "customer", request, includeAllFacets,
 
1060
 
1061
  facetByStatusAs(
1062
  facetName: string,
1063
+ request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery },
1064
  includeAllFacets = true,
1065
  ): this {
1066
  this.query.facetBy(facetName, "status", request, includeAllFacets,
 
1176
  return this;
1177
  }
1178
 
1179
+ async newEntity(context: UserContext): Promise<CustomerOrder> {
1180
  this.ensureIntent();
1181
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
1182
+ return CustomerOrder.teaqlCreate(context);
1183
  }
1184
 
1185
  executeForList(context: UserContext): Promise<SmartList<CustomerOrder>> {
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { Customer } from '../models/Customer';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
 
4
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
 
6
 
@@ -24,6 +25,10 @@ export class CustomerRequest {
24
  else this.selectSelfFields();
25
  }
26
 
 
 
 
 
27
  comment(c: string): this {
28
  this.query.comment(c);
29
  this._comment = c;
@@ -99,12 +104,14 @@ export class CustomerRequest {
99
  }
100
 
101
  withDeletedRows(): this {
 
102
  this.filters = this.filters.filter(filter => !("version" in filter));
103
  return this;
104
  }
105
 
106
  deletedRowsOnly(): this {
107
  this.withDeletedRows();
 
108
  this.filters.push({ version: { "$lte": -1 } });
109
  return this;
110
  }
@@ -131,7 +138,7 @@ export class CustomerRequest {
131
  }
132
 
133
 
134
- selectPlatformWith(request: { toQuery(): SelectQuery }): this {
135
  this.query.select(["platform"]);
136
  this.query.relationQuery(
137
  "platform", request.toQuery(), "platform", "id", false,
@@ -139,7 +146,7 @@ export class CustomerRequest {
139
  return this;
140
  }
141
 
142
- withPlatformMatching(request: { toQuery(): SelectQuery }): this {
143
  this.filters.push({
144
  "platform": {
145
  "$inSubquery": { query: request.toQuery(), field: "id" },
@@ -148,7 +155,7 @@ export class CustomerRequest {
148
  return this;
149
  }
150
 
151
- withoutPlatformMatching(request: { toQuery(): SelectQuery }): this {
152
  this.filters.push({
153
  "platform": {
154
  "$notInSubquery": { query: request.toQuery(), field: "id" },
@@ -157,7 +164,7 @@ export class CustomerRequest {
157
  return this;
158
  }
159
 
160
- selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this {
161
  this.query.relationQuery(
162
  "customerOrderList", request.toQuery(), "id", "customer", true,
163
  { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" });
@@ -166,17 +173,19 @@ export class CustomerRequest {
166
 
167
  haveCustomerOrders(): this {
168
  return this.withCustomerOrderListMatching({
 
169
  toQuery: () => new SelectQuery("CustomerOrder"),
170
  });
171
  }
172
 
173
  haveNoCustomerOrders(): this {
174
  return this.withoutCustomerOrderListMatching({
 
175
  toQuery: () => new SelectQuery("CustomerOrder"),
176
  });
177
  }
178
 
179
- withCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
180
  this.filters.push({
181
  "id": {
182
  "$inSubquery": {
@@ -187,7 +196,7 @@ export class CustomerRequest {
187
  return this;
188
  }
189
 
190
- withoutCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
191
  this.filters.push({
192
  "id": {
193
  "$notInSubquery": {
@@ -204,13 +213,13 @@ export class CustomerRequest {
204
 
205
  countCustomerOrdersAs(alias: string): this {
206
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
207
- this.countCustomerOrdersWith(alias, { toQuery: () => query });
208
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
209
  kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias };
210
  return this;
211
  }
212
 
213
- countCustomerOrdersWith(alias: string, child: { toQuery(): SelectQuery }): this {
214
  const query = child.toQuery().clone();
215
  query.aggregateItems = [];
216
  query.aggregate("Count", "id", alias);
@@ -222,10 +231,10 @@ export class CustomerRequest {
222
  minTotalAmountOfCustomerOrders(): this {
223
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
224
  return this.minTotalAmountOfCustomerOrdersAs(
225
- "minOfTotalAmountOfCustomerOrders", { toQuery: () => query });
226
  }
227
 
228
- minTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
229
  const query = child.toQuery().clone();
230
  query.aggregateItems = [];
231
  query.aggregate("min", "totalAmount", alias);
@@ -236,10 +245,10 @@ export class CustomerRequest {
236
  maxTotalAmountOfCustomerOrders(): this {
237
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
238
  return this.maxTotalAmountOfCustomerOrdersAs(
239
- "maxOfTotalAmountOfCustomerOrders", { toQuery: () => query });
240
  }
241
 
242
- maxTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
243
  const query = child.toQuery().clone();
244
  query.aggregateItems = [];
245
  query.aggregate("max", "totalAmount", alias);
@@ -250,10 +259,10 @@ export class CustomerRequest {
250
  sumTotalAmountOfCustomerOrders(): this {
251
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
252
  return this.sumTotalAmountOfCustomerOrdersAs(
253
- "sumOfTotalAmountOfCustomerOrders", { toQuery: () => query });
254
  }
255
 
256
- sumTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
257
  const query = child.toQuery().clone();
258
  query.aggregateItems = [];
259
  query.aggregate("sum", "totalAmount", alias);
@@ -264,10 +273,10 @@ export class CustomerRequest {
264
  avgTotalAmountOfCustomerOrders(): this {
265
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
266
  return this.avgTotalAmountOfCustomerOrdersAs(
267
- "avgOfTotalAmountOfCustomerOrders", { toQuery: () => query });
268
  }
269
 
270
- avgTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
271
  const query = child.toQuery().clone();
272
  query.aggregateItems = [];
273
  query.aggregate("avg", "totalAmount", alias);
@@ -278,10 +287,10 @@ export class CustomerRequest {
278
  standardDeviationTotalAmountOfCustomerOrders(): this {
279
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
280
  return this.standardDeviationTotalAmountOfCustomerOrdersAs(
281
- "standardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
282
  }
283
 
284
- standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
285
  const query = child.toQuery().clone();
286
  query.aggregateItems = [];
287
  query.aggregate("stddev", "totalAmount", alias);
@@ -292,10 +301,10 @@ export class CustomerRequest {
292
  squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this {
293
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
294
  return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(
295
- "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
296
  }
297
 
298
- squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
299
  const query = child.toQuery().clone();
300
  query.aggregateItems = [];
301
  query.aggregate("stddev_pop", "totalAmount", alias);
@@ -306,10 +315,10 @@ export class CustomerRequest {
306
  sampleVarianceTotalAmountOfCustomerOrders(): this {
307
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
308
  return this.sampleVarianceTotalAmountOfCustomerOrdersAs(
309
- "sampleVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
310
  }
311
 
312
- sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
313
  const query = child.toQuery().clone();
314
  query.aggregateItems = [];
315
  query.aggregate("var_samp", "totalAmount", alias);
@@ -320,10 +329,10 @@ export class CustomerRequest {
320
  samplePopulationVarianceTotalAmountOfCustomerOrders(): this {
321
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
322
  return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs(
323
- "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
324
  }
325
 
326
- samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
327
  const query = child.toQuery().clone();
328
  query.aggregateItems = [];
329
  query.aggregate("var_pop", "totalAmount", alias);
@@ -332,47 +341,47 @@ export class CustomerRequest {
332
  return this;
333
  }
334
 
335
- withIdIs(val: any): this {
336
  this.filters.push({ "id": { "$eq": val } });
337
  return this;
338
  }
339
 
340
- withIdIsNot(val: any): this {
341
  this.filters.push({ "id": { "$ne": val } });
342
  return this;
343
  }
344
 
345
- withIdIn(...vals: any[]): this {
346
  this.filters.push({ "id": { "$in": vals } });
347
  return this;
348
  }
349
 
350
- withIdNotIn(...vals: any[]): this {
351
  this.filters.push({ "id": { "$notIn": vals } });
352
  return this;
353
  }
354
 
355
- withIdGreaterThan(val: any): this {
356
  this.filters.push({ "id": { "$gt": val } });
357
  return this;
358
  }
359
 
360
- withIdGreaterThanOrEqualTo(val: any): this {
361
  this.filters.push({ "id": { "$gte": val } });
362
  return this;
363
  }
364
 
365
- withIdLessThan(val: any): this {
366
  this.filters.push({ "id": { "$lt": val } });
367
  return this;
368
  }
369
 
370
- withIdLessThanOrEqualTo(val: any): this {
371
  this.filters.push({ "id": { "$lte": val } });
372
  return this;
373
  }
374
 
375
- withIdBetween(lower: any, upper: any): this {
376
  this.filters.push({ "id": { "$between": [lower, upper] } });
377
  return this;
378
  }
@@ -417,42 +426,42 @@ export class CustomerRequest {
417
  return this;
418
  }
419
 
420
- withNameIsNot(val: any): this {
421
  this.filters.push({ "name": { "$ne": val } });
422
  return this;
423
  }
424
 
425
- withNameIn(...vals: any[]): this {
426
  this.filters.push({ "name": { "$in": vals } });
427
  return this;
428
  }
429
 
430
- withNameNotIn(...vals: any[]): this {
431
  this.filters.push({ "name": { "$notIn": vals } });
432
  return this;
433
  }
434
 
435
- withNameGreaterThan(val: any): this {
436
  this.filters.push({ "name": { "$gt": val } });
437
  return this;
438
  }
439
 
440
- withNameGreaterThanOrEqualTo(val: any): this {
441
  this.filters.push({ "name": { "$gte": val } });
442
  return this;
443
  }
444
 
445
- withNameLessThan(val: any): this {
446
  this.filters.push({ "name": { "$lt": val } });
447
  return this;
448
  }
449
 
450
- withNameLessThanOrEqualTo(val: any): this {
451
  this.filters.push({ "name": { "$lte": val } });
452
  return this;
453
  }
454
 
455
- withNameBetween(lower: any, upper: any): this {
456
  this.filters.push({ "name": { "$between": [lower, upper] } });
457
  return this;
458
  }
@@ -496,47 +505,47 @@ export class CustomerRequest {
496
  return this;
497
  }
498
 
499
- withVersionIs(val: any): this {
500
  this.filters.push({ "version": { "$eq": val } });
501
  return this;
502
  }
503
 
504
- withVersionIsNot(val: any): this {
505
  this.filters.push({ "version": { "$ne": val } });
506
  return this;
507
  }
508
 
509
- withVersionIn(...vals: any[]): this {
510
  this.filters.push({ "version": { "$in": vals } });
511
  return this;
512
  }
513
 
514
- withVersionNotIn(...vals: any[]): this {
515
  this.filters.push({ "version": { "$notIn": vals } });
516
  return this;
517
  }
518
 
519
- withVersionGreaterThan(val: any): this {
520
  this.filters.push({ "version": { "$gt": val } });
521
  return this;
522
  }
523
 
524
- withVersionGreaterThanOrEqualTo(val: any): this {
525
  this.filters.push({ "version": { "$gte": val } });
526
  return this;
527
  }
528
 
529
- withVersionLessThan(val: any): this {
530
  this.filters.push({ "version": { "$lt": val } });
531
  return this;
532
  }
533
 
534
- withVersionLessThanOrEqualTo(val: any): this {
535
  this.filters.push({ "version": { "$lte": val } });
536
  return this;
537
  }
538
 
539
- withVersionBetween(lower: any, upper: any): this {
540
  this.filters.push({ "version": { "$between": [lower, upper] } });
541
  return this;
542
  }
@@ -606,7 +615,7 @@ export class CustomerRequest {
606
  }
607
 
608
  groupByIdAs(retName: string): this {
609
- this.query.groupBy("id"); // In TS we don't alias group by yet natively
610
  return this;
611
  }
612
  groupByPlatform(): this {
@@ -615,7 +624,7 @@ export class CustomerRequest {
615
  }
616
 
617
  groupByPlatformAs(retName: string): this {
618
- this.query.groupBy("platform"); // In TS we don't alias group by yet natively
619
  return this;
620
  }
621
  groupByName(): this {
@@ -624,7 +633,7 @@ export class CustomerRequest {
624
  }
625
 
626
  groupByNameAs(retName: string): this {
627
- this.query.groupBy("name"); // In TS we don't alias group by yet natively
628
  return this;
629
  }
630
  groupByVersion(): this {
@@ -633,14 +642,14 @@ export class CustomerRequest {
633
  }
634
 
635
  groupByVersionAs(retName: string): this {
636
- this.query.groupBy("version"); // In TS we don't alias group by yet natively
637
  return this;
638
  }
639
 
640
  // --- Facets ---
641
  facetByPlatformAs(
642
  facetName: string,
643
- request: { toQuery(): SelectQuery },
644
  includeAllFacets = true,
645
  ): this {
646
  this.query.facetBy(facetName, "platform", request, includeAllFacets,
@@ -756,9 +765,10 @@ export class ExecutableCustomerRequest {
756
  return this;
757
  }
758
 
759
- newEntity(context: UserContext): Customer {
760
  this.ensureIntent();
761
- return new Customer();
 
762
  }
763
 
764
  executeForList(context: UserContext): Promise<SmartList<Customer>> {
 
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { Customer } from '../models/Customer';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
 
7
 
 
25
  else this.selectSelfFields();
26
  }
27
 
28
+ get entityName(): "Customer" {
29
+ return "Customer";
30
+ }
31
+
32
  comment(c: string): this {
33
  this.query.comment(c);
34
  this._comment = c;
 
104
  }
105
 
106
  withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
  this.filters = this.filters.filter(filter => !("version" in filter));
109
  return this;
110
  }
111
 
112
  deletedRowsOnly(): this {
113
  this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
  this.filters.push({ version: { "$lte": -1 } });
116
  return this;
117
  }
 
138
  }
139
 
140
 
141
+ selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this {
142
  this.query.select(["platform"]);
143
  this.query.relationQuery(
144
  "platform", request.toQuery(), "platform", "id", false,
 
146
  return this;
147
  }
148
 
149
+ withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this {
150
  this.filters.push({
151
  "platform": {
152
  "$inSubquery": { query: request.toQuery(), field: "id" },
 
155
  return this;
156
  }
157
 
158
+ withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this {
159
  this.filters.push({
160
  "platform": {
161
  "$notInSubquery": { query: request.toQuery(), field: "id" },
 
164
  return this;
165
  }
166
 
167
+ selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
168
  this.query.relationQuery(
169
  "customerOrderList", request.toQuery(), "id", "customer", true,
170
  { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" });
 
173
 
174
  haveCustomerOrders(): this {
175
  return this.withCustomerOrderListMatching({
176
+ entityName: "CustomerOrder",
177
  toQuery: () => new SelectQuery("CustomerOrder"),
178
  });
179
  }
180
 
181
  haveNoCustomerOrders(): this {
182
  return this.withoutCustomerOrderListMatching({
183
+ entityName: "CustomerOrder",
184
  toQuery: () => new SelectQuery("CustomerOrder"),
185
  });
186
  }
187
 
188
+ withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
189
  this.filters.push({
190
  "id": {
191
  "$inSubquery": {
 
196
  return this;
197
  }
198
 
199
+ withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
200
  this.filters.push({
201
  "id": {
202
  "$notInSubquery": {
 
213
 
214
  countCustomerOrdersAs(alias: string): this {
215
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
216
+ this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query });
217
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
218
  kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias };
219
  return this;
220
  }
221
 
222
+ countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
223
  const query = child.toQuery().clone();
224
  query.aggregateItems = [];
225
  query.aggregate("Count", "id", alias);
 
231
  minTotalAmountOfCustomerOrders(): this {
232
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
233
  return this.minTotalAmountOfCustomerOrdersAs(
234
+ "minOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
235
  }
236
 
237
+ minTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
238
  const query = child.toQuery().clone();
239
  query.aggregateItems = [];
240
  query.aggregate("min", "totalAmount", alias);
 
245
  maxTotalAmountOfCustomerOrders(): this {
246
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
247
  return this.maxTotalAmountOfCustomerOrdersAs(
248
+ "maxOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
249
  }
250
 
251
+ maxTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
252
  const query = child.toQuery().clone();
253
  query.aggregateItems = [];
254
  query.aggregate("max", "totalAmount", alias);
 
259
  sumTotalAmountOfCustomerOrders(): this {
260
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
261
  return this.sumTotalAmountOfCustomerOrdersAs(
262
+ "sumOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
263
  }
264
 
265
+ sumTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
266
  const query = child.toQuery().clone();
267
  query.aggregateItems = [];
268
  query.aggregate("sum", "totalAmount", alias);
 
273
  avgTotalAmountOfCustomerOrders(): this {
274
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
275
  return this.avgTotalAmountOfCustomerOrdersAs(
276
+ "avgOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
277
  }
278
 
279
+ avgTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
280
  const query = child.toQuery().clone();
281
  query.aggregateItems = [];
282
  query.aggregate("avg", "totalAmount", alias);
 
287
  standardDeviationTotalAmountOfCustomerOrders(): this {
288
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
289
  return this.standardDeviationTotalAmountOfCustomerOrdersAs(
290
+ "standardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
291
  }
292
 
293
+ standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
294
  const query = child.toQuery().clone();
295
  query.aggregateItems = [];
296
  query.aggregate("stddev", "totalAmount", alias);
 
301
  squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this {
302
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
303
  return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(
304
+ "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
305
  }
306
 
307
+ squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
308
  const query = child.toQuery().clone();
309
  query.aggregateItems = [];
310
  query.aggregate("stddev_pop", "totalAmount", alias);
 
315
  sampleVarianceTotalAmountOfCustomerOrders(): this {
316
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
317
  return this.sampleVarianceTotalAmountOfCustomerOrdersAs(
318
+ "sampleVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
319
  }
320
 
321
+ sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
322
  const query = child.toQuery().clone();
323
  query.aggregateItems = [];
324
  query.aggregate("var_samp", "totalAmount", alias);
 
329
  samplePopulationVarianceTotalAmountOfCustomerOrders(): this {
330
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
331
  return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs(
332
+ "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
333
  }
334
 
335
+ samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
336
  const query = child.toQuery().clone();
337
  query.aggregateItems = [];
338
  query.aggregate("var_pop", "totalAmount", alias);
 
341
  return this;
342
  }
343
 
344
+ withIdIs(val: string): this {
345
  this.filters.push({ "id": { "$eq": val } });
346
  return this;
347
  }
348
 
349
+ withIdIsNot(val: string): this {
350
  this.filters.push({ "id": { "$ne": val } });
351
  return this;
352
  }
353
 
354
+ withIdIn(...vals: string[]): this {
355
  this.filters.push({ "id": { "$in": vals } });
356
  return this;
357
  }
358
 
359
+ withIdNotIn(...vals: string[]): this {
360
  this.filters.push({ "id": { "$notIn": vals } });
361
  return this;
362
  }
363
 
364
+ withIdGreaterThan(val: string): this {
365
  this.filters.push({ "id": { "$gt": val } });
366
  return this;
367
  }
368
 
369
+ withIdGreaterThanOrEqualTo(val: string): this {
370
  this.filters.push({ "id": { "$gte": val } });
371
  return this;
372
  }
373
 
374
+ withIdLessThan(val: string): this {
375
  this.filters.push({ "id": { "$lt": val } });
376
  return this;
377
  }
378
 
379
+ withIdLessThanOrEqualTo(val: string): this {
380
  this.filters.push({ "id": { "$lte": val } });
381
  return this;
382
  }
383
 
384
+ withIdBetween(lower: string, upper: string): this {
385
  this.filters.push({ "id": { "$between": [lower, upper] } });
386
  return this;
387
  }
 
426
  return this;
427
  }
428
 
429
+ withNameIsNot(val: string): this {
430
  this.filters.push({ "name": { "$ne": val } });
431
  return this;
432
  }
433
 
434
+ withNameIn(...vals: string[]): this {
435
  this.filters.push({ "name": { "$in": vals } });
436
  return this;
437
  }
438
 
439
+ withNameNotIn(...vals: string[]): this {
440
  this.filters.push({ "name": { "$notIn": vals } });
441
  return this;
442
  }
443
 
444
+ withNameGreaterThan(val: string): this {
445
  this.filters.push({ "name": { "$gt": val } });
446
  return this;
447
  }
448
 
449
+ withNameGreaterThanOrEqualTo(val: string): this {
450
  this.filters.push({ "name": { "$gte": val } });
451
  return this;
452
  }
453
 
454
+ withNameLessThan(val: string): this {
455
  this.filters.push({ "name": { "$lt": val } });
456
  return this;
457
  }
458
 
459
+ withNameLessThanOrEqualTo(val: string): this {
460
  this.filters.push({ "name": { "$lte": val } });
461
  return this;
462
  }
463
 
464
+ withNameBetween(lower: string, upper: string): this {
465
  this.filters.push({ "name": { "$between": [lower, upper] } });
466
  return this;
467
  }
 
505
  return this;
506
  }
507
 
508
+ withVersionIs(val: unknown): this {
509
  this.filters.push({ "version": { "$eq": val } });
510
  return this;
511
  }
512
 
513
+ withVersionIsNot(val: unknown): this {
514
  this.filters.push({ "version": { "$ne": val } });
515
  return this;
516
  }
517
 
518
+ withVersionIn(...vals: unknown[]): this {
519
  this.filters.push({ "version": { "$in": vals } });
520
  return this;
521
  }
522
 
523
+ withVersionNotIn(...vals: unknown[]): this {
524
  this.filters.push({ "version": { "$notIn": vals } });
525
  return this;
526
  }
527
 
528
+ withVersionGreaterThan(val: unknown): this {
529
  this.filters.push({ "version": { "$gt": val } });
530
  return this;
531
  }
532
 
533
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
534
  this.filters.push({ "version": { "$gte": val } });
535
  return this;
536
  }
537
 
538
+ withVersionLessThan(val: unknown): this {
539
  this.filters.push({ "version": { "$lt": val } });
540
  return this;
541
  }
542
 
543
+ withVersionLessThanOrEqualTo(val: unknown): this {
544
  this.filters.push({ "version": { "$lte": val } });
545
  return this;
546
  }
547
 
548
+ withVersionBetween(lower: unknown, upper: unknown): this {
549
  this.filters.push({ "version": { "$between": [lower, upper] } });
550
  return this;
551
  }
 
615
  }
616
 
617
  groupByIdAs(retName: string): this {
618
+ this.query.groupBy("id", retName);
619
  return this;
620
  }
621
  groupByPlatform(): this {
 
624
  }
625
 
626
  groupByPlatformAs(retName: string): this {
627
+ this.query.groupBy("platform", retName);
628
  return this;
629
  }
630
  groupByName(): this {
 
633
  }
634
 
635
  groupByNameAs(retName: string): this {
636
+ this.query.groupBy("name", retName);
637
  return this;
638
  }
639
  groupByVersion(): this {
 
642
  }
643
 
644
  groupByVersionAs(retName: string): this {
645
+ this.query.groupBy("version", retName);
646
  return this;
647
  }
648
 
649
  // --- Facets ---
650
  facetByPlatformAs(
651
  facetName: string,
652
+ request: { readonly entityName: "Platform"; toQuery(): SelectQuery },
653
  includeAllFacets = true,
654
  ): this {
655
  this.query.facetBy(facetName, "platform", request, includeAllFacets,
 
765
  return this;
766
  }
767
 
768
+ async newEntity(context: UserContext): Promise<Customer> {
769
  this.ensureIntent();
770
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
771
+ return Customer.teaqlCreate(context);
772
  }
773
 
774
  executeForList(context: UserContext): Promise<SmartList<Customer>> {
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { OrderItem } from '../models/OrderItem';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
 
4
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
 
6
 
@@ -24,6 +25,10 @@ export class OrderItemRequest {
24
  else this.selectSelfFields();
25
  }
26
 
 
 
 
 
27
  comment(c: string): this {
28
  this.query.comment(c);
29
  this._comment = c;
@@ -99,12 +104,14 @@ export class OrderItemRequest {
99
  }
100
 
101
  withDeletedRows(): this {
 
102
  this.filters = this.filters.filter(filter => !("version" in filter));
103
  return this;
104
  }
105
 
106
  deletedRowsOnly(): this {
107
  this.withDeletedRows();
 
108
  this.filters.push({ version: { "$lte": -1 } });
109
  return this;
110
  }
@@ -141,7 +148,7 @@ export class OrderItemRequest {
141
  }
142
 
143
 
144
- selectCustomerOrderWith(request: { toQuery(): SelectQuery }): this {
145
  this.query.select(["customerOrder"]);
146
  this.query.relationQuery(
147
  "customerOrder", request.toQuery(), "customerOrder", "id", false,
@@ -149,7 +156,7 @@ export class OrderItemRequest {
149
  return this;
150
  }
151
 
152
- withCustomerOrderMatching(request: { toQuery(): SelectQuery }): this {
153
  this.filters.push({
154
  "customerOrder": {
155
  "$inSubquery": { query: request.toQuery(), field: "id" },
@@ -158,7 +165,7 @@ export class OrderItemRequest {
158
  return this;
159
  }
160
 
161
- withoutCustomerOrderMatching(request: { toQuery(): SelectQuery }): this {
162
  this.filters.push({
163
  "customerOrder": {
164
  "$notInSubquery": { query: request.toQuery(), field: "id" },
@@ -170,47 +177,47 @@ export class OrderItemRequest {
170
 
171
 
172
 
173
- withIdIs(val: any): this {
174
  this.filters.push({ "id": { "$eq": val } });
175
  return this;
176
  }
177
 
178
- withIdIsNot(val: any): this {
179
  this.filters.push({ "id": { "$ne": val } });
180
  return this;
181
  }
182
 
183
- withIdIn(...vals: any[]): this {
184
  this.filters.push({ "id": { "$in": vals } });
185
  return this;
186
  }
187
 
188
- withIdNotIn(...vals: any[]): this {
189
  this.filters.push({ "id": { "$notIn": vals } });
190
  return this;
191
  }
192
 
193
- withIdGreaterThan(val: any): this {
194
  this.filters.push({ "id": { "$gt": val } });
195
  return this;
196
  }
197
 
198
- withIdGreaterThanOrEqualTo(val: any): this {
199
  this.filters.push({ "id": { "$gte": val } });
200
  return this;
201
  }
202
 
203
- withIdLessThan(val: any): this {
204
  this.filters.push({ "id": { "$lt": val } });
205
  return this;
206
  }
207
 
208
- withIdLessThanOrEqualTo(val: any): this {
209
  this.filters.push({ "id": { "$lte": val } });
210
  return this;
211
  }
212
 
213
- withIdBetween(lower: any, upper: any): this {
214
  this.filters.push({ "id": { "$between": [lower, upper] } });
215
  return this;
216
  }
@@ -255,42 +262,42 @@ export class OrderItemRequest {
255
  return this;
256
  }
257
 
258
- withProductNameIsNot(val: any): this {
259
  this.filters.push({ "productName": { "$ne": val } });
260
  return this;
261
  }
262
 
263
- withProductNameIn(...vals: any[]): this {
264
  this.filters.push({ "productName": { "$in": vals } });
265
  return this;
266
  }
267
 
268
- withProductNameNotIn(...vals: any[]): this {
269
  this.filters.push({ "productName": { "$notIn": vals } });
270
  return this;
271
  }
272
 
273
- withProductNameGreaterThan(val: any): this {
274
  this.filters.push({ "productName": { "$gt": val } });
275
  return this;
276
  }
277
 
278
- withProductNameGreaterThanOrEqualTo(val: any): this {
279
  this.filters.push({ "productName": { "$gte": val } });
280
  return this;
281
  }
282
 
283
- withProductNameLessThan(val: any): this {
284
  this.filters.push({ "productName": { "$lt": val } });
285
  return this;
286
  }
287
 
288
- withProductNameLessThanOrEqualTo(val: any): this {
289
  this.filters.push({ "productName": { "$lte": val } });
290
  return this;
291
  }
292
 
293
- withProductNameBetween(lower: any, upper: any): this {
294
  this.filters.push({ "productName": { "$between": [lower, upper] } });
295
  return this;
296
  }
@@ -334,47 +341,47 @@ export class OrderItemRequest {
334
  return this;
335
  }
336
 
337
- withQuantityIs(val: any): this {
338
  this.filters.push({ "quantity": { "$eq": val } });
339
  return this;
340
  }
341
 
342
- withQuantityIsNot(val: any): this {
343
  this.filters.push({ "quantity": { "$ne": val } });
344
  return this;
345
  }
346
 
347
- withQuantityIn(...vals: any[]): this {
348
  this.filters.push({ "quantity": { "$in": vals } });
349
  return this;
350
  }
351
 
352
- withQuantityNotIn(...vals: any[]): this {
353
  this.filters.push({ "quantity": { "$notIn": vals } });
354
  return this;
355
  }
356
 
357
- withQuantityGreaterThan(val: any): this {
358
  this.filters.push({ "quantity": { "$gt": val } });
359
  return this;
360
  }
361
 
362
- withQuantityGreaterThanOrEqualTo(val: any): this {
363
  this.filters.push({ "quantity": { "$gte": val } });
364
  return this;
365
  }
366
 
367
- withQuantityLessThan(val: any): this {
368
  this.filters.push({ "quantity": { "$lt": val } });
369
  return this;
370
  }
371
 
372
- withQuantityLessThanOrEqualTo(val: any): this {
373
  this.filters.push({ "quantity": { "$lte": val } });
374
  return this;
375
  }
376
 
377
- withQuantityBetween(lower: any, upper: any): this {
378
  this.filters.push({ "quantity": { "$between": [lower, upper] } });
379
  return this;
380
  }
@@ -389,47 +396,47 @@ export class OrderItemRequest {
389
  return this;
390
  }
391
 
392
- withUnitPriceIs(val: any): this {
393
  this.filters.push({ "unitPrice": { "$eq": val } });
394
  return this;
395
  }
396
 
397
- withUnitPriceIsNot(val: any): this {
398
  this.filters.push({ "unitPrice": { "$ne": val } });
399
  return this;
400
  }
401
 
402
- withUnitPriceIn(...vals: any[]): this {
403
  this.filters.push({ "unitPrice": { "$in": vals } });
404
  return this;
405
  }
406
 
407
- withUnitPriceNotIn(...vals: any[]): this {
408
  this.filters.push({ "unitPrice": { "$notIn": vals } });
409
  return this;
410
  }
411
 
412
- withUnitPriceGreaterThan(val: any): this {
413
  this.filters.push({ "unitPrice": { "$gt": val } });
414
  return this;
415
  }
416
 
417
- withUnitPriceGreaterThanOrEqualTo(val: any): this {
418
  this.filters.push({ "unitPrice": { "$gte": val } });
419
  return this;
420
  }
421
 
422
- withUnitPriceLessThan(val: any): this {
423
  this.filters.push({ "unitPrice": { "$lt": val } });
424
  return this;
425
  }
426
 
427
- withUnitPriceLessThanOrEqualTo(val: any): this {
428
  this.filters.push({ "unitPrice": { "$lte": val } });
429
  return this;
430
  }
431
 
432
- withUnitPriceBetween(lower: any, upper: any): this {
433
  this.filters.push({ "unitPrice": { "$between": [lower, upper] } });
434
  return this;
435
  }
@@ -444,47 +451,47 @@ export class OrderItemRequest {
444
  return this;
445
  }
446
 
447
- withVersionIs(val: any): this {
448
  this.filters.push({ "version": { "$eq": val } });
449
  return this;
450
  }
451
 
452
- withVersionIsNot(val: any): this {
453
  this.filters.push({ "version": { "$ne": val } });
454
  return this;
455
  }
456
 
457
- withVersionIn(...vals: any[]): this {
458
  this.filters.push({ "version": { "$in": vals } });
459
  return this;
460
  }
461
 
462
- withVersionNotIn(...vals: any[]): this {
463
  this.filters.push({ "version": { "$notIn": vals } });
464
  return this;
465
  }
466
 
467
- withVersionGreaterThan(val: any): this {
468
  this.filters.push({ "version": { "$gt": val } });
469
  return this;
470
  }
471
 
472
- withVersionGreaterThanOrEqualTo(val: any): this {
473
  this.filters.push({ "version": { "$gte": val } });
474
  return this;
475
  }
476
 
477
- withVersionLessThan(val: any): this {
478
  this.filters.push({ "version": { "$lt": val } });
479
  return this;
480
  }
481
 
482
- withVersionLessThanOrEqualTo(val: any): this {
483
  this.filters.push({ "version": { "$lte": val } });
484
  return this;
485
  }
486
 
487
- withVersionBetween(lower: any, upper: any): this {
488
  this.filters.push({ "version": { "$between": [lower, upper] } });
489
  return this;
490
  }
@@ -702,7 +709,7 @@ export class OrderItemRequest {
702
  }
703
 
704
  groupByIdAs(retName: string): this {
705
- this.query.groupBy("id"); // In TS we don't alias group by yet natively
706
  return this;
707
  }
708
  groupByCustomerOrder(): this {
@@ -711,7 +718,7 @@ export class OrderItemRequest {
711
  }
712
 
713
  groupByCustomerOrderAs(retName: string): this {
714
- this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively
715
  return this;
716
  }
717
  groupByProductName(): this {
@@ -720,7 +727,7 @@ export class OrderItemRequest {
720
  }
721
 
722
  groupByProductNameAs(retName: string): this {
723
- this.query.groupBy("productName"); // In TS we don't alias group by yet natively
724
  return this;
725
  }
726
  groupByQuantity(): this {
@@ -729,7 +736,7 @@ export class OrderItemRequest {
729
  }
730
 
731
  groupByQuantityAs(retName: string): this {
732
- this.query.groupBy("quantity"); // In TS we don't alias group by yet natively
733
  return this;
734
  }
735
  groupByUnitPrice(): this {
@@ -738,7 +745,7 @@ export class OrderItemRequest {
738
  }
739
 
740
  groupByUnitPriceAs(retName: string): this {
741
- this.query.groupBy("unitPrice"); // In TS we don't alias group by yet natively
742
  return this;
743
  }
744
  groupByVersion(): this {
@@ -747,14 +754,14 @@ export class OrderItemRequest {
747
  }
748
 
749
  groupByVersionAs(retName: string): this {
750
- this.query.groupBy("version"); // In TS we don't alias group by yet natively
751
  return this;
752
  }
753
 
754
  // --- Facets ---
755
  facetByCustomerOrderAs(
756
  facetName: string,
757
- request: { toQuery(): SelectQuery },
758
  includeAllFacets = true,
759
  ): this {
760
  this.query.facetBy(facetName, "customerOrder", request, includeAllFacets,
@@ -870,9 +877,10 @@ export class ExecutableOrderItemRequest {
870
  return this;
871
  }
872
 
873
- newEntity(context: UserContext): OrderItem {
874
  this.ensureIntent();
875
- return new OrderItem();
 
876
  }
877
 
878
  executeForList(context: UserContext): Promise<SmartList<OrderItem>> {
 
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { OrderItem } from '../models/OrderItem';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
 
7
 
 
25
  else this.selectSelfFields();
26
  }
27
 
28
+ get entityName(): "OrderItem" {
29
+ return "OrderItem";
30
+ }
31
+
32
  comment(c: string): this {
33
  this.query.comment(c);
34
  this._comment = c;
 
104
  }
105
 
106
  withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
  this.filters = this.filters.filter(filter => !("version" in filter));
109
  return this;
110
  }
111
 
112
  deletedRowsOnly(): this {
113
  this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
  this.filters.push({ version: { "$lte": -1 } });
116
  return this;
117
  }
 
148
  }
149
 
150
 
151
+ selectCustomerOrderWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
152
  this.query.select(["customerOrder"]);
153
  this.query.relationQuery(
154
  "customerOrder", request.toQuery(), "customerOrder", "id", false,
 
156
  return this;
157
  }
158
 
159
+ withCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
160
  this.filters.push({
161
  "customerOrder": {
162
  "$inSubquery": { query: request.toQuery(), field: "id" },
 
165
  return this;
166
  }
167
 
168
+ withoutCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
169
  this.filters.push({
170
  "customerOrder": {
171
  "$notInSubquery": { query: request.toQuery(), field: "id" },
 
177
 
178
 
179
 
180
+ withIdIs(val: string): this {
181
  this.filters.push({ "id": { "$eq": val } });
182
  return this;
183
  }
184
 
185
+ withIdIsNot(val: string): this {
186
  this.filters.push({ "id": { "$ne": val } });
187
  return this;
188
  }
189
 
190
+ withIdIn(...vals: string[]): this {
191
  this.filters.push({ "id": { "$in": vals } });
192
  return this;
193
  }
194
 
195
+ withIdNotIn(...vals: string[]): this {
196
  this.filters.push({ "id": { "$notIn": vals } });
197
  return this;
198
  }
199
 
200
+ withIdGreaterThan(val: string): this {
201
  this.filters.push({ "id": { "$gt": val } });
202
  return this;
203
  }
204
 
205
+ withIdGreaterThanOrEqualTo(val: string): this {
206
  this.filters.push({ "id": { "$gte": val } });
207
  return this;
208
  }
209
 
210
+ withIdLessThan(val: string): this {
211
  this.filters.push({ "id": { "$lt": val } });
212
  return this;
213
  }
214
 
215
+ withIdLessThanOrEqualTo(val: string): this {
216
  this.filters.push({ "id": { "$lte": val } });
217
  return this;
218
  }
219
 
220
+ withIdBetween(lower: string, upper: string): this {
221
  this.filters.push({ "id": { "$between": [lower, upper] } });
222
  return this;
223
  }
 
262
  return this;
263
  }
264
 
265
+ withProductNameIsNot(val: string): this {
266
  this.filters.push({ "productName": { "$ne": val } });
267
  return this;
268
  }
269
 
270
+ withProductNameIn(...vals: string[]): this {
271
  this.filters.push({ "productName": { "$in": vals } });
272
  return this;
273
  }
274
 
275
+ withProductNameNotIn(...vals: string[]): this {
276
  this.filters.push({ "productName": { "$notIn": vals } });
277
  return this;
278
  }
279
 
280
+ withProductNameGreaterThan(val: string): this {
281
  this.filters.push({ "productName": { "$gt": val } });
282
  return this;
283
  }
284
 
285
+ withProductNameGreaterThanOrEqualTo(val: string): this {
286
  this.filters.push({ "productName": { "$gte": val } });
287
  return this;
288
  }
289
 
290
+ withProductNameLessThan(val: string): this {
291
  this.filters.push({ "productName": { "$lt": val } });
292
  return this;
293
  }
294
 
295
+ withProductNameLessThanOrEqualTo(val: string): this {
296
  this.filters.push({ "productName": { "$lte": val } });
297
  return this;
298
  }
299
 
300
+ withProductNameBetween(lower: string, upper: string): this {
301
  this.filters.push({ "productName": { "$between": [lower, upper] } });
302
  return this;
303
  }
 
341
  return this;
342
  }
343
 
344
+ withQuantityIs(val: number): this {
345
  this.filters.push({ "quantity": { "$eq": val } });
346
  return this;
347
  }
348
 
349
+ withQuantityIsNot(val: number): this {
350
  this.filters.push({ "quantity": { "$ne": val } });
351
  return this;
352
  }
353
 
354
+ withQuantityIn(...vals: number[]): this {
355
  this.filters.push({ "quantity": { "$in": vals } });
356
  return this;
357
  }
358
 
359
+ withQuantityNotIn(...vals: number[]): this {
360
  this.filters.push({ "quantity": { "$notIn": vals } });
361
  return this;
362
  }
363
 
364
+ withQuantityGreaterThan(val: number): this {
365
  this.filters.push({ "quantity": { "$gt": val } });
366
  return this;
367
  }
368
 
369
+ withQuantityGreaterThanOrEqualTo(val: number): this {
370
  this.filters.push({ "quantity": { "$gte": val } });
371
  return this;
372
  }
373
 
374
+ withQuantityLessThan(val: number): this {
375
  this.filters.push({ "quantity": { "$lt": val } });
376
  return this;
377
  }
378
 
379
+ withQuantityLessThanOrEqualTo(val: number): this {
380
  this.filters.push({ "quantity": { "$lte": val } });
381
  return this;
382
  }
383
 
384
+ withQuantityBetween(lower: number, upper: number): this {
385
  this.filters.push({ "quantity": { "$between": [lower, upper] } });
386
  return this;
387
  }
 
396
  return this;
397
  }
398
 
399
+ withUnitPriceIs(val: Decimal): this {
400
  this.filters.push({ "unitPrice": { "$eq": val } });
401
  return this;
402
  }
403
 
404
+ withUnitPriceIsNot(val: Decimal): this {
405
  this.filters.push({ "unitPrice": { "$ne": val } });
406
  return this;
407
  }
408
 
409
+ withUnitPriceIn(...vals: Decimal[]): this {
410
  this.filters.push({ "unitPrice": { "$in": vals } });
411
  return this;
412
  }
413
 
414
+ withUnitPriceNotIn(...vals: Decimal[]): this {
415
  this.filters.push({ "unitPrice": { "$notIn": vals } });
416
  return this;
417
  }
418
 
419
+ withUnitPriceGreaterThan(val: Decimal): this {
420
  this.filters.push({ "unitPrice": { "$gt": val } });
421
  return this;
422
  }
423
 
424
+ withUnitPriceGreaterThanOrEqualTo(val: Decimal): this {
425
  this.filters.push({ "unitPrice": { "$gte": val } });
426
  return this;
427
  }
428
 
429
+ withUnitPriceLessThan(val: Decimal): this {
430
  this.filters.push({ "unitPrice": { "$lt": val } });
431
  return this;
432
  }
433
 
434
+ withUnitPriceLessThanOrEqualTo(val: Decimal): this {
435
  this.filters.push({ "unitPrice": { "$lte": val } });
436
  return this;
437
  }
438
 
439
+ withUnitPriceBetween(lower: Decimal, upper: Decimal): this {
440
  this.filters.push({ "unitPrice": { "$between": [lower, upper] } });
441
  return this;
442
  }
 
451
  return this;
452
  }
453
 
454
+ withVersionIs(val: unknown): this {
455
  this.filters.push({ "version": { "$eq": val } });
456
  return this;
457
  }
458
 
459
+ withVersionIsNot(val: unknown): this {
460
  this.filters.push({ "version": { "$ne": val } });
461
  return this;
462
  }
463
 
464
+ withVersionIn(...vals: unknown[]): this {
465
  this.filters.push({ "version": { "$in": vals } });
466
  return this;
467
  }
468
 
469
+ withVersionNotIn(...vals: unknown[]): this {
470
  this.filters.push({ "version": { "$notIn": vals } });
471
  return this;
472
  }
473
 
474
+ withVersionGreaterThan(val: unknown): this {
475
  this.filters.push({ "version": { "$gt": val } });
476
  return this;
477
  }
478
 
479
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
480
  this.filters.push({ "version": { "$gte": val } });
481
  return this;
482
  }
483
 
484
+ withVersionLessThan(val: unknown): this {
485
  this.filters.push({ "version": { "$lt": val } });
486
  return this;
487
  }
488
 
489
+ withVersionLessThanOrEqualTo(val: unknown): this {
490
  this.filters.push({ "version": { "$lte": val } });
491
  return this;
492
  }
493
 
494
+ withVersionBetween(lower: unknown, upper: unknown): this {
495
  this.filters.push({ "version": { "$between": [lower, upper] } });
496
  return this;
497
  }
 
709
  }
710
 
711
  groupByIdAs(retName: string): this {
712
+ this.query.groupBy("id", retName);
713
  return this;
714
  }
715
  groupByCustomerOrder(): this {
 
718
  }
719
 
720
  groupByCustomerOrderAs(retName: string): this {
721
+ this.query.groupBy("customerOrder", retName);
722
  return this;
723
  }
724
  groupByProductName(): this {
 
727
  }
728
 
729
  groupByProductNameAs(retName: string): this {
730
+ this.query.groupBy("productName", retName);
731
  return this;
732
  }
733
  groupByQuantity(): this {
 
736
  }
737
 
738
  groupByQuantityAs(retName: string): this {
739
+ this.query.groupBy("quantity", retName);
740
  return this;
741
  }
742
  groupByUnitPrice(): this {
 
745
  }
746
 
747
  groupByUnitPriceAs(retName: string): this {
748
+ this.query.groupBy("unitPrice", retName);
749
  return this;
750
  }
751
  groupByVersion(): this {
 
754
  }
755
 
756
  groupByVersionAs(retName: string): this {
757
+ this.query.groupBy("version", retName);
758
  return this;
759
  }
760
 
761
  // --- Facets ---
762
  facetByCustomerOrderAs(
763
  facetName: string,
764
+ request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery },
765
  includeAllFacets = true,
766
  ): this {
767
  this.query.facetBy(facetName, "customerOrder", request, includeAllFacets,
 
877
  return this;
878
  }
879
 
880
+ async newEntity(context: UserContext): Promise<OrderItem> {
881
  this.ensureIntent();
882
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
883
+ return OrderItem.teaqlCreate(context);
884
  }
885
 
886
  executeForList(context: UserContext): Promise<SmartList<OrderItem>> {
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { OrderStatus } from '../models/OrderStatus';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
 
4
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
 
6
 
@@ -24,6 +25,10 @@ export class OrderStatusRequest {
24
  else this.selectSelfFields();
25
  }
26
 
 
 
 
 
27
  comment(c: string): this {
28
  this.query.comment(c);
29
  this._comment = c;
@@ -99,12 +104,14 @@ export class OrderStatusRequest {
99
  }
100
 
101
  withDeletedRows(): this {
 
102
  this.filters = this.filters.filter(filter => !("version" in filter));
103
  return this;
104
  }
105
 
106
  deletedRowsOnly(): this {
107
  this.withDeletedRows();
 
108
  this.filters.push({ version: { "$lte": -1 } });
109
  return this;
110
  }
@@ -145,7 +152,7 @@ export class OrderStatusRequest {
145
  }
146
 
147
 
148
- selectPlatformWith(request: { toQuery(): SelectQuery }): this {
149
  this.query.select(["platform"]);
150
  this.query.relationQuery(
151
  "platform", request.toQuery(), "platform", "id", false,
@@ -153,7 +160,7 @@ export class OrderStatusRequest {
153
  return this;
154
  }
155
 
156
- withPlatformMatching(request: { toQuery(): SelectQuery }): this {
157
  this.filters.push({
158
  "platform": {
159
  "$inSubquery": { query: request.toQuery(), field: "id" },
@@ -162,7 +169,7 @@ export class OrderStatusRequest {
162
  return this;
163
  }
164
 
165
- withoutPlatformMatching(request: { toQuery(): SelectQuery }): this {
166
  this.filters.push({
167
  "platform": {
168
  "$notInSubquery": { query: request.toQuery(), field: "id" },
@@ -171,7 +178,7 @@ export class OrderStatusRequest {
171
  return this;
172
  }
173
 
174
- selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this {
175
  this.query.relationQuery(
176
  "customerOrderList", request.toQuery(), "id", "status", true,
177
  { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" });
@@ -180,17 +187,19 @@ export class OrderStatusRequest {
180
 
181
  haveCustomerOrders(): this {
182
  return this.withCustomerOrderListMatching({
 
183
  toQuery: () => new SelectQuery("CustomerOrder"),
184
  });
185
  }
186
 
187
  haveNoCustomerOrders(): this {
188
  return this.withoutCustomerOrderListMatching({
 
189
  toQuery: () => new SelectQuery("CustomerOrder"),
190
  });
191
  }
192
 
193
- withCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
194
  this.filters.push({
195
  "id": {
196
  "$inSubquery": {
@@ -201,7 +210,7 @@ export class OrderStatusRequest {
201
  return this;
202
  }
203
 
204
- withoutCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
205
  this.filters.push({
206
  "id": {
207
  "$notInSubquery": {
@@ -218,13 +227,13 @@ export class OrderStatusRequest {
218
 
219
  countCustomerOrdersAs(alias: string): this {
220
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
221
- this.countCustomerOrdersWith(alias, { toQuery: () => query });
222
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
223
  kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias };
224
  return this;
225
  }
226
 
227
- countCustomerOrdersWith(alias: string, child: { toQuery(): SelectQuery }): this {
228
  const query = child.toQuery().clone();
229
  query.aggregateItems = [];
230
  query.aggregate("Count", "id", alias);
@@ -236,10 +245,10 @@ export class OrderStatusRequest {
236
  minTotalAmountOfCustomerOrders(): this {
237
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
238
  return this.minTotalAmountOfCustomerOrdersAs(
239
- "minOfTotalAmountOfCustomerOrders", { toQuery: () => query });
240
  }
241
 
242
- minTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
243
  const query = child.toQuery().clone();
244
  query.aggregateItems = [];
245
  query.aggregate("min", "totalAmount", alias);
@@ -250,10 +259,10 @@ export class OrderStatusRequest {
250
  maxTotalAmountOfCustomerOrders(): this {
251
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
252
  return this.maxTotalAmountOfCustomerOrdersAs(
253
- "maxOfTotalAmountOfCustomerOrders", { toQuery: () => query });
254
  }
255
 
256
- maxTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
257
  const query = child.toQuery().clone();
258
  query.aggregateItems = [];
259
  query.aggregate("max", "totalAmount", alias);
@@ -264,10 +273,10 @@ export class OrderStatusRequest {
264
  sumTotalAmountOfCustomerOrders(): this {
265
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
266
  return this.sumTotalAmountOfCustomerOrdersAs(
267
- "sumOfTotalAmountOfCustomerOrders", { toQuery: () => query });
268
  }
269
 
270
- sumTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
271
  const query = child.toQuery().clone();
272
  query.aggregateItems = [];
273
  query.aggregate("sum", "totalAmount", alias);
@@ -278,10 +287,10 @@ export class OrderStatusRequest {
278
  avgTotalAmountOfCustomerOrders(): this {
279
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
280
  return this.avgTotalAmountOfCustomerOrdersAs(
281
- "avgOfTotalAmountOfCustomerOrders", { toQuery: () => query });
282
  }
283
 
284
- avgTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
285
  const query = child.toQuery().clone();
286
  query.aggregateItems = [];
287
  query.aggregate("avg", "totalAmount", alias);
@@ -292,10 +301,10 @@ export class OrderStatusRequest {
292
  standardDeviationTotalAmountOfCustomerOrders(): this {
293
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
294
  return this.standardDeviationTotalAmountOfCustomerOrdersAs(
295
- "standardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
296
  }
297
 
298
- standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
299
  const query = child.toQuery().clone();
300
  query.aggregateItems = [];
301
  query.aggregate("stddev", "totalAmount", alias);
@@ -306,10 +315,10 @@ export class OrderStatusRequest {
306
  squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this {
307
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
308
  return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(
309
- "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
310
  }
311
 
312
- squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
313
  const query = child.toQuery().clone();
314
  query.aggregateItems = [];
315
  query.aggregate("stddev_pop", "totalAmount", alias);
@@ -320,10 +329,10 @@ export class OrderStatusRequest {
320
  sampleVarianceTotalAmountOfCustomerOrders(): this {
321
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
322
  return this.sampleVarianceTotalAmountOfCustomerOrdersAs(
323
- "sampleVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
324
  }
325
 
326
- sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
327
  const query = child.toQuery().clone();
328
  query.aggregateItems = [];
329
  query.aggregate("var_samp", "totalAmount", alias);
@@ -334,10 +343,10 @@ export class OrderStatusRequest {
334
  samplePopulationVarianceTotalAmountOfCustomerOrders(): this {
335
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
336
  return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs(
337
- "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
338
  }
339
 
340
- samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
341
  const query = child.toQuery().clone();
342
  query.aggregateItems = [];
343
  query.aggregate("var_pop", "totalAmount", alias);
@@ -366,47 +375,47 @@ export class OrderStatusRequest {
366
  return this;
367
  }
368
 
369
- withIdIs(val: any): this {
370
  this.filters.push({ "id": { "$eq": val } });
371
  return this;
372
  }
373
 
374
- withIdIsNot(val: any): this {
375
  this.filters.push({ "id": { "$ne": val } });
376
  return this;
377
  }
378
 
379
- withIdIn(...vals: any[]): this {
380
  this.filters.push({ "id": { "$in": vals } });
381
  return this;
382
  }
383
 
384
- withIdNotIn(...vals: any[]): this {
385
  this.filters.push({ "id": { "$notIn": vals } });
386
  return this;
387
  }
388
 
389
- withIdGreaterThan(val: any): this {
390
  this.filters.push({ "id": { "$gt": val } });
391
  return this;
392
  }
393
 
394
- withIdGreaterThanOrEqualTo(val: any): this {
395
  this.filters.push({ "id": { "$gte": val } });
396
  return this;
397
  }
398
 
399
- withIdLessThan(val: any): this {
400
  this.filters.push({ "id": { "$lt": val } });
401
  return this;
402
  }
403
 
404
- withIdLessThanOrEqualTo(val: any): this {
405
  this.filters.push({ "id": { "$lte": val } });
406
  return this;
407
  }
408
 
409
- withIdBetween(lower: any, upper: any): this {
410
  this.filters.push({ "id": { "$between": [lower, upper] } });
411
  return this;
412
  }
@@ -431,42 +440,42 @@ export class OrderStatusRequest {
431
  return this;
432
  }
433
 
434
- withNameIsNot(val: any): this {
435
  this.filters.push({ "name": { "$ne": val } });
436
  return this;
437
  }
438
 
439
- withNameIn(...vals: any[]): this {
440
  this.filters.push({ "name": { "$in": vals } });
441
  return this;
442
  }
443
 
444
- withNameNotIn(...vals: any[]): this {
445
  this.filters.push({ "name": { "$notIn": vals } });
446
  return this;
447
  }
448
 
449
- withNameGreaterThan(val: any): this {
450
  this.filters.push({ "name": { "$gt": val } });
451
  return this;
452
  }
453
 
454
- withNameGreaterThanOrEqualTo(val: any): this {
455
  this.filters.push({ "name": { "$gte": val } });
456
  return this;
457
  }
458
 
459
- withNameLessThan(val: any): this {
460
  this.filters.push({ "name": { "$lt": val } });
461
  return this;
462
  }
463
 
464
- withNameLessThanOrEqualTo(val: any): this {
465
  this.filters.push({ "name": { "$lte": val } });
466
  return this;
467
  }
468
 
469
- withNameBetween(lower: any, upper: any): this {
470
  this.filters.push({ "name": { "$between": [lower, upper] } });
471
  return this;
472
  }
@@ -520,42 +529,42 @@ export class OrderStatusRequest {
520
  return this;
521
  }
522
 
523
- withCodeIsNot(val: any): this {
524
  this.filters.push({ "code": { "$ne": val } });
525
  return this;
526
  }
527
 
528
- withCodeIn(...vals: any[]): this {
529
  this.filters.push({ "code": { "$in": vals } });
530
  return this;
531
  }
532
 
533
- withCodeNotIn(...vals: any[]): this {
534
  this.filters.push({ "code": { "$notIn": vals } });
535
  return this;
536
  }
537
 
538
- withCodeGreaterThan(val: any): this {
539
  this.filters.push({ "code": { "$gt": val } });
540
  return this;
541
  }
542
 
543
- withCodeGreaterThanOrEqualTo(val: any): this {
544
  this.filters.push({ "code": { "$gte": val } });
545
  return this;
546
  }
547
 
548
- withCodeLessThan(val: any): this {
549
  this.filters.push({ "code": { "$lt": val } });
550
  return this;
551
  }
552
 
553
- withCodeLessThanOrEqualTo(val: any): this {
554
  this.filters.push({ "code": { "$lte": val } });
555
  return this;
556
  }
557
 
558
- withCodeBetween(lower: any, upper: any): this {
559
  this.filters.push({ "code": { "$between": [lower, upper] } });
560
  return this;
561
  }
@@ -609,42 +618,42 @@ export class OrderStatusRequest {
609
  return this;
610
  }
611
 
612
- withColorIsNot(val: any): this {
613
  this.filters.push({ "color": { "$ne": val } });
614
  return this;
615
  }
616
 
617
- withColorIn(...vals: any[]): this {
618
  this.filters.push({ "color": { "$in": vals } });
619
  return this;
620
  }
621
 
622
- withColorNotIn(...vals: any[]): this {
623
  this.filters.push({ "color": { "$notIn": vals } });
624
  return this;
625
  }
626
 
627
- withColorGreaterThan(val: any): this {
628
  this.filters.push({ "color": { "$gt": val } });
629
  return this;
630
  }
631
 
632
- withColorGreaterThanOrEqualTo(val: any): this {
633
  this.filters.push({ "color": { "$gte": val } });
634
  return this;
635
  }
636
 
637
- withColorLessThan(val: any): this {
638
  this.filters.push({ "color": { "$lt": val } });
639
  return this;
640
  }
641
 
642
- withColorLessThanOrEqualTo(val: any): this {
643
  this.filters.push({ "color": { "$lte": val } });
644
  return this;
645
  }
646
 
647
- withColorBetween(lower: any, upper: any): this {
648
  this.filters.push({ "color": { "$between": [lower, upper] } });
649
  return this;
650
  }
@@ -688,47 +697,47 @@ export class OrderStatusRequest {
688
  return this;
689
  }
690
 
691
- withDisplayOrderIs(val: any): this {
692
  this.filters.push({ "displayOrder": { "$eq": val } });
693
  return this;
694
  }
695
 
696
- withDisplayOrderIsNot(val: any): this {
697
  this.filters.push({ "displayOrder": { "$ne": val } });
698
  return this;
699
  }
700
 
701
- withDisplayOrderIn(...vals: any[]): this {
702
  this.filters.push({ "displayOrder": { "$in": vals } });
703
  return this;
704
  }
705
 
706
- withDisplayOrderNotIn(...vals: any[]): this {
707
  this.filters.push({ "displayOrder": { "$notIn": vals } });
708
  return this;
709
  }
710
 
711
- withDisplayOrderGreaterThan(val: any): this {
712
  this.filters.push({ "displayOrder": { "$gt": val } });
713
  return this;
714
  }
715
 
716
- withDisplayOrderGreaterThanOrEqualTo(val: any): this {
717
  this.filters.push({ "displayOrder": { "$gte": val } });
718
  return this;
719
  }
720
 
721
- withDisplayOrderLessThan(val: any): this {
722
  this.filters.push({ "displayOrder": { "$lt": val } });
723
  return this;
724
  }
725
 
726
- withDisplayOrderLessThanOrEqualTo(val: any): this {
727
  this.filters.push({ "displayOrder": { "$lte": val } });
728
  return this;
729
  }
730
 
731
- withDisplayOrderBetween(lower: any, upper: any): this {
732
  this.filters.push({ "displayOrder": { "$between": [lower, upper] } });
733
  return this;
734
  }
@@ -743,47 +752,47 @@ export class OrderStatusRequest {
743
  return this;
744
  }
745
 
746
- withVersionIs(val: any): this {
747
  this.filters.push({ "version": { "$eq": val } });
748
  return this;
749
  }
750
 
751
- withVersionIsNot(val: any): this {
752
  this.filters.push({ "version": { "$ne": val } });
753
  return this;
754
  }
755
 
756
- withVersionIn(...vals: any[]): this {
757
  this.filters.push({ "version": { "$in": vals } });
758
  return this;
759
  }
760
 
761
- withVersionNotIn(...vals: any[]): this {
762
  this.filters.push({ "version": { "$notIn": vals } });
763
  return this;
764
  }
765
 
766
- withVersionGreaterThan(val: any): this {
767
  this.filters.push({ "version": { "$gt": val } });
768
  return this;
769
  }
770
 
771
- withVersionGreaterThanOrEqualTo(val: any): this {
772
  this.filters.push({ "version": { "$gte": val } });
773
  return this;
774
  }
775
 
776
- withVersionLessThan(val: any): this {
777
  this.filters.push({ "version": { "$lt": val } });
778
  return this;
779
  }
780
 
781
- withVersionLessThanOrEqualTo(val: any): this {
782
  this.filters.push({ "version": { "$lte": val } });
783
  return this;
784
  }
785
 
786
- withVersionBetween(lower: any, upper: any): this {
787
  this.filters.push({ "version": { "$between": [lower, upper] } });
788
  return this;
789
  }
@@ -946,7 +955,7 @@ export class OrderStatusRequest {
946
  }
947
 
948
  groupByPlatformAs(retName: string): this {
949
- this.query.groupBy("platform"); // In TS we don't alias group by yet natively
950
  return this;
951
  }
952
  groupById(): this {
@@ -955,7 +964,7 @@ export class OrderStatusRequest {
955
  }
956
 
957
  groupByIdAs(retName: string): this {
958
- this.query.groupBy("id"); // In TS we don't alias group by yet natively
959
  return this;
960
  }
961
  groupByName(): this {
@@ -964,7 +973,7 @@ export class OrderStatusRequest {
964
  }
965
 
966
  groupByNameAs(retName: string): this {
967
- this.query.groupBy("name"); // In TS we don't alias group by yet natively
968
  return this;
969
  }
970
  groupByCode(): this {
@@ -973,7 +982,7 @@ export class OrderStatusRequest {
973
  }
974
 
975
  groupByCodeAs(retName: string): this {
976
- this.query.groupBy("code"); // In TS we don't alias group by yet natively
977
  return this;
978
  }
979
  groupByColor(): this {
@@ -982,7 +991,7 @@ export class OrderStatusRequest {
982
  }
983
 
984
  groupByColorAs(retName: string): this {
985
- this.query.groupBy("color"); // In TS we don't alias group by yet natively
986
  return this;
987
  }
988
  groupByDisplayOrder(): this {
@@ -991,7 +1000,7 @@ export class OrderStatusRequest {
991
  }
992
 
993
  groupByDisplayOrderAs(retName: string): this {
994
- this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively
995
  return this;
996
  }
997
  groupByVersion(): this {
@@ -1000,14 +1009,14 @@ export class OrderStatusRequest {
1000
  }
1001
 
1002
  groupByVersionAs(retName: string): this {
1003
- this.query.groupBy("version"); // In TS we don't alias group by yet natively
1004
  return this;
1005
  }
1006
 
1007
  // --- Facets ---
1008
  facetByPlatformAs(
1009
  facetName: string,
1010
- request: { toQuery(): SelectQuery },
1011
  includeAllFacets = true,
1012
  ): this {
1013
  this.query.facetBy(facetName, "platform", request, includeAllFacets,
@@ -1123,9 +1132,10 @@ export class ExecutableOrderStatusRequest {
1123
  return this;
1124
  }
1125
 
1126
- newEntity(context: UserContext): OrderStatus {
1127
  this.ensureIntent();
1128
- return new OrderStatus();
 
1129
  }
1130
 
1131
  executeForList(context: UserContext): Promise<SmartList<OrderStatus>> {
 
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { OrderStatus } from '../models/OrderStatus';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
 
7
 
 
25
  else this.selectSelfFields();
26
  }
27
 
28
+ get entityName(): "OrderStatus" {
29
+ return "OrderStatus";
30
+ }
31
+
32
  comment(c: string): this {
33
  this.query.comment(c);
34
  this._comment = c;
 
104
  }
105
 
106
  withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
  this.filters = this.filters.filter(filter => !("version" in filter));
109
  return this;
110
  }
111
 
112
  deletedRowsOnly(): this {
113
  this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
  this.filters.push({ version: { "$lte": -1 } });
116
  return this;
117
  }
 
152
  }
153
 
154
 
155
+ selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this {
156
  this.query.select(["platform"]);
157
  this.query.relationQuery(
158
  "platform", request.toQuery(), "platform", "id", false,
 
160
  return this;
161
  }
162
 
163
+ withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this {
164
  this.filters.push({
165
  "platform": {
166
  "$inSubquery": { query: request.toQuery(), field: "id" },
 
169
  return this;
170
  }
171
 
172
+ withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this {
173
  this.filters.push({
174
  "platform": {
175
  "$notInSubquery": { query: request.toQuery(), field: "id" },
 
178
  return this;
179
  }
180
 
181
+ selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
182
  this.query.relationQuery(
183
  "customerOrderList", request.toQuery(), "id", "status", true,
184
  { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" });
 
187
 
188
  haveCustomerOrders(): this {
189
  return this.withCustomerOrderListMatching({
190
+ entityName: "CustomerOrder",
191
  toQuery: () => new SelectQuery("CustomerOrder"),
192
  });
193
  }
194
 
195
  haveNoCustomerOrders(): this {
196
  return this.withoutCustomerOrderListMatching({
197
+ entityName: "CustomerOrder",
198
  toQuery: () => new SelectQuery("CustomerOrder"),
199
  });
200
  }
201
 
202
+ withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
203
  this.filters.push({
204
  "id": {
205
  "$inSubquery": {
 
210
  return this;
211
  }
212
 
213
+ withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
214
  this.filters.push({
215
  "id": {
216
  "$notInSubquery": {
 
227
 
228
  countCustomerOrdersAs(alias: string): this {
229
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
230
+ this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query });
231
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
232
  kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias };
233
  return this;
234
  }
235
 
236
+ countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
237
  const query = child.toQuery().clone();
238
  query.aggregateItems = [];
239
  query.aggregate("Count", "id", alias);
 
245
  minTotalAmountOfCustomerOrders(): this {
246
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
247
  return this.minTotalAmountOfCustomerOrdersAs(
248
+ "minOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
249
  }
250
 
251
+ minTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
252
  const query = child.toQuery().clone();
253
  query.aggregateItems = [];
254
  query.aggregate("min", "totalAmount", alias);
 
259
  maxTotalAmountOfCustomerOrders(): this {
260
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
261
  return this.maxTotalAmountOfCustomerOrdersAs(
262
+ "maxOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
263
  }
264
 
265
+ maxTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
266
  const query = child.toQuery().clone();
267
  query.aggregateItems = [];
268
  query.aggregate("max", "totalAmount", alias);
 
273
  sumTotalAmountOfCustomerOrders(): this {
274
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
275
  return this.sumTotalAmountOfCustomerOrdersAs(
276
+ "sumOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
277
  }
278
 
279
+ sumTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
280
  const query = child.toQuery().clone();
281
  query.aggregateItems = [];
282
  query.aggregate("sum", "totalAmount", alias);
 
287
  avgTotalAmountOfCustomerOrders(): this {
288
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
289
  return this.avgTotalAmountOfCustomerOrdersAs(
290
+ "avgOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
291
  }
292
 
293
+ avgTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
294
  const query = child.toQuery().clone();
295
  query.aggregateItems = [];
296
  query.aggregate("avg", "totalAmount", alias);
 
301
  standardDeviationTotalAmountOfCustomerOrders(): this {
302
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
303
  return this.standardDeviationTotalAmountOfCustomerOrdersAs(
304
+ "standardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
305
  }
306
 
307
+ standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
308
  const query = child.toQuery().clone();
309
  query.aggregateItems = [];
310
  query.aggregate("stddev", "totalAmount", alias);
 
315
  squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this {
316
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
317
  return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(
318
+ "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
319
  }
320
 
321
+ squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
322
  const query = child.toQuery().clone();
323
  query.aggregateItems = [];
324
  query.aggregate("stddev_pop", "totalAmount", alias);
 
329
  sampleVarianceTotalAmountOfCustomerOrders(): this {
330
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
331
  return this.sampleVarianceTotalAmountOfCustomerOrdersAs(
332
+ "sampleVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
333
  }
334
 
335
+ sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
336
  const query = child.toQuery().clone();
337
  query.aggregateItems = [];
338
  query.aggregate("var_samp", "totalAmount", alias);
 
343
  samplePopulationVarianceTotalAmountOfCustomerOrders(): this {
344
  const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
345
  return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs(
346
+ "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query });
347
  }
348
 
349
+ samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this {
350
  const query = child.toQuery().clone();
351
  query.aggregateItems = [];
352
  query.aggregate("var_pop", "totalAmount", alias);
 
375
  return this;
376
  }
377
 
378
+ withIdIs(val: string): this {
379
  this.filters.push({ "id": { "$eq": val } });
380
  return this;
381
  }
382
 
383
+ withIdIsNot(val: string): this {
384
  this.filters.push({ "id": { "$ne": val } });
385
  return this;
386
  }
387
 
388
+ withIdIn(...vals: string[]): this {
389
  this.filters.push({ "id": { "$in": vals } });
390
  return this;
391
  }
392
 
393
+ withIdNotIn(...vals: string[]): this {
394
  this.filters.push({ "id": { "$notIn": vals } });
395
  return this;
396
  }
397
 
398
+ withIdGreaterThan(val: string): this {
399
  this.filters.push({ "id": { "$gt": val } });
400
  return this;
401
  }
402
 
403
+ withIdGreaterThanOrEqualTo(val: string): this {
404
  this.filters.push({ "id": { "$gte": val } });
405
  return this;
406
  }
407
 
408
+ withIdLessThan(val: string): this {
409
  this.filters.push({ "id": { "$lt": val } });
410
  return this;
411
  }
412
 
413
+ withIdLessThanOrEqualTo(val: string): this {
414
  this.filters.push({ "id": { "$lte": val } });
415
  return this;
416
  }
417
 
418
+ withIdBetween(lower: string, upper: string): this {
419
  this.filters.push({ "id": { "$between": [lower, upper] } });
420
  return this;
421
  }
 
440
  return this;
441
  }
442
 
443
+ withNameIsNot(val: string): this {
444
  this.filters.push({ "name": { "$ne": val } });
445
  return this;
446
  }
447
 
448
+ withNameIn(...vals: string[]): this {
449
  this.filters.push({ "name": { "$in": vals } });
450
  return this;
451
  }
452
 
453
+ withNameNotIn(...vals: string[]): this {
454
  this.filters.push({ "name": { "$notIn": vals } });
455
  return this;
456
  }
457
 
458
+ withNameGreaterThan(val: string): this {
459
  this.filters.push({ "name": { "$gt": val } });
460
  return this;
461
  }
462
 
463
+ withNameGreaterThanOrEqualTo(val: string): this {
464
  this.filters.push({ "name": { "$gte": val } });
465
  return this;
466
  }
467
 
468
+ withNameLessThan(val: string): this {
469
  this.filters.push({ "name": { "$lt": val } });
470
  return this;
471
  }
472
 
473
+ withNameLessThanOrEqualTo(val: string): this {
474
  this.filters.push({ "name": { "$lte": val } });
475
  return this;
476
  }
477
 
478
+ withNameBetween(lower: string, upper: string): this {
479
  this.filters.push({ "name": { "$between": [lower, upper] } });
480
  return this;
481
  }
 
529
  return this;
530
  }
531
 
532
+ withCodeIsNot(val: string): this {
533
  this.filters.push({ "code": { "$ne": val } });
534
  return this;
535
  }
536
 
537
+ withCodeIn(...vals: string[]): this {
538
  this.filters.push({ "code": { "$in": vals } });
539
  return this;
540
  }
541
 
542
+ withCodeNotIn(...vals: string[]): this {
543
  this.filters.push({ "code": { "$notIn": vals } });
544
  return this;
545
  }
546
 
547
+ withCodeGreaterThan(val: string): this {
548
  this.filters.push({ "code": { "$gt": val } });
549
  return this;
550
  }
551
 
552
+ withCodeGreaterThanOrEqualTo(val: string): this {
553
  this.filters.push({ "code": { "$gte": val } });
554
  return this;
555
  }
556
 
557
+ withCodeLessThan(val: string): this {
558
  this.filters.push({ "code": { "$lt": val } });
559
  return this;
560
  }
561
 
562
+ withCodeLessThanOrEqualTo(val: string): this {
563
  this.filters.push({ "code": { "$lte": val } });
564
  return this;
565
  }
566
 
567
+ withCodeBetween(lower: string, upper: string): this {
568
  this.filters.push({ "code": { "$between": [lower, upper] } });
569
  return this;
570
  }
 
618
  return this;
619
  }
620
 
621
+ withColorIsNot(val: string): this {
622
  this.filters.push({ "color": { "$ne": val } });
623
  return this;
624
  }
625
 
626
+ withColorIn(...vals: string[]): this {
627
  this.filters.push({ "color": { "$in": vals } });
628
  return this;
629
  }
630
 
631
+ withColorNotIn(...vals: string[]): this {
632
  this.filters.push({ "color": { "$notIn": vals } });
633
  return this;
634
  }
635
 
636
+ withColorGreaterThan(val: string): this {
637
  this.filters.push({ "color": { "$gt": val } });
638
  return this;
639
  }
640
 
641
+ withColorGreaterThanOrEqualTo(val: string): this {
642
  this.filters.push({ "color": { "$gte": val } });
643
  return this;
644
  }
645
 
646
+ withColorLessThan(val: string): this {
647
  this.filters.push({ "color": { "$lt": val } });
648
  return this;
649
  }
650
 
651
+ withColorLessThanOrEqualTo(val: string): this {
652
  this.filters.push({ "color": { "$lte": val } });
653
  return this;
654
  }
655
 
656
+ withColorBetween(lower: string, upper: string): this {
657
  this.filters.push({ "color": { "$between": [lower, upper] } });
658
  return this;
659
  }
 
697
  return this;
698
  }
699
 
700
+ withDisplayOrderIs(val: number): this {
701
  this.filters.push({ "displayOrder": { "$eq": val } });
702
  return this;
703
  }
704
 
705
+ withDisplayOrderIsNot(val: number): this {
706
  this.filters.push({ "displayOrder": { "$ne": val } });
707
  return this;
708
  }
709
 
710
+ withDisplayOrderIn(...vals: number[]): this {
711
  this.filters.push({ "displayOrder": { "$in": vals } });
712
  return this;
713
  }
714
 
715
+ withDisplayOrderNotIn(...vals: number[]): this {
716
  this.filters.push({ "displayOrder": { "$notIn": vals } });
717
  return this;
718
  }
719
 
720
+ withDisplayOrderGreaterThan(val: number): this {
721
  this.filters.push({ "displayOrder": { "$gt": val } });
722
  return this;
723
  }
724
 
725
+ withDisplayOrderGreaterThanOrEqualTo(val: number): this {
726
  this.filters.push({ "displayOrder": { "$gte": val } });
727
  return this;
728
  }
729
 
730
+ withDisplayOrderLessThan(val: number): this {
731
  this.filters.push({ "displayOrder": { "$lt": val } });
732
  return this;
733
  }
734
 
735
+ withDisplayOrderLessThanOrEqualTo(val: number): this {
736
  this.filters.push({ "displayOrder": { "$lte": val } });
737
  return this;
738
  }
739
 
740
+ withDisplayOrderBetween(lower: number, upper: number): this {
741
  this.filters.push({ "displayOrder": { "$between": [lower, upper] } });
742
  return this;
743
  }
 
752
  return this;
753
  }
754
 
755
+ withVersionIs(val: unknown): this {
756
  this.filters.push({ "version": { "$eq": val } });
757
  return this;
758
  }
759
 
760
+ withVersionIsNot(val: unknown): this {
761
  this.filters.push({ "version": { "$ne": val } });
762
  return this;
763
  }
764
 
765
+ withVersionIn(...vals: unknown[]): this {
766
  this.filters.push({ "version": { "$in": vals } });
767
  return this;
768
  }
769
 
770
+ withVersionNotIn(...vals: unknown[]): this {
771
  this.filters.push({ "version": { "$notIn": vals } });
772
  return this;
773
  }
774
 
775
+ withVersionGreaterThan(val: unknown): this {
776
  this.filters.push({ "version": { "$gt": val } });
777
  return this;
778
  }
779
 
780
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
781
  this.filters.push({ "version": { "$gte": val } });
782
  return this;
783
  }
784
 
785
+ withVersionLessThan(val: unknown): this {
786
  this.filters.push({ "version": { "$lt": val } });
787
  return this;
788
  }
789
 
790
+ withVersionLessThanOrEqualTo(val: unknown): this {
791
  this.filters.push({ "version": { "$lte": val } });
792
  return this;
793
  }
794
 
795
+ withVersionBetween(lower: unknown, upper: unknown): this {
796
  this.filters.push({ "version": { "$between": [lower, upper] } });
797
  return this;
798
  }
 
955
  }
956
 
957
  groupByPlatformAs(retName: string): this {
958
+ this.query.groupBy("platform", retName);
959
  return this;
960
  }
961
  groupById(): this {
 
964
  }
965
 
966
  groupByIdAs(retName: string): this {
967
+ this.query.groupBy("id", retName);
968
  return this;
969
  }
970
  groupByName(): this {
 
973
  }
974
 
975
  groupByNameAs(retName: string): this {
976
+ this.query.groupBy("name", retName);
977
  return this;
978
  }
979
  groupByCode(): this {
 
982
  }
983
 
984
  groupByCodeAs(retName: string): this {
985
+ this.query.groupBy("code", retName);
986
  return this;
987
  }
988
  groupByColor(): this {
 
991
  }
992
 
993
  groupByColorAs(retName: string): this {
994
+ this.query.groupBy("color", retName);
995
  return this;
996
  }
997
  groupByDisplayOrder(): this {
 
1000
  }
1001
 
1002
  groupByDisplayOrderAs(retName: string): this {
1003
+ this.query.groupBy("displayOrder", retName);
1004
  return this;
1005
  }
1006
  groupByVersion(): this {
 
1009
  }
1010
 
1011
  groupByVersionAs(retName: string): this {
1012
+ this.query.groupBy("version", retName);
1013
  return this;
1014
  }
1015
 
1016
  // --- Facets ---
1017
  facetByPlatformAs(
1018
  facetName: string,
1019
+ request: { readonly entityName: "Platform"; toQuery(): SelectQuery },
1020
  includeAllFacets = true,
1021
  ): this {
1022
  this.query.facetBy(facetName, "platform", request, includeAllFacets,
 
1132
  return this;
1133
  }
1134
 
1135
+ async newEntity(context: UserContext): Promise<OrderStatus> {
1136
  this.ensureIntent();
1137
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
1138
+ return OrderStatus.teaqlCreate(context);
1139
  }
1140
 
1141
  executeForList(context: UserContext): Promise<SmartList<OrderStatus>> {
source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { Platform } from '../models/Platform';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
 
4
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
 
6
 
@@ -24,6 +25,10 @@ export class PlatformRequest {
24
  else this.selectSelfFields();
25
  }
26
 
 
 
 
 
27
  comment(c: string): this {
28
  this.query.comment(c);
29
  this._comment = c;
@@ -99,12 +104,14 @@ export class PlatformRequest {
99
  }
100
 
101
  withDeletedRows(): this {
 
102
  this.filters = this.filters.filter(filter => !("version" in filter));
103
  return this;
104
  }
105
 
106
  deletedRowsOnly(): this {
107
  this.withDeletedRows();
 
108
  this.filters.push({ version: { "$lte": -1 } });
109
  return this;
110
  }
@@ -132,13 +139,13 @@ export class PlatformRequest {
132
 
133
 
134
 
135
- selectOrderStatusListWith(request: { toQuery(): SelectQuery }): this {
136
  this.query.relationQuery(
137
  "orderStatusList", request.toQuery(), "id", "platform", true,
138
  { kind: "relation-select", method: "selectOrderStatusListWith", relation: "orderStatusList" });
139
  return this;
140
  }
141
- selectCustomerListWith(request: { toQuery(): SelectQuery }): this {
142
  this.query.relationQuery(
143
  "customerList", request.toQuery(), "id", "platform", true,
144
  { kind: "relation-select", method: "selectCustomerListWith", relation: "customerList" });
@@ -147,17 +154,19 @@ export class PlatformRequest {
147
 
148
  haveOrderStatuses(): this {
149
  return this.withOrderStatusListMatching({
 
150
  toQuery: () => new SelectQuery("OrderStatus"),
151
  });
152
  }
153
 
154
  haveNoOrderStatuses(): this {
155
  return this.withoutOrderStatusListMatching({
 
156
  toQuery: () => new SelectQuery("OrderStatus"),
157
  });
158
  }
159
 
160
- withOrderStatusListMatching(request: { toQuery(): SelectQuery }): this {
161
  this.filters.push({
162
  "id": {
163
  "$inSubquery": {
@@ -168,7 +177,7 @@ export class PlatformRequest {
168
  return this;
169
  }
170
 
171
- withoutOrderStatusListMatching(request: { toQuery(): SelectQuery }): this {
172
  this.filters.push({
173
  "id": {
174
  "$notInSubquery": {
@@ -180,17 +189,19 @@ export class PlatformRequest {
180
  }
181
  haveCustomers(): this {
182
  return this.withCustomerListMatching({
 
183
  toQuery: () => new SelectQuery("Customer"),
184
  });
185
  }
186
 
187
  haveNoCustomers(): this {
188
  return this.withoutCustomerListMatching({
 
189
  toQuery: () => new SelectQuery("Customer"),
190
  });
191
  }
192
 
193
- withCustomerListMatching(request: { toQuery(): SelectQuery }): this {
194
  this.filters.push({
195
  "id": {
196
  "$inSubquery": {
@@ -201,7 +212,7 @@ export class PlatformRequest {
201
  return this;
202
  }
203
 
204
- withoutCustomerListMatching(request: { toQuery(): SelectQuery }): this {
205
  this.filters.push({
206
  "id": {
207
  "$notInSubquery": {
@@ -218,13 +229,13 @@ export class PlatformRequest {
218
 
219
  countOrderStatusesAs(alias: string): this {
220
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
221
- this.countOrderStatusesWith(alias, { toQuery: () => query });
222
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
223
  kind: "relation-count", method: "countOrderStatusesAs", relation: "orderStatusList", alias };
224
  return this;
225
  }
226
 
227
- countOrderStatusesWith(alias: string, child: { toQuery(): SelectQuery }): this {
228
  const query = child.toQuery().clone();
229
  query.aggregateItems = [];
230
  query.aggregate("Count", "id", alias);
@@ -236,10 +247,10 @@ export class PlatformRequest {
236
  minDisplayOrderOfOrderStatuses(): this {
237
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
238
  return this.minDisplayOrderOfOrderStatusesAs(
239
- "minOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
240
  }
241
 
242
- minDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
243
  const query = child.toQuery().clone();
244
  query.aggregateItems = [];
245
  query.aggregate("min", "displayOrder", alias);
@@ -250,10 +261,10 @@ export class PlatformRequest {
250
  maxDisplayOrderOfOrderStatuses(): this {
251
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
252
  return this.maxDisplayOrderOfOrderStatusesAs(
253
- "maxOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
254
  }
255
 
256
- maxDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
257
  const query = child.toQuery().clone();
258
  query.aggregateItems = [];
259
  query.aggregate("max", "displayOrder", alias);
@@ -264,10 +275,10 @@ export class PlatformRequest {
264
  sumDisplayOrderOfOrderStatuses(): this {
265
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
266
  return this.sumDisplayOrderOfOrderStatusesAs(
267
- "sumOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
268
  }
269
 
270
- sumDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
271
  const query = child.toQuery().clone();
272
  query.aggregateItems = [];
273
  query.aggregate("sum", "displayOrder", alias);
@@ -278,10 +289,10 @@ export class PlatformRequest {
278
  avgDisplayOrderOfOrderStatuses(): this {
279
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
280
  return this.avgDisplayOrderOfOrderStatusesAs(
281
- "avgOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
282
  }
283
 
284
- avgDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
285
  const query = child.toQuery().clone();
286
  query.aggregateItems = [];
287
  query.aggregate("avg", "displayOrder", alias);
@@ -292,10 +303,10 @@ export class PlatformRequest {
292
  standardDeviationDisplayOrderOfOrderStatuses(): this {
293
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
294
  return this.standardDeviationDisplayOrderOfOrderStatusesAs(
295
- "standardDeviationOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
296
  }
297
 
298
- standardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
299
  const query = child.toQuery().clone();
300
  query.aggregateItems = [];
301
  query.aggregate("stddev", "displayOrder", alias);
@@ -306,10 +317,10 @@ export class PlatformRequest {
306
  squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(): this {
307
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
308
  return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(
309
- "squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
310
  }
311
 
312
- squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
313
  const query = child.toQuery().clone();
314
  query.aggregateItems = [];
315
  query.aggregate("stddev_pop", "displayOrder", alias);
@@ -320,10 +331,10 @@ export class PlatformRequest {
320
  sampleVarianceDisplayOrderOfOrderStatuses(): this {
321
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
322
  return this.sampleVarianceDisplayOrderOfOrderStatusesAs(
323
- "sampleVarianceOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
324
  }
325
 
326
- sampleVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
327
  const query = child.toQuery().clone();
328
  query.aggregateItems = [];
329
  query.aggregate("var_samp", "displayOrder", alias);
@@ -334,10 +345,10 @@ export class PlatformRequest {
334
  samplePopulationVarianceDisplayOrderOfOrderStatuses(): this {
335
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
336
  return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs(
337
- "samplePopulationVarianceOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
338
  }
339
 
340
- samplePopulationVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
341
  const query = child.toQuery().clone();
342
  query.aggregateItems = [];
343
  query.aggregate("var_pop", "displayOrder", alias);
@@ -351,13 +362,13 @@ export class PlatformRequest {
351
 
352
  countCustomersAs(alias: string): this {
353
  const query = new SelectQuery("Customer").filter({ version: { "$gte": 1 } });
354
- this.countCustomersWith(alias, { toQuery: () => query });
355
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
356
  kind: "relation-count", method: "countCustomersAs", relation: "customerList", alias };
357
  return this;
358
  }
359
 
360
- countCustomersWith(alias: string, child: { toQuery(): SelectQuery }): this {
361
  const query = child.toQuery().clone();
362
  query.aggregateItems = [];
363
  query.aggregate("Count", "id", alias);
@@ -368,47 +379,47 @@ export class PlatformRequest {
368
 
369
 
370
 
371
- withIdIs(val: any): this {
372
  this.filters.push({ "id": { "$eq": val } });
373
  return this;
374
  }
375
 
376
- withIdIsNot(val: any): this {
377
  this.filters.push({ "id": { "$ne": val } });
378
  return this;
379
  }
380
 
381
- withIdIn(...vals: any[]): this {
382
  this.filters.push({ "id": { "$in": vals } });
383
  return this;
384
  }
385
 
386
- withIdNotIn(...vals: any[]): this {
387
  this.filters.push({ "id": { "$notIn": vals } });
388
  return this;
389
  }
390
 
391
- withIdGreaterThan(val: any): this {
392
  this.filters.push({ "id": { "$gt": val } });
393
  return this;
394
  }
395
 
396
- withIdGreaterThanOrEqualTo(val: any): this {
397
  this.filters.push({ "id": { "$gte": val } });
398
  return this;
399
  }
400
 
401
- withIdLessThan(val: any): this {
402
  this.filters.push({ "id": { "$lt": val } });
403
  return this;
404
  }
405
 
406
- withIdLessThanOrEqualTo(val: any): this {
407
  this.filters.push({ "id": { "$lte": val } });
408
  return this;
409
  }
410
 
411
- withIdBetween(lower: any, upper: any): this {
412
  this.filters.push({ "id": { "$between": [lower, upper] } });
413
  return this;
414
  }
@@ -433,42 +444,42 @@ export class PlatformRequest {
433
  return this;
434
  }
435
 
436
- withNameIsNot(val: any): this {
437
  this.filters.push({ "name": { "$ne": val } });
438
  return this;
439
  }
440
 
441
- withNameIn(...vals: any[]): this {
442
  this.filters.push({ "name": { "$in": vals } });
443
  return this;
444
  }
445
 
446
- withNameNotIn(...vals: any[]): this {
447
  this.filters.push({ "name": { "$notIn": vals } });
448
  return this;
449
  }
450
 
451
- withNameGreaterThan(val: any): this {
452
  this.filters.push({ "name": { "$gt": val } });
453
  return this;
454
  }
455
 
456
- withNameGreaterThanOrEqualTo(val: any): this {
457
  this.filters.push({ "name": { "$gte": val } });
458
  return this;
459
  }
460
 
461
- withNameLessThan(val: any): this {
462
  this.filters.push({ "name": { "$lt": val } });
463
  return this;
464
  }
465
 
466
- withNameLessThanOrEqualTo(val: any): this {
467
  this.filters.push({ "name": { "$lte": val } });
468
  return this;
469
  }
470
 
471
- withNameBetween(lower: any, upper: any): this {
472
  this.filters.push({ "name": { "$between": [lower, upper] } });
473
  return this;
474
  }
@@ -512,47 +523,47 @@ export class PlatformRequest {
512
  return this;
513
  }
514
 
515
- withVersionIs(val: any): this {
516
  this.filters.push({ "version": { "$eq": val } });
517
  return this;
518
  }
519
 
520
- withVersionIsNot(val: any): this {
521
  this.filters.push({ "version": { "$ne": val } });
522
  return this;
523
  }
524
 
525
- withVersionIn(...vals: any[]): this {
526
  this.filters.push({ "version": { "$in": vals } });
527
  return this;
528
  }
529
 
530
- withVersionNotIn(...vals: any[]): this {
531
  this.filters.push({ "version": { "$notIn": vals } });
532
  return this;
533
  }
534
 
535
- withVersionGreaterThan(val: any): this {
536
  this.filters.push({ "version": { "$gt": val } });
537
  return this;
538
  }
539
 
540
- withVersionGreaterThanOrEqualTo(val: any): this {
541
  this.filters.push({ "version": { "$gte": val } });
542
  return this;
543
  }
544
 
545
- withVersionLessThan(val: any): this {
546
  this.filters.push({ "version": { "$lt": val } });
547
  return this;
548
  }
549
 
550
- withVersionLessThanOrEqualTo(val: any): this {
551
  this.filters.push({ "version": { "$lte": val } });
552
  return this;
553
  }
554
 
555
- withVersionBetween(lower: any, upper: any): this {
556
  this.filters.push({ "version": { "$between": [lower, upper] } });
557
  return this;
558
  }
@@ -621,7 +632,7 @@ export class PlatformRequest {
621
  }
622
 
623
  groupByIdAs(retName: string): this {
624
- this.query.groupBy("id"); // In TS we don't alias group by yet natively
625
  return this;
626
  }
627
  groupByName(): this {
@@ -630,7 +641,7 @@ export class PlatformRequest {
630
  }
631
 
632
  groupByNameAs(retName: string): this {
633
- this.query.groupBy("name"); // In TS we don't alias group by yet natively
634
  return this;
635
  }
636
  groupByVersion(): this {
@@ -639,7 +650,7 @@ export class PlatformRequest {
639
  }
640
 
641
  groupByVersionAs(retName: string): this {
642
- this.query.groupBy("version"); // In TS we don't alias group by yet natively
643
  return this;
644
  }
645
 
@@ -752,9 +763,10 @@ export class ExecutablePlatformRequest {
752
  return this;
753
  }
754
 
755
- newEntity(context: UserContext): Platform {
756
  this.ensureIntent();
757
- return new Platform();
 
758
  }
759
 
760
  executeForList(context: UserContext): Promise<SmartList<Platform>> {
 
1
  import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
  import { Platform } from '../models/Platform';
3
  import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
  import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
 
7
 
 
25
  else this.selectSelfFields();
26
  }
27
 
28
+ get entityName(): "Platform" {
29
+ return "Platform";
30
+ }
31
+
32
  comment(c: string): this {
33
  this.query.comment(c);
34
  this._comment = c;
 
104
  }
105
 
106
  withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
  this.filters = this.filters.filter(filter => !("version" in filter));
109
  return this;
110
  }
111
 
112
  deletedRowsOnly(): this {
113
  this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
  this.filters.push({ version: { "$lte": -1 } });
116
  return this;
117
  }
 
139
 
140
 
141
 
142
+ selectOrderStatusListWith(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
143
  this.query.relationQuery(
144
  "orderStatusList", request.toQuery(), "id", "platform", true,
145
  { kind: "relation-select", method: "selectOrderStatusListWith", relation: "orderStatusList" });
146
  return this;
147
  }
148
+ selectCustomerListWith(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this {
149
  this.query.relationQuery(
150
  "customerList", request.toQuery(), "id", "platform", true,
151
  { kind: "relation-select", method: "selectCustomerListWith", relation: "customerList" });
 
154
 
155
  haveOrderStatuses(): this {
156
  return this.withOrderStatusListMatching({
157
+ entityName: "OrderStatus",
158
  toQuery: () => new SelectQuery("OrderStatus"),
159
  });
160
  }
161
 
162
  haveNoOrderStatuses(): this {
163
  return this.withoutOrderStatusListMatching({
164
+ entityName: "OrderStatus",
165
  toQuery: () => new SelectQuery("OrderStatus"),
166
  });
167
  }
168
 
169
+ withOrderStatusListMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
170
  this.filters.push({
171
  "id": {
172
  "$inSubquery": {
 
177
  return this;
178
  }
179
 
180
+ withoutOrderStatusListMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
181
  this.filters.push({
182
  "id": {
183
  "$notInSubquery": {
 
189
  }
190
  haveCustomers(): this {
191
  return this.withCustomerListMatching({
192
+ entityName: "Customer",
193
  toQuery: () => new SelectQuery("Customer"),
194
  });
195
  }
196
 
197
  haveNoCustomers(): this {
198
  return this.withoutCustomerListMatching({
199
+ entityName: "Customer",
200
  toQuery: () => new SelectQuery("Customer"),
201
  });
202
  }
203
 
204
+ withCustomerListMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this {
205
  this.filters.push({
206
  "id": {
207
  "$inSubquery": {
 
212
  return this;
213
  }
214
 
215
+ withoutCustomerListMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this {
216
  this.filters.push({
217
  "id": {
218
  "$notInSubquery": {
 
229
 
230
  countOrderStatusesAs(alias: string): this {
231
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
232
+ this.countOrderStatusesWith(alias, { entityName: "OrderStatus", toQuery: () => query });
233
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
234
  kind: "relation-count", method: "countOrderStatusesAs", relation: "orderStatusList", alias };
235
  return this;
236
  }
237
 
238
+ countOrderStatusesWith(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
239
  const query = child.toQuery().clone();
240
  query.aggregateItems = [];
241
  query.aggregate("Count", "id", alias);
 
247
  minDisplayOrderOfOrderStatuses(): this {
248
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
249
  return this.minDisplayOrderOfOrderStatusesAs(
250
+ "minOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
251
  }
252
 
253
+ minDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
254
  const query = child.toQuery().clone();
255
  query.aggregateItems = [];
256
  query.aggregate("min", "displayOrder", alias);
 
261
  maxDisplayOrderOfOrderStatuses(): this {
262
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
263
  return this.maxDisplayOrderOfOrderStatusesAs(
264
+ "maxOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
265
  }
266
 
267
+ maxDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
268
  const query = child.toQuery().clone();
269
  query.aggregateItems = [];
270
  query.aggregate("max", "displayOrder", alias);
 
275
  sumDisplayOrderOfOrderStatuses(): this {
276
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
277
  return this.sumDisplayOrderOfOrderStatusesAs(
278
+ "sumOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
279
  }
280
 
281
+ sumDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
282
  const query = child.toQuery().clone();
283
  query.aggregateItems = [];
284
  query.aggregate("sum", "displayOrder", alias);
 
289
  avgDisplayOrderOfOrderStatuses(): this {
290
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
291
  return this.avgDisplayOrderOfOrderStatusesAs(
292
+ "avgOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
293
  }
294
 
295
+ avgDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
296
  const query = child.toQuery().clone();
297
  query.aggregateItems = [];
298
  query.aggregate("avg", "displayOrder", alias);
 
303
  standardDeviationDisplayOrderOfOrderStatuses(): this {
304
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
305
  return this.standardDeviationDisplayOrderOfOrderStatusesAs(
306
+ "standardDeviationOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
307
  }
308
 
309
+ standardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
310
  const query = child.toQuery().clone();
311
  query.aggregateItems = [];
312
  query.aggregate("stddev", "displayOrder", alias);
 
317
  squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(): this {
318
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
319
  return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(
320
+ "squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
321
  }
322
 
323
+ squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
324
  const query = child.toQuery().clone();
325
  query.aggregateItems = [];
326
  query.aggregate("stddev_pop", "displayOrder", alias);
 
331
  sampleVarianceDisplayOrderOfOrderStatuses(): this {
332
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
333
  return this.sampleVarianceDisplayOrderOfOrderStatusesAs(
334
+ "sampleVarianceOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
335
  }
336
 
337
+ sampleVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
338
  const query = child.toQuery().clone();
339
  query.aggregateItems = [];
340
  query.aggregate("var_samp", "displayOrder", alias);
 
345
  samplePopulationVarianceDisplayOrderOfOrderStatuses(): this {
346
  const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
347
  return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs(
348
+ "samplePopulationVarianceOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query });
349
  }
350
 
351
+ samplePopulationVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this {
352
  const query = child.toQuery().clone();
353
  query.aggregateItems = [];
354
  query.aggregate("var_pop", "displayOrder", alias);
 
362
 
363
  countCustomersAs(alias: string): this {
364
  const query = new SelectQuery("Customer").filter({ version: { "$gte": 1 } });
365
+ this.countCustomersWith(alias, { entityName: "Customer", toQuery: () => query });
366
  this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
367
  kind: "relation-count", method: "countCustomersAs", relation: "customerList", alias };
368
  return this;
369
  }
370
 
371
+ countCustomersWith(alias: string, child: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this {
372
  const query = child.toQuery().clone();
373
  query.aggregateItems = [];
374
  query.aggregate("Count", "id", alias);
 
379
 
380
 
381
 
382
+ withIdIs(val: string): this {
383
  this.filters.push({ "id": { "$eq": val } });
384
  return this;
385
  }
386
 
387
+ withIdIsNot(val: string): this {
388
  this.filters.push({ "id": { "$ne": val } });
389
  return this;
390
  }
391
 
392
+ withIdIn(...vals: string[]): this {
393
  this.filters.push({ "id": { "$in": vals } });
394
  return this;
395
  }
396
 
397
+ withIdNotIn(...vals: string[]): this {
398
  this.filters.push({ "id": { "$notIn": vals } });
399
  return this;
400
  }
401
 
402
+ withIdGreaterThan(val: string): this {
403
  this.filters.push({ "id": { "$gt": val } });
404
  return this;
405
  }
406
 
407
+ withIdGreaterThanOrEqualTo(val: string): this {
408
  this.filters.push({ "id": { "$gte": val } });
409
  return this;
410
  }
411
 
412
+ withIdLessThan(val: string): this {
413
  this.filters.push({ "id": { "$lt": val } });
414
  return this;
415
  }
416
 
417
+ withIdLessThanOrEqualTo(val: string): this {
418
  this.filters.push({ "id": { "$lte": val } });
419
  return this;
420
  }
421
 
422
+ withIdBetween(lower: string, upper: string): this {
423
  this.filters.push({ "id": { "$between": [lower, upper] } });
424
  return this;
425
  }
 
444
  return this;
445
  }
446
 
447
+ withNameIsNot(val: string): this {
448
  this.filters.push({ "name": { "$ne": val } });
449
  return this;
450
  }
451
 
452
+ withNameIn(...vals: string[]): this {
453
  this.filters.push({ "name": { "$in": vals } });
454
  return this;
455
  }
456
 
457
+ withNameNotIn(...vals: string[]): this {
458
  this.filters.push({ "name": { "$notIn": vals } });
459
  return this;
460
  }
461
 
462
+ withNameGreaterThan(val: string): this {
463
  this.filters.push({ "name": { "$gt": val } });
464
  return this;
465
  }
466
 
467
+ withNameGreaterThanOrEqualTo(val: string): this {
468
  this.filters.push({ "name": { "$gte": val } });
469
  return this;
470
  }
471
 
472
+ withNameLessThan(val: string): this {
473
  this.filters.push({ "name": { "$lt": val } });
474
  return this;
475
  }
476
 
477
+ withNameLessThanOrEqualTo(val: string): this {
478
  this.filters.push({ "name": { "$lte": val } });
479
  return this;
480
  }
481
 
482
+ withNameBetween(lower: string, upper: string): this {
483
  this.filters.push({ "name": { "$between": [lower, upper] } });
484
  return this;
485
  }
 
523
  return this;
524
  }
525
 
526
+ withVersionIs(val: unknown): this {
527
  this.filters.push({ "version": { "$eq": val } });
528
  return this;
529
  }
530
 
531
+ withVersionIsNot(val: unknown): this {
532
  this.filters.push({ "version": { "$ne": val } });
533
  return this;
534
  }
535
 
536
+ withVersionIn(...vals: unknown[]): this {
537
  this.filters.push({ "version": { "$in": vals } });
538
  return this;
539
  }
540
 
541
+ withVersionNotIn(...vals: unknown[]): this {
542
  this.filters.push({ "version": { "$notIn": vals } });
543
  return this;
544
  }
545
 
546
+ withVersionGreaterThan(val: unknown): this {
547
  this.filters.push({ "version": { "$gt": val } });
548
  return this;
549
  }
550
 
551
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
552
  this.filters.push({ "version": { "$gte": val } });
553
  return this;
554
  }
555
 
556
+ withVersionLessThan(val: unknown): this {
557
  this.filters.push({ "version": { "$lt": val } });
558
  return this;
559
  }
560
 
561
+ withVersionLessThanOrEqualTo(val: unknown): this {
562
  this.filters.push({ "version": { "$lte": val } });
563
  return this;
564
  }
565
 
566
+ withVersionBetween(lower: unknown, upper: unknown): this {
567
  this.filters.push({ "version": { "$between": [lower, upper] } });
568
  return this;
569
  }
 
632
  }
633
 
634
  groupByIdAs(retName: string): this {
635
+ this.query.groupBy("id", retName);
636
  return this;
637
  }
638
  groupByName(): this {
 
641
  }
642
 
643
  groupByNameAs(retName: string): this {
644
+ this.query.groupBy("name", retName);
645
  return this;
646
  }
647
  groupByVersion(): this {
 
650
  }
651
 
652
  groupByVersionAs(retName: string): this {
653
+ this.query.groupBy("version", retName);
654
  return this;
655
  }
656
 
 
763
  return this;
764
  }
765
 
766
+ async newEntity(context: UserContext): Promise<Platform> {
767
  this.ensureIntent();
768
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
769
+ return Platform.teaqlCreate(context);
770
  }
771
 
772
  executeForList(context: UserContext): Promise<SmartList<Platform>> {
source/teaql-ts/examples/browser-sqlite/orders-lib/src/runtime-module.ts CHANGED
@@ -1,3 +1,4 @@
 
1
  import { ObjectLocation, RuntimeModule } from "teaql-ts";
2
  import { ENTITY_SCHEMAS } from "./teaql-schemas";
3
  import { ensureGeneratedBootstrap } from "./generated-bootstrap";
 
1
+ import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts';
2
  import { ObjectLocation, RuntimeModule } from "teaql-ts";
3
  import { ENTITY_SCHEMAS } from "./teaql-schemas";
4
  import { ensureGeneratedBootstrap } from "./generated-bootstrap";
source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-schemas.ts CHANGED
@@ -10,7 +10,7 @@ export const ENTITY_SCHEMAS: Record<string, EntitySchema> = {
10
  "OrderStatus": {
11
  table: "order_status_data",
12
  auditMaskFields: [],
13
- 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 }, "color": { columnName: "color", modelName: "color", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
14
  relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "status", many: true }}
15
  },
16
  "Customer": {
@@ -22,13 +22,13 @@ export const ENTITY_SCHEMAS: Record<string, EntitySchema> = {
22
  "CustomerOrder": {
23
  table: "customer_order_data",
24
  auditMaskFields: [],
25
- columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customer": { columnName: "customer", modelName: "customer", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "status": { columnName: "status", modelName: "status", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "orderNumber": { columnName: "order_number", modelName: "order_number", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "orderDate": { columnName: "order_date", modelName: "order_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "totalAmount": { columnName: "total_amount", modelName: "total_amount", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
26
  relations: {"customer": { targetEntity: "Customer", localKey: "customer", foreignKey: "id", many: false }, "status": { targetEntity: "OrderStatus", localKey: "status", foreignKey: "id", many: false }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "customerOrder", many: true }}
27
  },
28
  "OrderItem": {
29
  table: "order_item_data",
30
  auditMaskFields: [],
31
- columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customerOrder": { columnName: "customer_order", modelName: "customer_order", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "productName": { columnName: "product_name", modelName: "product_name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "quantity": { columnName: "quantity", modelName: "quantity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "unitPrice": { columnName: "unit_price", modelName: "unit_price", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
32
  relations: {"customerOrder": { targetEntity: "CustomerOrder", localKey: "customerOrder", foreignKey: "id", many: false }}
33
  }
34
  };
 
10
  "OrderStatus": {
11
  table: "order_status_data",
12
  auditMaskFields: [],
13
+ 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 }, "color": { columnName: "color", modelName: "color", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
14
  relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "status", many: true }}
15
  },
16
  "Customer": {
 
22
  "CustomerOrder": {
23
  table: "customer_order_data",
24
  auditMaskFields: [],
25
+ columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customer": { columnName: "customer", modelName: "customer", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "status": { columnName: "status", modelName: "status", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "orderNumber": { columnName: "order_number", modelName: "order_number", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "orderDate": { columnName: "order_date", modelName: "order_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "totalAmount": { columnName: "total_amount", modelName: "total_amount", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
26
  relations: {"customer": { targetEntity: "Customer", localKey: "customer", foreignKey: "id", many: false }, "status": { targetEntity: "OrderStatus", localKey: "status", foreignKey: "id", many: false }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "customerOrder", many: true }}
27
  },
28
  "OrderItem": {
29
  table: "order_item_data",
30
  auditMaskFields: [],
31
+ columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customerOrder": { columnName: "customer_order", modelName: "customer_order", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "productName": { columnName: "product_name", modelName: "product_name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "quantity": { columnName: "quantity", modelName: "quantity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "unitPrice": { columnName: "unit_price", modelName: "unit_price", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
32
  relations: {"customerOrder": { targetEntity: "CustomerOrder", localKey: "customerOrder", foreignKey: "id", many: false }}
33
  }
34
  };
source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-ts.ts CHANGED
@@ -1,14 +1,26 @@
1
  import {
2
- CheckException, EntityChecker, RuntimeModule,
3
  SelectQuery as RuntimeSelectQuery, UserContext,
4
- executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession,
 
5
  } from "teaql-ts";
6
 
7
  export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts";
8
- export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts";
 
 
 
 
 
 
 
 
 
 
9
  export type { EntityKey } from "teaql-ts";
10
  export type { TeaQLPage } from "teaql-ts";
11
  import type { QueryOperation } from "teaql-ts";
 
12
 
13
  function soundex(input: unknown): string {
14
  const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, "");
@@ -41,7 +53,8 @@ export class SelectQuery extends RuntimeSelectQuery {
41
  }
42
 
43
  export interface TeaQLDataService {
44
- executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>): Promise<T>;
 
45
  preflightMutation(mutation: any): any;
46
  afterGraphCommit(work: () => void): void;
47
  afterGraphRollback(work: () => void): void;
@@ -52,18 +65,24 @@ export interface TeaQLDataService {
52
  close?(): Promise<void>;
53
  }
54
 
55
- export class TeaQLClient implements TeaQLDataService {
56
  private data: Record<string, Record<string, any>> = {};
57
  private nextIds: Record<string, number> = {};
58
  private readonly checkers: Record<string, EntityChecker> = {};
 
59
  private userContext = new UserContext();
60
  private graphSaveActive = false;
 
61
  private graphCommitActions: Array<() => void> = [];
62
  private graphRollbackActions: Array<() => void> = [];
 
63
  private graphSaveTail: Promise<void> = Promise.resolve();
64
  private readonly mutationGovernanceEvents: any[] = [];
 
 
65
 
66
  constructor(private storagePath?: string) {
 
67
  if (storagePath) {
68
  const fs = require("fs");
69
  if (fs.existsSync(storagePath)) {
@@ -76,10 +95,74 @@ export class TeaQLClient implements TeaQLDataService {
76
 
77
  /** Installs passive generated metadata. It never mutates storage. */
78
  install(module: RuntimeModule): this {
 
79
  Object.assign(this.checkers, module.checkers);
 
80
  return this;
81
  }
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  setUserContext(context: UserContext): this {
84
  this.userContext = context;
85
  return this;
@@ -89,6 +172,33 @@ export class TeaQLClient implements TeaQLDataService {
89
  return [...this.mutationGovernanceEvents];
90
  }
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  private persist() {
93
  if (!this.storagePath) return;
94
  const fs = require("fs");
@@ -99,8 +209,15 @@ export class TeaQLClient implements TeaQLDataService {
99
  fs.renameSync(temporaryPath, this.storagePath);
100
  }
101
 
102
- async executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>): Promise<T> {
103
  const graph = new GraphMutationSession(intent);
 
 
 
 
 
 
 
104
  const predecessor = this.graphSaveTail;
105
  let release!: () => void;
106
  this.graphSaveTail = new Promise<void>(resolve => { release = resolve; });
@@ -109,32 +226,57 @@ export class TeaQLClient implements TeaQLDataService {
109
  const nextIdsSnapshot = { ...this.nextIds };
110
  let fixEvidenceStarted = false;
111
  let mutationPolicyGraphStarted = false;
 
112
  try {
 
113
  this.graphSaveActive = true;
 
114
  this.graphCommitActions = [];
115
  this.graphRollbackActions = [];
116
- this.userContext.insertResource("fixTime", new Date());
117
- this.userContext.beginFixEvidence();
118
- fixEvidenceStarted = true;
119
- this.userContext.beginMutationPolicyGraph();
 
 
 
120
  mutationPolicyGraphStarted = true;
 
 
 
 
 
 
 
121
  const result = await work(graph);
122
- this.userContext.ensureMutationPolicyGraphComplete();
123
- this.persist();
124
- for (const action of this.graphCommitActions) action();
 
 
 
 
 
 
 
125
  return result;
126
  } catch (error) {
127
- this.data = dataSnapshot;
128
- this.nextIds = nextIdsSnapshot;
129
- for (const action of [...this.graphRollbackActions].reverse()) action();
 
 
 
 
130
  throw error;
131
  } finally {
132
  this.graphSaveActive = false;
 
133
  this.graphCommitActions = [];
134
  this.graphRollbackActions = [];
135
- if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph();
136
- this.userContext.removeResource("fixTime");
137
- if (fixEvidenceStarted) this.userContext.finishFixEvidence();
138
  release();
139
  }
140
  }
@@ -150,84 +292,145 @@ export class TeaQLClient implements TeaQLDataService {
150
  }
151
 
152
  preflightMutation(mutation: any): any {
153
- mutation = this.checkAndFixMutation(mutation);
154
- this.userContext.recordMutationPolicyPreflight(mutation);
 
 
 
 
 
 
 
 
 
 
 
155
  return mutation;
156
  }
157
 
158
  private checkAndFixMutation(mutation: any): any {
159
- if (mutation instanceof MutationRequest) mutation = mutation.mutation;
160
- if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } };
162
- const checker = this.checkers[String(mutation.entity)];
163
- if (!checker) return mutation;
 
 
 
 
 
 
 
 
164
  const results: any[] = [];
165
  const ownsFixTime = this.userContext.getResource("fixTime") === undefined;
166
- if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence();
167
  try {
168
  checker.checkAndFix(this.userContext, mutation, results);
169
- if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value);
170
- this.userContext.translateCheckResults(results);
 
 
171
  if (results.length) throw new CheckException(results);
172
- return mutation;
 
 
173
  } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); }
174
  }
175
 
176
  async executeMutation(mutation: any): Promise<any> {
177
- mutation = this.checkAndFixMutation(mutation);
 
 
 
178
  const mutationGovernance = this.userContext.enterMutationPolicy(mutation);
179
- this.mutationGovernanceEvents.push(mutationGovernance);
180
  const table = this.data[mutation.entity] ||= {};
 
181
  if (mutation.action === "Create") {
182
  const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1);
183
- this.nextIds[mutation.entity] = Number(id) + 1;
184
- const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 };
 
185
  table[String(id)] = record;
186
  if (!this.graphSaveActive) this.persist();
187
- return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } };
188
- }
189
- if (mutation.action === "Update") {
190
- const id = String(mutation.id);
191
- if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`);
192
- const expectedVersion = Number(mutation.version);
193
- const currentVersion = Number(table[id].version || 0);
194
- if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) {
195
- throw new Error(
196
- `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`);
197
- }
198
- table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 };
199
- if (!this.graphSaveActive) this.persist();
200
- return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } };
201
  }
202
- if (mutation.action === "Delete") {
203
  const id = String(mutation.id);
204
  if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`);
205
- const expectedVersion = Number(mutation.version);
206
- const currentVersion = Number(table[id].version || 0);
207
- if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) {
208
  throw new Error(
209
  `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`);
210
  }
211
- table[id] = { ...table[id], id, version: -(currentVersion + 1) };
212
  if (!this.graphSaveActive) this.persist();
213
- return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } };
 
214
  }
215
  throw new Error(`Unsupported mutation action: ${mutation.action}`);
216
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  async query(context: any, req: any): Promise<any> {
218
  return { rows: [] };
219
  }
220
  async executeQuery(query: any): Promise<any> {
 
 
221
  if (!(query instanceof RuntimeSelectQuery)) {
222
  throw new Error("TeaQL list execution requires the formal runtime SelectQuery");
223
  }
224
  query.prepareForList();
225
- let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row }));
 
 
 
 
226
  const matches = (row: any, expression: any): boolean => {
227
  if (expression?.$and) return expression.$and.every((item: any) => matches(row, item));
228
  return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => {
229
- if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq);
230
- if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne);
 
 
 
 
231
  if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains));
232
  if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains));
233
  if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith));
@@ -235,15 +438,17 @@ export class TeaQLClient implements TeaQLDataService {
235
  if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith));
236
  if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith));
237
  if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike);
238
- if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value));
239
- if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value));
240
- if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1];
 
 
241
  if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined;
242
  if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined;
243
- if (predicate?.$gt !== undefined) return row[field] > predicate.$gt;
244
- if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte;
245
- if (predicate?.$lt !== undefined) return row[field] < predicate.$lt;
246
- if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte;
247
  return true;
248
  });
249
  };
@@ -257,17 +462,19 @@ export class TeaQLClient implements TeaQLDataService {
257
  }))];
258
  }
259
  for (const order of [...query.orderItems].reverse()) {
260
- 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));
 
261
  }
262
  const start = query.offsetValue || 0;
263
  rows = rows.slice(start, start + query.limitValue);
264
  for (const relation of (query.relations || []) as any[]) {
265
- const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"]));
266
- const relatedRows = (await this.executeQuery(relation.query)).filter(
267
- (row: any) => localValues.has(row[relation.foreignKey || "id"]));
268
  for (const row of rows) {
269
- const matches = relatedRows.filter(
270
- (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]);
 
 
 
 
271
  row[relation.name] = relation.many === false ? matches[0] : matches;
272
  }
273
  }
@@ -277,6 +484,8 @@ export class TeaQLClient implements TeaQLDataService {
277
  rows = rows.map((row: any) => Object.fromEntries(
278
  Object.entries(row).filter(([field]) => selections.has(field))));
279
  }
 
 
280
  return rows;
281
  }
282
  async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise<number> {
@@ -294,6 +503,7 @@ export class TeaQLClient implements TeaQLDataService {
294
  return value;
295
  }
296
  async *executeForStream(query: any, chunkSize = 1000): AsyncIterable<any[]> {
 
297
  if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer");
298
  const rows = await this.executeQuery(query);
299
  for (let offset = 0; offset < rows.length; offset += chunkSize) {
 
1
  import {
2
+ CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider,
3
  SelectQuery as RuntimeSelectQuery, UserContext,
4
+ GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout,
5
+ EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId,
6
  } from "teaql-ts";
7
 
8
  export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts";
9
+ export { decimal, compareDecimals } from "teaql-ts";
10
+ export type { Decimal } from "teaql-ts";
11
+ export { long, compareLongs, localTime } from "teaql-ts";
12
+ export type { Long, LocalTime } from "teaql-ts";
13
+ export { entityVersion, nextEntityVersion } from "teaql-ts";
14
+ export { internalId } from "teaql-ts";
15
+ export { EntityCreation, EntityCreationError } from "teaql-ts";
16
+ export { integer32Error } from "teaql-ts";
17
+ export type { EntityVersion } from "teaql-ts";
18
+ export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts";
19
+ export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts";
20
  export type { EntityKey } from "teaql-ts";
21
  export type { TeaQLPage } from "teaql-ts";
22
  import type { QueryOperation } from "teaql-ts";
23
+ import type { EntitySchema } from "teaql-ts/sql/core";
24
 
25
  function soundex(input: unknown): string {
26
  const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, "");
 
53
  }
54
 
55
  export interface TeaQLDataService {
56
+ reserveInternalId(entity: string, context: UserContext): Promise<string>;
57
+ executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>, prepare?: (graph: GraphMutationSession) => void | Promise<void>, admit?: (graph: GraphMutationSession) => boolean): Promise<T>;
58
  preflightMutation(mutation: any): any;
59
  afterGraphCommit(work: () => void): void;
60
  afterGraphRollback(work: () => void): void;
 
65
  close?(): Promise<void>;
66
  }
67
 
68
+ export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService {
69
  private data: Record<string, Record<string, any>> = {};
70
  private nextIds: Record<string, number> = {};
71
  private readonly checkers: Record<string, EntityChecker> = {};
72
+ private readonly schemas: Record<string, EntitySchema> = {};
73
  private userContext = new UserContext();
74
  private graphSaveActive = false;
75
+ private activeGraph?: GraphMutationSession;
76
  private graphCommitActions: Array<() => void> = [];
77
  private graphRollbackActions: Array<() => void> = [];
78
+ private graphAuditActions: Array<() => Promise<void>> = [];
79
  private graphSaveTail: Promise<void> = Promise.resolve();
80
  private readonly mutationGovernanceEvents: any[] = [];
81
+ private readonly auditEvents: Readonly<Record<string, unknown>>[] = [];
82
+ private auditSink?: (event: Readonly<Record<string, unknown>>) => void | Promise<void>;
83
 
84
  constructor(private storagePath?: string) {
85
+ super();
86
  if (storagePath) {
87
  const fs = require("fs");
88
  if (fs.existsSync(storagePath)) {
 
95
 
96
  /** Installs passive generated metadata. It never mutates storage. */
97
  install(module: RuntimeModule): this {
98
+ this.installBootstrap(module.bootstrap);
99
  Object.assign(this.checkers, module.checkers);
100
+ Object.assign(this.schemas, module.schemas);
101
  return this;
102
  }
103
 
104
+ protected enterSchemaContext(context: UserContext): () => void {
105
+ const previous = this.userContext;
106
+ this.userContext = context;
107
+ return () => { this.userContext = previous; };
108
+ }
109
+
110
+ protected async ensurePhysicalSchema(_context: UserContext): Promise<void> {
111
+ // JSON/in-memory storage has no physical DDL. The runtime still requires
112
+ // the explicit Context invocation before running generated bootstrap.
113
+ }
114
+
115
+ private storagePayload(entity: string, payload: Record<string, any>): Record<string, any> {
116
+ const values = { ...payload };
117
+ for (const relation of Object.values(this.schemas[entity]?.relations || {})) {
118
+ if (relation.many) continue;
119
+ const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName;
120
+ const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName)
121
+ ? modelName : relation.localKey;
122
+ if (!Object.prototype.hasOwnProperty.call(values, field)) continue;
123
+ const value = values[field];
124
+ if (value === null || value === undefined || typeof value !== "object") continue;
125
+ if (value.id === null || value.id === undefined) {
126
+ throw new Error(`Unresolved relation identity: ${entity}.${field}`);
127
+ }
128
+ values[field] = String(value.id);
129
+ }
130
+ return values;
131
+ }
132
+
133
+ /** Physical/model keys stay canonical; generated entities use native TS members. */
134
+ private runtimeRecord(entity: string, record: Record<string, any>): Record<string, any> {
135
+ const columns = this.schemas[entity]?.columns;
136
+ if (!columns) return { ...record };
137
+ const result: Record<string, any> = {};
138
+ for (const [name, column] of Object.entries(columns)) {
139
+ const key = column.modelName ?? name;
140
+ result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key]
141
+ : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null;
142
+ }
143
+ if (result.version != null) result.version = entityVersion(result.version);
144
+ return result;
145
+ }
146
+
147
+ private checkedMutationVersion(mutation: any): EntityVersion | undefined {
148
+ if (mutation.action === "Create") return undefined;
149
+ if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined;
150
+ const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion);
151
+ if (mutation.version !== undefined && mutation.expectedVersion !== undefined
152
+ && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type");
153
+ nextEntityVersion(mutation.action, version);
154
+ return version;
155
+ }
156
+
157
+ private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any {
158
+ Object.defineProperties(mutation, {
159
+ version: { value: original, enumerable: true, writable: false, configurable: false },
160
+ expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false },
161
+ action: { value: mutation.action, enumerable: true, writable: false, configurable: false },
162
+ });
163
+ return mutation;
164
+ }
165
+
166
  setUserContext(context: UserContext): this {
167
  this.userContext = context;
168
  return this;
 
172
  return [...this.mutationGovernanceEvents];
173
  }
174
 
175
+ get auditTrace(): ReadonlyArray<Readonly<Record<string, unknown>>> { return [...this.auditEvents]; }
176
+ setAuditSink(sink: (event: Readonly<Record<string, unknown>>) => void | Promise<void>): this {
177
+ this.auditSink = sink;
178
+ return this;
179
+ }
180
+
181
+ async reserveInternalId(entity: string, context: UserContext): Promise<string> {
182
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation");
183
+ if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required");
184
+ if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save");
185
+ const predecessor = this.graphSaveTail;
186
+ let release!: () => void;
187
+ this.graphSaveTail = new Promise<void>(resolve => { release = resolve; });
188
+ await predecessor;
189
+ const previous = this.nextIds[entity];
190
+ try {
191
+ const id = internalId(previous ?? 1);
192
+ this.nextIds[entity] = Number(id) + 1;
193
+ this.persist();
194
+ return id;
195
+ } catch (error) {
196
+ if (previous === undefined) delete this.nextIds[entity];
197
+ else this.nextIds[entity] = previous;
198
+ throw error;
199
+ } finally { release(); }
200
+ }
201
+
202
  private persist() {
203
  if (!this.storagePath) return;
204
  const fs = require("fs");
 
209
  fs.renameSync(temporaryPath, this.storagePath);
210
  }
211
 
212
+ async executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>, prepare?: (graph: GraphMutationSession) => void | Promise<void>, admit?: (graph: GraphMutationSession) => boolean): Promise<T> {
213
  const graph = new GraphMutationSession(intent);
214
+ const executionContext = this.userContext;
215
+ graph.bindExecutionReference(() => this.userContext);
216
+ graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()}));
217
+ for (const name of Object.keys(this.checkers)) {
218
+ graph.bindExecutionReference(() => this.checkers[name]);
219
+ graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix);
220
+ }
221
  const predecessor = this.graphSaveTail;
222
  let release!: () => void;
223
  this.graphSaveTail = new Promise<void>(resolve => { release = resolve; });
 
226
  const nextIdsSnapshot = { ...this.nextIds };
227
  let fixEvidenceStarted = false;
228
  let mutationPolicyGraphStarted = false;
229
+ let committed = false;
230
  try {
231
+ graph.validatePreparedSources();
232
  this.graphSaveActive = true;
233
+ this.activeGraph = graph;
234
  this.graphCommitActions = [];
235
  this.graphRollbackActions = [];
236
+ this.graphAuditActions = [];
237
+ const pending = admit?.(graph);
238
+ if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED");
239
+ graph.captureInputSources();
240
+ if (pending === false) { graph.sealPreparedGraph(); return await work(graph); }
241
+ // Reject a competing Context owner before changing its Fix resources.
242
+ executionContext.beginMutationPolicyGraph();
243
  mutationPolicyGraphStarted = true;
244
+ executionContext.insertResource("fixTime", executionContext.businessTime());
245
+ executionContext.beginFixEvidence();
246
+ fixEvidenceStarted = true;
247
+ await prepare?.(graph);
248
+ if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph();
249
+ executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity);
250
+ graph.validatePreparedSources();
251
  const result = await work(graph);
252
+ graph.requirePreparedComplete();
253
+ executionContext.ensureMutationPolicyGraphComplete();
254
+ if (!graph.isPreparedEmpty) this.persist();
255
+ committed = true;
256
+ let failure: unknown;
257
+ let failed = false;
258
+ for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) {
259
+ try { await action(); } catch (error) { if (!failed) failure = error; failed = true; }
260
+ }
261
+ if (failed) throw new GraphCommittedError(failure);
262
  return result;
263
  } catch (error) {
264
+ if (!committed) {
265
+ this.data = dataSnapshot;
266
+ this.nextIds = nextIdsSnapshot;
267
+ for (const action of [...this.graphRollbackActions].reverse()) {
268
+ try { action(); } catch { /* retain the original failure */ }
269
+ }
270
+ }
271
  throw error;
272
  } finally {
273
  this.graphSaveActive = false;
274
+ this.activeGraph = undefined;
275
  this.graphCommitActions = [];
276
  this.graphRollbackActions = [];
277
+ this.graphAuditActions = [];
278
+ if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph();
279
+ if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence();
280
  release();
281
  }
282
  }
 
292
  }
293
 
294
  preflightMutation(mutation: any): any {
295
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
296
+ request.graphSession?.recordPreparedMutation();
297
+ mutation = this.checkAndFixMutation(request);
298
+ if (request.graphSession) {
299
+ const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())];
300
+ request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated",
301
+ parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) });
302
+ }
303
+ const schema = this.schemas[mutation.entity];
304
+ const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many)
305
+ .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity]));
306
+ const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation;
307
+ this.userContext.recordMutationPolicyPreflight(policyMutation);
308
  return mutation;
309
  }
310
 
311
  private checkAndFixMutation(mutation: any): any {
312
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
313
+ if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) {
314
+ throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability");
315
+ }
316
+ const prepared = request.graphSession?.replayPreparedMutation(request);
317
+ if (prepared) return prepared;
318
+ mutation = request.mutation;
319
+ const schema = this.schemas[String(mutation.entity)];
320
+ if (schema) {
321
+ const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name));
322
+ fields.validate(mutation.payload ?? {}, mutation.action === "Update");
323
+ if (mutation.ledgerKey && mutation.ledgerRoot) {
324
+ if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH");
325
+ fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update");
326
+ }
327
+ }
328
+ const originalVersion = this.checkedMutationVersion(mutation);
329
  mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } };
330
+ request.bindCheckerLoadedValues(mutation);
331
+ Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true });
332
+ const declaringEntityType = String(mutation.entity);
333
+ const width = new ModeledInteger32Layout(declaringEntityType, schema);
334
+ const checker = this.checkers[declaringEntityType];
335
+ if (!checker) {
336
+ const violations = width.checkMutation(mutation.payload || {});
337
+ if (violations.length) throw new CheckException(violations);
338
+ return this.sealMutationVersion(mutation, originalVersion);
339
+ }
340
  const results: any[] = [];
341
  const ownsFixTime = this.userContext.getResource("fixTime") === undefined;
342
+ if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence();
343
  try {
344
  checker.checkAndFix(this.userContext, mutation, results);
345
+ if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion)
346
+ throw new MutationVersionError("invalid_type");
347
+ width.checkMutation(mutation.payload || {}, results);
348
+ this.userContext.translateCheckResults(results, declaringEntityType);
349
  if (results.length) throw new CheckException(results);
350
+ // Loaded Delete values are validation/audit input, never field-write intent.
351
+ if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value);
352
+ return this.sealMutationVersion(mutation, originalVersion);
353
  } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); }
354
  }
355
 
356
  async executeMutation(mutation: any): Promise<any> {
357
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
358
+ request.graphSession?.requireMutationAllowed();
359
+ mutation = this.checkAndFixMutation(request);
360
+ const nextVersion = nextEntityVersion(mutation.action, mutation.version);
361
  const mutationGovernance = this.userContext.enterMutationPolicy(mutation);
 
362
  const table = this.data[mutation.entity] ||= {};
363
+ const payload = this.storagePayload(mutation.entity, mutation.payload);
364
  if (mutation.action === "Create") {
365
  const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1);
366
+ if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`);
367
+ this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1);
368
+ const record = { ...payload, id: String(id), version: nextVersion };
369
  table[String(id)] = record;
370
  if (!this.graphSaveActive) this.persist();
371
+ return this.finishMutation(request, mutation, mutationGovernance,
372
+ { success: true, id: String(id), version: record.version, persistedRecord: { ...record } });
 
 
 
 
 
 
 
 
 
 
 
 
373
  }
374
+ if (["Update", "Delete", "Recover"].includes(mutation.action)) {
375
  const id = String(mutation.id);
376
  if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`);
377
+ const expectedVersion = entityVersion(mutation.version);
378
+ const currentVersion = entityVersion(table[id].version);
379
+ if (expectedVersion !== currentVersion) {
380
  throw new Error(
381
  `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`);
382
  }
383
+ table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion };
384
  if (!this.graphSaveActive) this.persist();
385
+ return this.finishMutation(request, mutation, mutationGovernance,
386
+ { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } });
387
  }
388
  throw new Error(`Unsupported mutation action: ${mutation.action}`);
389
  }
390
+ private async finishMutation(request: MutationRequest<any>, mutation: any,
391
+ mutationGovernance: unknown, result: any): Promise<any> {
392
+ request.graphSession?.recordPreparedResult(request, result);
393
+ const event = Object.freeze({ entity: mutation.entity, action: mutation.action,
394
+ id: result.id, version: result.version,
395
+ ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload),
396
+ changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()),
397
+ mutationGovernance,
398
+ actor: this.userContext.getResource("bootstrapActor"),
399
+ category: this.userContext.getResource("bootstrapCategory"),
400
+ recordedAt: (this.userContext.getResource<Date>("fixTime") ?? new Date()).toISOString() });
401
+ const publish = async () => {
402
+ this.mutationGovernanceEvents.push(mutationGovernance);
403
+ this.auditEvents.push(event);
404
+ await this.auditSink?.(event);
405
+ };
406
+ if (request.graphSession) this.graphAuditActions.push(publish);
407
+ else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } }
408
+ return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) };
409
+ }
410
  async query(context: any, req: any): Promise<any> {
411
  return { rows: [] };
412
  }
413
  async executeQuery(query: any): Promise<any> {
414
+ const request = query instanceof QueryRequest ? query : new QueryRequest(query);
415
+ query = request.query;
416
  if (!(query instanceof RuntimeSelectQuery)) {
417
  throw new Error("TeaQL list execution requires the formal runtime SelectQuery");
418
  }
419
  query.prepareForList();
420
+ const visibility = query.deletionVisibility ?? "live";
421
+ if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY");
422
+ let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row));
423
+ if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row =>
424
+ compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1));
425
  const matches = (row: any, expression: any): boolean => {
426
  if (expression?.$and) return expression.$and.every((item: any) => matches(row, item));
427
  return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => {
428
+ const compare = (value: any): number => field === "version" && value != null && row[field] != null
429
+ ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value)))
430
+ : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1;
431
+ const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value);
432
+ if (predicate?.$eq !== undefined) return equal(predicate.$eq);
433
+ if (predicate?.$ne !== undefined) return !equal(predicate.$ne);
434
  if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains));
435
  if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains));
436
  if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith));
 
438
  if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith));
439
  if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith));
440
  if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike);
441
+ if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value));
442
+ if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value));
443
+ if (predicate?.$between !== undefined) return field === "version"
444
+ ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0
445
+ : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1];
446
  if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined;
447
  if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined;
448
+ if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt;
449
+ if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte;
450
+ if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt;
451
+ if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte;
452
  return true;
453
  });
454
  };
 
462
  }))];
463
  }
464
  for (const order of [...query.orderItems].reverse()) {
465
+ rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version))
466
+ : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1));
467
  }
468
  const start = query.offsetValue || 0;
469
  rows = rows.slice(start, start + query.limitValue);
470
  for (const relation of (query.relations || []) as any[]) {
 
 
 
471
  for (const row of rows) {
472
+ // Scope before ordering/offset/limit. A nested bound belongs to
473
+ // each parent, not to unrelated children from earlier saves.
474
+ const childQuery = relation.query.clone();
475
+ childQuery.filter({$and: [childQuery.filterCondition ?? {},
476
+ {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]});
477
+ const matches = await this.executeQuery(request.derive(childQuery, relation.name));
478
  row[relation.name] = relation.many === false ? matches[0] : matches;
479
  }
480
  }
 
484
  rows = rows.map((row: any) => Object.fromEntries(
485
  Object.entries(row).filter(([field]) => selections.has(field))));
486
  }
487
+ const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]);
488
+ for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]);
489
  return rows;
490
  }
491
  async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise<number> {
 
503
  return value;
504
  }
505
  async *executeForStream(query: any, chunkSize = 1000): AsyncIterable<any[]> {
506
+ query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query;
507
  if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer");
508
  const rows = await this.executeQuery(query);
509
  for (let offset = 0; offset < rows.length; offset += chunkSize) {
source/teaql-ts/examples/browser-sqlite/package-lock.json CHANGED
@@ -19,7 +19,7 @@
19
  },
20
  "../..": {
21
  "name": "@teaql/teaql",
22
- "version": "0.3.1",
23
  "license": "Apache-2.0",
24
  "dependencies": {
25
  "node-fetch": "^2.7.0"
@@ -43,7 +43,7 @@
43
  "@types/jest": "^29.5.0",
44
  "@types/node-fetch": "^2.6.13",
45
  "@types/pg": "^8.11.0",
46
- "better-sqlite3": "^12.10.0",
47
  "esbuild": "^0.28.2",
48
  "jest": "^29.5.0",
49
  "jest-util": "^29.7.0",
@@ -70,7 +70,7 @@
70
  "@opentelemetry/sdk-metrics": "^2.10.0",
71
  "@opentelemetry/sdk-trace-base": "^2.10.0",
72
  "@sqlite.org/sqlite-wasm": "3.53.0-build1",
73
- "better-sqlite3": "^12.10.0",
74
  "expo-sqlite": "*",
75
  "mysql2": "^3.11.0",
76
  "pg": "^8.12.0",
 
19
  },
20
  "../..": {
21
  "name": "@teaql/teaql",
22
+ "version": "0.5.0",
23
  "license": "Apache-2.0",
24
  "dependencies": {
25
  "node-fetch": "^2.7.0"
 
43
  "@types/jest": "^29.5.0",
44
  "@types/node-fetch": "^2.6.13",
45
  "@types/pg": "^8.11.0",
46
+ "better-sqlite3": "^13.0.3",
47
  "esbuild": "^0.28.2",
48
  "jest": "^29.5.0",
49
  "jest-util": "^29.7.0",
 
70
  "@opentelemetry/sdk-metrics": "^2.10.0",
71
  "@opentelemetry/sdk-trace-base": "^2.10.0",
72
  "@sqlite.org/sqlite-wasm": "3.53.0-build1",
73
+ "better-sqlite3": "^13.0.3",
74
  "expo-sqlite": "*",
75
  "mysql2": "^3.11.0",
76
  "pg": "^8.12.0",
source/teaql-ts/examples/browser-sqlite/scripts/orders-smoke.mjs CHANGED
@@ -29,9 +29,14 @@ try {
29
  ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
30
  : '/usr/bin/google-chrome'),
31
  args: ['--no-sandbox', '--disable-dev-shm-usage'], headless: true});
32
- const page = await browser.newPage(), errors = [];
33
  page.on('pageerror', error => errors.push(error.message));
34
- page.on('console', event => { if (event.type() === 'error') errors.push(event.text()); });
 
 
 
 
 
35
  page.on('response', response => { if (response.status() >= 400) errors.push(`${response.status()} ${response.url()}`); });
36
  page.on('requestfailed', request => errors.push(`${request.failure()?.errorText} ${request.url()}`));
37
  async function waitReady(storage) {
@@ -55,7 +60,7 @@ try {
55
  assert.deepEqual(order.items.map(item => [item.productName, item.quantity]), [['Box 1', 1], ['Box 2', 2], ['Box 3', 3]]);
56
  assert.equal(order.itemCount, 5);
57
  assert.deepEqual(response.facets.statusCounts.map(row => [String(row.id), row.orderCount, row.orderTotalAmount]),
58
- [['1001', 1, 100], ['1002', 2, 500], ['1003', 0, null]]);
59
  const evidence = JSON.parse(await page.$eval('#sql', element => element.textContent));
60
  assert.equal(evidence.length, 8);
61
  const comments = evidence.map(entry => entry.traceChain.filter(node => node.kind === 'comment').map(node => node.detail));
@@ -109,6 +114,9 @@ try {
109
  assert.deepEqual(await inspect('opfs-reset', 8), baseline);
110
  assert.deepEqual(errors, []); checkLibrary();
111
  if (process.env.TEAQL_BROWSER_ORDER_EVIDENCE) writeFileSync(process.env.TEAQL_BROWSER_ORDER_EVIDENCE,
112
- JSON.stringify({receipts, generatedLibraryUnchanged: true, browserErrors: errors}, null, 2) + '\n', {flag: 'wx'});
 
 
 
113
  console.log('PASS browser generated order TraceChain: memory/OPFS, refresh/reset, logging on/off, exact facets/counts/previews, actual SQL=8, unchanged generated library');
114
  } finally { await browser?.close(); server.kill('SIGTERM'); }
 
29
  ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
30
  : '/usr/bin/google-chrome'),
31
  args: ['--no-sandbox', '--disable-dev-shm-usage'], headless: true});
32
+ const page = await browser.newPage(), errors = [], rawMutationConsole = [];
33
  page.on('pageerror', error => errors.push(error.message));
34
+ page.on('console', event => {
35
+ if (event.type() === 'error') errors.push(event.text());
36
+ // Mutation diagnostics are disabled above. A second SDK write tracer must
37
+ // not bypass TeaQL's policy-aware diagnostic channel.
38
+ if (/\b(?:INSERT INTO|UPDATE\s+.+\s+SET|DELETE FROM)\b/i.test(event.text())) rawMutationConsole.push(event.text());
39
+ });
40
  page.on('response', response => { if (response.status() >= 400) errors.push(`${response.status()} ${response.url()}`); });
41
  page.on('requestfailed', request => errors.push(`${request.failure()?.errorText} ${request.url()}`));
42
  async function waitReady(storage) {
 
60
  assert.deepEqual(order.items.map(item => [item.productName, item.quantity]), [['Box 1', 1], ['Box 2', 2], ['Box 3', 3]]);
61
  assert.equal(order.itemCount, 5);
62
  assert.deepEqual(response.facets.statusCounts.map(row => [String(row.id), row.orderCount, row.orderTotalAmount]),
63
+ [['1001', 1, '100'], ['1002', 2, '500'], ['1003', 0, null]]);
64
  const evidence = JSON.parse(await page.$eval('#sql', element => element.textContent));
65
  assert.equal(evidence.length, 8);
66
  const comments = evidence.map(entry => entry.traceChain.filter(node => node.kind === 'comment').map(node => node.detail));
 
114
  assert.deepEqual(await inspect('opfs-reset', 8), baseline);
115
  assert.deepEqual(errors, []); checkLibrary();
116
  if (process.env.TEAQL_BROWSER_ORDER_EVIDENCE) writeFileSync(process.env.TEAQL_BROWSER_ORDER_EVIDENCE,
117
+ JSON.stringify({receipts, generatedLibraryUnchanged: true, browserErrors: errors,
118
+ rawMutationConsoleCount: rawMutationConsole.length}, null, 2) + '\n', {flag: 'wx'});
119
+ console.log('BROWSER_RAW_SQL_OBSERVATION=' + JSON.stringify({rawMutationConsoleCount: rawMutationConsole.length}));
120
+ assert.equal(rawMutationConsole.length, 0, 'An ungoverned SQLite write tracer bypassed the runtime diagnostic policy');
121
  console.log('PASS browser generated order TraceChain: memory/OPFS, refresh/reset, logging on/off, exact facets/counts/previews, actual SQL=8, unchanged generated library');
122
  } finally { await browser?.close(); server.kill('SIGTERM'); }
source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs CHANGED
@@ -79,6 +79,27 @@ try {
79
  || runtimeLanguages.links.some(language => !language.href.startsWith('https://github.com/teaql/'))) {
80
  throw new Error(`Seven-runtime selector is incomplete: ${JSON.stringify(runtimeLanguages)}`);
81
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  const observabilityProof = await page.evaluate(() => {
83
  const image = document.querySelector('.observability-proof img');
84
  return {
@@ -373,6 +394,11 @@ try {
373
  title: document.querySelector('#query-browser-title')?.textContent || '',
374
  runtimeTitle: document.querySelector('#runtime-language-title')?.textContent || '',
375
  currentRuntime: document.querySelector('.runtime-language.active small')?.textContent || '',
 
 
 
 
 
376
  observabilityTitle: document.querySelector('#observability-proof-title')?.textContent || '',
377
  observabilityCaption: document.querySelector('.observability-proof figcaption')?.textContent || '',
378
  evidenceTitle: document.querySelector('.sql-card-heading .query-card-label')?.textContent || '',
@@ -383,6 +409,10 @@ try {
383
  if (chineseLocale.title !== '选择一个查询'
384
  || chineseLocale.runtimeTitle !== '这个演示在浏览器中运行 TypeScript。'
385
  || chineseLocale.currentRuntime !== '当前浏览器 runtime'
 
 
 
 
386
  || chineseLocale.observabilityTitle !== 'OpenObserve 中的 TraceChain'
387
  || chineseLocale.observabilityCaption !== 'OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。'
388
  || chineseLocale.evidenceTitle !== '执行证据'
 
79
  || runtimeLanguages.links.some(language => !language.href.startsWith('https://github.com/teaql/'))) {
80
  throw new Error(`Seven-runtime selector is incomplete: ${JSON.stringify(runtimeLanguages)}`);
81
  }
82
+ const developmentProcess = await page.evaluate(() => ({
83
+ title: document.querySelector('#development-process-title')?.textContent || '',
84
+ steps: [...document.querySelectorAll('.development-process-flow > li')].map(step => ({
85
+ title: step.querySelector('strong')?.textContent || '',
86
+ code: step.querySelector('code')?.textContent || '',
87
+ })),
88
+ modelHref: document.querySelector('.source-link-primary')?.getAttribute('href') || '',
89
+ assistHref: document.querySelector('.development-process-links .source-link:not(.source-link-primary)')?.getAttribute('href') || '',
90
+ contextTitle: document.querySelector('.context-efficiency h3')?.textContent || '',
91
+ }));
92
+ if (developmentProcess.title !== 'From one domain model to executable evidence.'
93
+ || developmentProcess.steps.length !== 4
94
+ || developmentProcess.steps.map(step => step.code).join('|')
95
+ !== 'order-model.xml|Q · E · Schema · Assist|comment · purpose · execute|Result · TraceChain · SQL'
96
+ || developmentProcess.modelHref
97
+ !== 'https://github.com/teaql/teaql-ts/blob/main/examples/browser-sqlite/order-model.xml'
98
+ || developmentProcess.assistHref
99
+ !== 'https://github.com/teaql/teaql-ts/tree/main/examples/browser-sqlite/assist'
100
+ || developmentProcess.contextTitle !== 'Spend context on the business change.') {
101
+ throw new Error(`Development process explanation is incomplete: ${JSON.stringify(developmentProcess)}`);
102
+ }
103
  const observabilityProof = await page.evaluate(() => {
104
  const image = document.querySelector('.observability-proof img');
105
  return {
 
394
  title: document.querySelector('#query-browser-title')?.textContent || '',
395
  runtimeTitle: document.querySelector('#runtime-language-title')?.textContent || '',
396
  currentRuntime: document.querySelector('.runtime-language.active small')?.textContent || '',
397
+ developmentTitle: document.querySelector('#development-process-title')?.textContent || '',
398
+ modelLink: document.querySelector('.source-link-primary strong')?.textContent || '',
399
+ processSteps: [...document.querySelectorAll('.development-process-flow > li strong')]
400
+ .map(element => element.textContent || ''),
401
+ contextTitle: document.querySelector('.context-efficiency h3')?.textContent || '',
402
  observabilityTitle: document.querySelector('#observability-proof-title')?.textContent || '',
403
  observabilityCaption: document.querySelector('.observability-proof figcaption')?.textContent || '',
404
  evidenceTitle: document.querySelector('.sql-card-heading .query-card-label')?.textContent || '',
 
409
  if (chineseLocale.title !== '选择一个查询'
410
  || chineseLocale.runtimeTitle !== '这个演示在浏览器中运行 TypeScript。'
411
  || chineseLocale.currentRuntime !== '当前浏览器 runtime'
412
+ || chineseLocale.developmentTitle !== '从一份领域模型,到可以执行和审查的证据。'
413
+ || chineseLocale.modelLink !== '查看 order-model.xml'
414
+ || chineseLocale.processSteps.join('|') !== '建立领域模型|生成领域开发接口|构建一个有界的 Q 请求|运行并保留证据'
415
+ || chineseLocale.contextTitle !== '把上下文窗口留给真正的业务变更。'
416
  || chineseLocale.observabilityTitle !== 'OpenObserve 中的 TraceChain'
417
  || chineseLocale.observabilityCaption !== 'OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。'
418
  || chineseLocale.evidenceTitle !== '执行证据'
source/teaql-ts/examples/browser-sqlite/src/main.ts CHANGED
@@ -70,6 +70,24 @@ const UI_COPY: Readonly<Record<string, LocalizedCopy>> = {
70
  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 源码。' },
71
  currentBrowserRuntime: { en: 'Current browser runtime', zh: '当前浏览器 runtime' },
72
  supportedRuntime: { en: 'Supported runtime', zh: '已支持 runtime' },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  observabilityTitle: { en: 'TraceChain in OpenObserve', zh: 'OpenObserve 中的 TraceChain' },
74
  observabilityIntro: { en: 'A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.', zh: '一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。' },
75
  observabilityCaption: { en: 'OpenObserve dashboard showing one verified trace and its eight actual SQL executions.', zh: 'OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。' },
@@ -475,7 +493,7 @@ const QUERY_GROUPS: readonly QueryGroup[] = [
475
  code: `const input = {
476
  "filter": {
477
  "currency": "CNY",
478
- "totalAmount": { "$gte": 250 },
479
  "status": { "$in": ["PAID", "SHIPPED"] }
480
  },
481
  "orderBy": [{ "field": "totalAmount", "direction": "desc" }]
@@ -489,7 +507,7 @@ const data = await Q.customerOrders()
489
  run: active => dynamicOrderQuery(active, {
490
  filter: {
491
  currency: 'CNY',
492
- totalAmount: { $gte: 250 },
493
  status: { $in: ['PAID', 'SHIPPED'] },
494
  },
495
  orderBy: [{ field: 'totalAmount', direction: 'desc' }],
@@ -590,7 +608,13 @@ async function seedDemoData(active: Runtime): Promise<void> {
590
  entity: record.entity,
591
  action: 'Create',
592
  id: record.id,
593
- payload: record.payload,
 
 
 
 
 
 
594
  }));
595
  for (const request of requests) active.client.preflightMutation(request);
596
  for (const request of requests) await active.client.executeMutation(request);
 
70
  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 源码。' },
71
  currentBrowserRuntime: { en: 'Current browser runtime', zh: '当前浏览器 runtime' },
72
  supportedRuntime: { en: 'Supported runtime', zh: '已支持 runtime' },
73
+ developmentProcess: { en: '00 / DEVELOPMENT PROCESS', zh: '00 / 开发过程' },
74
+ developmentProcessTitle: { en: 'From one domain model to executable evidence.', zh: '从一份领域模型,到可以执行和审查的证据。' },
75
+ developmentProcessIntro: { en: 'TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.', zh: 'TeaQL 让业务模型保持精简、可读,从模型生成确定性的领域 API,并把请求意图一直带到 Runtime 实际执行的 SQL。' },
76
+ modelSource: { en: 'MODEL SOURCE', zh: '模型源文件' },
77
+ viewOrderModel: { en: 'View order-model.xml', zh: '查看 order-model.xml' },
78
+ scopedGuidance: { en: 'SCOPED GUIDANCE', zh: '按需指导' },
79
+ viewModelAssist: { en: 'View model-aware Assist', zh: '查看模型感知 Assist' },
80
+ processModelTitle: { en: 'Model the domain', zh: '建立领域模型' },
81
+ processModelBody: { en: 'Define entities, fields, relationships, constant objects, and constraints in one model file.', zh: '在一个模型文件中定义对象、字段、关系、常数对象和约束。' },
82
+ processGenerateTitle: { en: 'Generate the working surface', zh: '生成领域开发接口' },
83
+ processGenerateBody: { en: 'Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.', zh: '从模型生成强类型 Q 与 E API、Schema、可审计变更和字段级 Assist。' },
84
+ processQueryTitle: { en: 'Build one bounded Q request', zh: '构建一个有界的 Q 请求' },
85
+ processQueryBody: { en: 'Application code selects only what the page needs and attaches a readable comment and purpose.', zh: '应用代码只选择页面需要的内容,并附上可读的 comment 和 purpose。' },
86
+ processEvidenceTitle: { en: 'Run and retain evidence', zh: '运行并保留证据' },
87
+ processEvidenceBody: { en: 'The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.', zh: 'Runtime 执行策略和 SQLite/WASM,并保留从 purpose、嵌套 comment 到耗时和实际 SQL 的 TraceChain。' },
88
+ contextEfficiency: { en: 'CONTEXT EFFICIENCY', zh: '上下文效率' },
89
+ contextEfficiencyTitle: { en: 'Spend context on the business change.', zh: '把上下文窗口留给真正的业务变更。' },
90
+ contextEfficiencyBody: { en: 'Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.', zh: 'Agent 不需要加载 Runtime 内部实现和所有生成文件,而是从精简模型出发,只打开当前对象、动作或字段所需的 Assist。强类型领域操作把数据库和 Provider 细节压缩成更小的工作界面,减少重复占用上下文,同时保持行为确定、可审查。' },
91
  observabilityTitle: { en: 'TraceChain in OpenObserve', zh: 'OpenObserve 中的 TraceChain' },
92
  observabilityIntro: { en: 'A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.', zh: '一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。' },
93
  observabilityCaption: { en: 'OpenObserve dashboard showing one verified trace and its eight actual SQL executions.', zh: 'OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。' },
 
493
  code: `const input = {
494
  "filter": {
495
  "currency": "CNY",
496
+ "totalAmount": { "$gte": "250" },
497
  "status": { "$in": ["PAID", "SHIPPED"] }
498
  },
499
  "orderBy": [{ "field": "totalAmount", "direction": "desc" }]
 
507
  run: active => dynamicOrderQuery(active, {
508
  filter: {
509
  currency: 'CNY',
510
+ totalAmount: { $gte: '250' },
511
  status: { $in: ['PAID', 'SHIPPED'] },
512
  },
513
  orderBy: [{ field: 'totalAmount', direction: 'desc' }],
 
608
  entity: record.entity,
609
  action: 'Create',
610
  id: record.id,
611
+ // The fixture uses native JS member names; the mutation boundary uses
612
+ // model names from trusted metadata, never a guessed casing conversion.
613
+ payload: Object.fromEntries(Object.entries(record.payload).map(([field, value]) => {
614
+ const column = ORDER_SCHEMAS[record.entity]?.columns[field];
615
+ if (!column) throw new Error(`Unknown fixture field ${record.entity}.${field}`);
616
+ return [column.modelName ?? field, value];
617
+ })),
618
  }));
619
  for (const request of requests) active.client.preflightMutation(request);
620
  for (const request of requests) await active.client.executeMutation(request);
source/teaql-ts/examples/browser-sqlite/src/orders.ts CHANGED
@@ -1,5 +1,5 @@
1
  import { BrowserSQLiteTeaQLClient, type BrowserSQLiteStorage } from 'teaql-ts/sql/browser-sqlite';
2
- import { DelegatingMutationPolicyApprovalProvider, DelegatingMutationPolicyRegistry, UserContext } from 'teaql-ts';
3
  import { SQLExecutionEvidenceStore, type SQLExecutionMetadata } from 'teaql-ts/sql/core';
4
  import { Q } from '../orders-lib/src/generated/Q';
5
  import { E } from '../orders-lib/src/generated/E';
@@ -50,18 +50,18 @@ async function seed({context}: Runtime): Promise<void> {
50
  .comment('detect existing order demo').purpose('keep mutation seeding idempotent').executeForList(context);
51
  if (existing.length) return;
52
  const platform = (await Q.platforms().limit(2).comment('load bootstrap platform').purpose('prepare order demo').executeForList(context))[0];
53
- const customer = Q.customers().comment('initialize demo customer').purpose('prepare order demo').newEntity(context);
54
  customer.updateName('North Star Retail').updatePlatform(platform.id);
55
  await customer.auditAs('seed browser order customer').save(context);
56
  for (let index = 1; index <= 4; index++) {
57
- const order = Q.customerOrders().comment('initialize demo order').purpose('prepare order demo').newEntity(context);
58
  order.updateCustomer(customer.id).updateOrderNumber(index < 4 ? `KEEP-00${index}` : 'DROP-004')
59
- .updateOrderDate(`2026-10-0${index}`).updateTotalAmount(index < 4 ? index * 100 : 900);
60
  if (index === 1) order.updateStatusToNew(); else order.updateStatusToPaid();
61
  await order.auditAs('seed browser order').save(context);
62
  for (let item = 1; item <= 5; item++) {
63
- const line = Q.orderItems().comment('initialize demo item').purpose('prepare item previews').newEntity(context);
64
- line.updateCustomerOrder(order.id).updateProductName(`Box ${item}`).updateQuantity(item).updateUnitPrice(20);
65
  await line.auditAs('seed browser order item').save(context);
66
  }
67
  }
 
1
  import { BrowserSQLiteTeaQLClient, type BrowserSQLiteStorage } from 'teaql-ts/sql/browser-sqlite';
2
+ import { DelegatingMutationPolicyApprovalProvider, DelegatingMutationPolicyRegistry, UserContext, decimal } from 'teaql-ts';
3
  import { SQLExecutionEvidenceStore, type SQLExecutionMetadata } from 'teaql-ts/sql/core';
4
  import { Q } from '../orders-lib/src/generated/Q';
5
  import { E } from '../orders-lib/src/generated/E';
 
50
  .comment('detect existing order demo').purpose('keep mutation seeding idempotent').executeForList(context);
51
  if (existing.length) return;
52
  const platform = (await Q.platforms().limit(2).comment('load bootstrap platform').purpose('prepare order demo').executeForList(context))[0];
53
+ const customer = (await Q.customers().comment('initialize demo customer').purpose('prepare order demo').newEntity(context));
54
  customer.updateName('North Star Retail').updatePlatform(platform.id);
55
  await customer.auditAs('seed browser order customer').save(context);
56
  for (let index = 1; index <= 4; index++) {
57
+ const order = (await Q.customerOrders().comment('initialize demo order').purpose('prepare order demo').newEntity(context));
58
  order.updateCustomer(customer.id).updateOrderNumber(index < 4 ? `KEEP-00${index}` : 'DROP-004')
59
+ .updateOrderDate(`2026-10-0${index}`).updateTotalAmount(decimal(String(index < 4 ? index * 100 : 900)));
60
  if (index === 1) order.updateStatusToNew(); else order.updateStatusToPaid();
61
  await order.auditAs('seed browser order').save(context);
62
  for (let item = 1; item <= 5; item++) {
63
+ const line = (await Q.orderItems().comment('initialize demo item').purpose('prepare item previews').newEntity(context));
64
+ line.updateCustomerOrder(order.id).updateProductName(`Box ${item}`).updateQuantity(item).updateUnitPrice(decimal('20'));
65
  await line.auditAs('seed browser order item').save(context);
66
  }
67
  }
source/teaql-ts/examples/browser-sqlite/src/style.css CHANGED
@@ -159,6 +159,82 @@ h1 {
159
  .runtime-language small { color: #78837a; font-size: 8px; line-height: 1.25; }
160
  .runtime-language.active small { color: #d5e7da; }
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  .runtime-bar {
163
  min-height: 72px;
164
  padding: 14px 18px 14px 22px;
@@ -484,6 +560,10 @@ footer {
484
  .model-map { min-height: 260px; }
485
  .runtime-language-panel { grid-template-columns: 1fr; }
486
  .runtime-language-selector { grid-template-columns: repeat(4, minmax(100px, 1fr)); }
 
 
 
 
487
  .result-panel { margin: 0 -24px; padding-left: 24px; padding-right: 24px; }
488
  .result-grid { grid-template-columns: 1fr; }
489
  .observability-proof-heading { grid-template-columns: 1fr; align-items: start; gap: 14px; }
@@ -505,6 +585,16 @@ footer {
505
  .runtime-language-panel { padding: 20px 16px; gap: 20px; }
506
  .runtime-language-selector { grid-template-columns: repeat(2, minmax(0, 1fr)); }
507
  .runtime-language:last-child { grid-column: 1 / -1; }
 
 
 
 
 
 
 
 
 
 
508
  .runtime-bar, .section-heading, .result-heading { align-items: flex-start; flex-direction: column; }
509
  .runtime-bar { padding: 18px; }
510
  .controls { width: 100%; justify-content: space-between; }
 
159
  .runtime-language small { color: #78837a; font-size: 8px; line-height: 1.25; }
160
  .runtime-language.active small { color: #d5e7da; }
161
 
162
+ .development-process {
163
+ margin: 54px 0 28px;
164
+ padding: 42px;
165
+ border: 1px solid var(--line);
166
+ border-radius: 24px;
167
+ background: var(--paper);
168
+ box-shadow: 0 18px 48px rgba(33, 60, 40, .05);
169
+ }
170
+ .development-process-heading {
171
+ display: grid;
172
+ grid-template-columns: minmax(280px, .9fr) minmax(0, 1.1fr);
173
+ align-items: end;
174
+ gap: 48px;
175
+ }
176
+ .development-process-heading h2 {
177
+ margin: 0;
178
+ font-family: Georgia, "Noto Serif SC", serif;
179
+ font-size: clamp(30px, 3.5vw, 48px);
180
+ font-weight: 500;
181
+ line-height: 1.08;
182
+ letter-spacing: -.04em;
183
+ }
184
+ .development-process-intro > p { margin: 0; color: var(--muted); font-size: 16px; line-height: 1.7; }
185
+ .development-process-links { margin-top: 22px; display: flex; flex-wrap: wrap; gap: 10px; }
186
+ .source-link {
187
+ min-width: 210px;
188
+ padding: 12px 15px;
189
+ display: grid;
190
+ gap: 3px;
191
+ border: 1px solid #cad3c9;
192
+ border-radius: 10px;
193
+ color: var(--ink);
194
+ background: #f8faf5;
195
+ text-decoration: none;
196
+ transition: border-color .16s ease, background .16s ease, transform .16s ease;
197
+ }
198
+ .source-link:hover, .source-link:focus-visible { border-color: #819586; background: white; outline: none; transform: translateY(-1px); }
199
+ .source-link-primary { color: white; border-color: var(--green); background: var(--green); }
200
+ .source-link-primary:hover, .source-link-primary:focus-visible { border-color: var(--green-deep); background: var(--green-deep); }
201
+ .source-link span { color: #77847a; font-size: 10px; font-weight: 850; letter-spacing: .13em; }
202
+ .source-link-primary span { color: #c8dccd; }
203
+ .source-link strong { font-size: 14px; line-height: 1.35; }
204
+
205
+ .development-process-flow {
206
+ margin: 38px 0 0;
207
+ padding: 0;
208
+ display: grid;
209
+ grid-template-columns: repeat(4, minmax(0, 1fr));
210
+ border: 1px solid #d7ddd3;
211
+ border-radius: 16px;
212
+ background: #f8faf5;
213
+ list-style: none;
214
+ overflow: hidden;
215
+ }
216
+ .development-process-flow li { min-width: 0; padding: 22px; border-left: 1px solid #d7ddd3; }
217
+ .development-process-flow li:first-child { border-left: 0; }
218
+ .development-step { display: block; margin-bottom: 20px; color: var(--orange); font: 800 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace; }
219
+ .development-process-flow strong { display: block; min-height: 48px; font-size: 16px; line-height: 1.45; }
220
+ .development-process-flow p { min-height: 92px; margin: 10px 0 18px; color: var(--muted); font-size: 14px; line-height: 1.6; }
221
+ .development-process-flow code { color: var(--green); font: 650 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }
222
+
223
+ .context-efficiency {
224
+ margin-top: 18px;
225
+ padding: 24px;
226
+ display: grid;
227
+ grid-template-columns: minmax(230px, .72fr) minmax(0, 1.28fr);
228
+ align-items: center;
229
+ gap: 34px;
230
+ border-radius: 14px;
231
+ color: #edf7ef;
232
+ background: var(--green-deep);
233
+ }
234
+ .context-efficiency .section-index { margin-bottom: 8px; color: var(--lime); }
235
+ .context-efficiency h3 { margin: 0; font: 500 24px/1.2 Georgia, "Noto Serif SC", serif; letter-spacing: -.025em; }
236
+ .context-efficiency > p { margin: 0; color: #c7d8cc; font-size: 15px; line-height: 1.7; }
237
+
238
  .runtime-bar {
239
  min-height: 72px;
240
  padding: 14px 18px 14px 22px;
 
560
  .model-map { min-height: 260px; }
561
  .runtime-language-panel { grid-template-columns: 1fr; }
562
  .runtime-language-selector { grid-template-columns: repeat(4, minmax(100px, 1fr)); }
563
+ .development-process-heading { grid-template-columns: 1fr; align-items: start; gap: 24px; }
564
+ .development-process-flow { grid-template-columns: repeat(2, minmax(0, 1fr)); }
565
+ .development-process-flow li:nth-child(3) { border-left: 0; border-top: 1px solid #d7ddd3; }
566
+ .development-process-flow li:nth-child(4) { border-top: 1px solid #d7ddd3; }
567
  .result-panel { margin: 0 -24px; padding-left: 24px; padding-right: 24px; }
568
  .result-grid { grid-template-columns: 1fr; }
569
  .observability-proof-heading { grid-template-columns: 1fr; align-items: start; gap: 14px; }
 
585
  .runtime-language-panel { padding: 20px 16px; gap: 20px; }
586
  .runtime-language-selector { grid-template-columns: repeat(2, minmax(0, 1fr)); }
587
  .runtime-language:last-child { grid-column: 1 / -1; }
588
+ .development-process { margin-top: 38px; padding: 26px 18px; }
589
+ .development-process-intro > p { font-size: 15px; }
590
+ .development-process-links { align-items: stretch; flex-direction: column; }
591
+ .source-link { min-width: 0; width: 100%; }
592
+ .development-process-flow { grid-template-columns: 1fr; }
593
+ .development-process-flow li { border-top: 1px solid #d7ddd3; border-left: 0; }
594
+ .development-process-flow li:first-child { border-top: 0; }
595
+ .development-process-flow li:nth-child(3), .development-process-flow li:nth-child(4) { border-left: 0; }
596
+ .development-process-flow strong, .development-process-flow p { min-height: 0; }
597
+ .context-efficiency { grid-template-columns: 1fr; gap: 16px; padding: 20px; }
598
  .runtime-bar, .section-heading, .result-heading { align-items: flex-start; flex-direction: column; }
599
  .runtime-bar { padding: 18px; }
600
  .controls { width: 100%; justify-content: space-between; }