Spaces:
Running
Running
Deploy traceable order management playground
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+5
- README.md+30-40
- assets/dynamic-search-BBmdgl4H.jsAdded
- assets/index-3Oa_Nwum.jsDeleted
- assets/index-CSFBt0NB.jsDeleted
- assets/index-DTZ5iA72.jsDeleted
- assets/index-DmPc8xp3.cssDeleted-1
- assets/index-LiMSU-HT.jsDeleted
- assets/index-inj2slTy.cssDeleted-1
- assets/main-gHLGx1pH.jsAdded+102
- assets/object-location-xgYMemK6.jsAdded+1
- assets/orders-CQOGX0kN.jsAdded
- assets/style-SCdXWqgK.cssAdded+1
- assets/index-BMClFIER.css → assets/workItems-5mJKEgxC.cssRenamed+1-1
- assets/workItems-DraVJWt7.jsAdded+1
- dist/assets/dynamic-search-BBmdgl4H.jsAdded
- dist/assets/index-3Oa_Nwum.jsDeleted
- dist/assets/index-CSFBt0NB.jsDeleted
- dist/assets/index-DTZ5iA72.jsDeleted
- dist/assets/index-DmPc8xp3.cssDeleted-1
- dist/assets/index-LiMSU-HT.jsDeleted
- dist/assets/index-inj2slTy.cssDeleted-1
- dist/assets/main-gHLGx1pH.jsAdded+102
- dist/assets/object-location-xgYMemK6.jsAdded+1
- dist/assets/orders-CQOGX0kN.jsAdded
- dist/assets/style-SCdXWqgK.cssAdded+1
- dist/assets/index-BMClFIER.css → dist/assets/workItems-5mJKEgxC.cssRenamed+1-1
- dist/assets/workItems-DraVJWt7.jsAdded+1
- dist/index.html+138-41
- dist/orders.htmlAdded+43
- dist/work-items.htmlAdded+28
- evidence/live-browser.jsonDeleted
- evidence/local-browser.jsonDeleted
- index.html+138-41
- orders.htmlAdded+43
- source/browser-sqlite/generated-order-hashes.jsonDeleted-22
- source/browser-sqlite/scripts/verify-space.mjsDeleted-63
- source/browser-sqlite/src/web-response.tsDeleted-16
- source/browser-sqlite/vendor/teaql-teaql-0.3.0.tgzDeleted-3
- source/provenance.json+12-54
- source/teaql-ts/.npmignoreAdded+1
- source/teaql-ts/LICENSEAdded+202
- source/teaql-ts/README.mdAdded+369
- source/teaql-ts/examples/browser-sqlite/AGENTS.mdAdded+10
- source/teaql-ts/examples/browser-sqlite/README.mdAdded+118
- source/teaql-ts/examples/browser-sqlite/assist/create-customer.mdAdded+82
- source/teaql-ts/examples/browser-sqlite/assist/create-customer_order.mdAdded+92
- source/teaql-ts/examples/browser-sqlite/assist/create-order_item.mdAdded+86
- source/teaql-ts/examples/browser-sqlite/assist/debug.mdAdded+101
- source/teaql-ts/examples/browser-sqlite/assist/expression-customer_order.mdAdded+135
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394032 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# The browser demo's SQLite runtime is below 1 MiB. Keep it in ordinary Git so# the static Space is self-contained and reproducible without Git LFS tooling.assets/*.wasm -filter -diff -merge -textdist/assets/*.wasm -filter -diff -merge -text
6 unmodified lines789101112133 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071726 unmodified linesapp_file: dist/index.htmlpinned: falselicense: apache-2.0short_description: Typed queries and real TraceChain, entirely in your browser.tags:- teaql- sqlite3 unmodified lines# TeaQL Browser SQLite PlaygroundEdit a generated TypeScript Q query and inspect its data, facets and actual SQLexecution evidence. SQLite/WASM runs in a browser worker; there is no applicationbackend or server-side business database. Query data stays in your browser.The deterministic fixture contains four synthetic orders, twenty items and threestatuses. The default query demonstrates filtered pagination, named totals,status COUNT/SUM facets, status details and three-item previews with full counts.Switch the example, edit the query, or restore the preset. Peggy parses a controlledquery AST; it does not evaluate arbitrary JavaScript, imports or assignments.## Request TraceChainEach SQL record retains its root purpose, root comment, native Q-operation parentsand nested business comments. The browser only renders runtime `traceChain`;physical `tracePath` remains separate. For example:```textrender order list page: load order list → selectStatusWith(...) → load statusrender order list page: load order list → facetByStatusAs('statusCounts') → load status facets```The table displays `Time | Identity | Trace chain | SQL`. Time is recorded executionduration; Identity is the request entity, not an invented user or object ID. SQL isthe runtime's parameter-filled diagnostic text, with its masking policy intact.An explicit execution observer retains evidence even when diagnostic logging is off.## Storage and reproducibilityMemory is the default and resets on refresh. Audited generated mutation APIs seedthe data; Reset recreates it. OPFS is enabled only when the hosting origin providescross-origin isolation. When unavailable on Hugging Face, the option is disabledand memory mode remains fully usable.This demo uses a tested **unreleased request-tree runtime snapshot**, based onthe [TeaQL TypeScript repository](https://github.com/teaql/teaql-ts). Its packageversion remains 0.3.0; this is not a claim that published npm 0.3.0 contains the newTraceChain design. Exact source, model, generated library, packaged runtime andhashes are retained in [source](https://huggingface.co/spaces/teaql/browser-sqlite-playground/tree/main/source).```bashhf download teaql/browser-sqlite-playground --repo-type space --include 'source/**' --local-dir teaql-democd teaql-demo/source/browser-sqlitenpm cinpm run buildnpm run smokenpm run dev```The included browser test checks memory/OPFS, refresh/reset, logging modes, exactfacets/counts/previews, real TraceChain rows, query presets and rejected constructoraccess. This first profile does not implement multi-tab coordination or true streaming.Learn more at [teaql.io](https://teaql.io/).6 unmodified lines789101112133 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626 unmodified linesapp_file: dist/index.htmlpinned: falselicense: apache-2.0short_description: Business UI to generated Q, TraceChain and real SQLite SQL.tags:- teaql- sqlite3 unmodified lines# TeaQL Browser SQLite PlaygroundThis Space demonstrates an auditable chain from a recognizable order-managementinterface to generated TeaQL Q expressions, runtime TraceChain and the actual SQLexecuted by SQLite/WASM in the browser.The default page is the full order center. Its status cards, colors, order counts,order totals, rows, item previews and pagination are produced by one generated Qrequest whose search parameters change without changing the query shape. Resultscan be inspected as a table or a tree. The evidence table shows execution time,request identity, the runtime-provided TraceChain and executed SQL.Additional entry points are retained independently:- [`/orders.html`](./orders.html): generated Order model and request-tree conformance view.- [`/work-items.html`](./work-items.html): the earlier WorkItem browser SQLite example.All data is deterministic demo data and remains in the browser. Memory mode workseverywhere. OPFS is offered only when the hosting origin provides the requiredcross-origin isolation.## Reproduce the deployed buildThe exact runtime, tests, model, generated Order library and browser applicationsource are retained under [`source/teaql-ts`](./source/teaql-ts). They correspond toTeaQL TypeScript commit `e87b5d843a1bc2ae5f677f402b6b3177a7d40b50` on `main`.```bashcd source/teaql-tsnpm cinpm run buildnpm test -- --runInBand --silentcd examples/browser-sqlitenpm cinpm run buildnpm run smokenpm run smoke:orders```The validated runtime result was 56 passing suites and 604 passing tests, with sixtests skipped by the repository configuration. Both real-browser smoke suites pass.Learn more at [teaql.io](https://teaql.io/) and inspect the upstream source at[github.com/teaql/teaql-ts](https://github.com/teaql/teaql-ts).
1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10}body{margin:0}main{width:min(760px,calc(100% - 40px));margin:10vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button{border:0;border-radius:5px;padding:10px 14px;background:#d9ff52;font-weight:800}#status{color:#aab4c4}pre{min-height:260px;padding:22px;overflow:auto;border:1px solid #2b323e;border-radius:8px;background:#11151c;color:#c6d1df}.evidence-scroll{overflow-x:auto;margin:24px 0}.evidence-table{border-collapse:collapse;width:100%;text-align:left}.evidence-table th,.evidence-table td{padding:12px;border:1px solid #2b323e;vertical-align:top}.evidence-table td{white-space:pre-wrap;overflow-wrap:anywhere;min-width:110px}.evidence-table td:last-child{min-width:320px;font-family:monospace}1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10;color-scheme:dark}body{margin:0}main{width:min(1120px,calc(100% - 40px));margin:6vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button,select{border:0;border-radius:5px;padding:10px 14px;font:inherit;font-weight:700}button{background:#d9ff52;color:#111;cursor:pointer}button:disabled{cursor:wait;opacity:.55}select{background:#202630;color:#e8edf5}#status{color:#aab4c4}.query-panel,.response-panel{margin-top:22px;border:1px solid #2b323e;border-radius:10px;background:#11151c;overflow:hidden}.query-toolbar,.response-heading{display:flex;gap:12px;align-items:center;padding:14px 16px;border-bottom:1px solid #2b323e}.query-toolbar label{color:#aab4c4;font-size:13px;font-weight:800;text-transform:uppercase;letter-spacing:.08em}.query-toolbar .run{margin-left:auto;min-width:120px}textarea{box-sizing:border-box;width:100%;min-height:330px;resize:vertical;border:0;outline:0;padding:22px;background:#0c1016;color:#d9ff52;font:15px/1.65 ui-monospace,SFMono-Regular,Menlo,monospace;tab-size:2}.hint{margin:0;padding:10px 16px;border-top:1px solid #2b323e;color:#7f8a9a;font-size:13px}.response-heading{justify-content:space-between}.response-heading h2{margin:0;font-size:18px}.response-heading span{color:#8c98a8;font:12px ui-monospace,monospace}pre{box-sizing:border-box;min-height:360px;margin:0;padding:22px;overflow:auto;background:#11151c;color:#c6d1df;font-size:14px}@media(max-width:640px){main{width:min(100% - 24px,1120px);margin:24px auto}.controls,.query-toolbar{align-items:stretch;flex-direction:column}.query-toolbar .run{margin-left:0}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import{S as T,m as Te,a as ie,e as de,O as R,B as Qe,b as $e,R as Re,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-BBmdgl4H.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),_e=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ce={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},he=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(``,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),Me={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,o=n.status,s=d=>{const a=f[String(d)];return a===void 0?d:Number(a)};return o&&typeof o=="object"&&!Array.isArray(o)&&"$in"in o?n.status={$in:Array.isArray(o.$in)?o.$in.map(s):o.$in}:n.status=s(o),e}class D{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new T(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(``)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){this.ensureIntent();const r=this.service(e),n=this.toQuery(),o=await r.executeQuery(e.prepareQuery(n)),s=new ie(o);return n.facets.length&&(s.facets=await de(r,d=>e.prepareQuery(d),n,n.facets)),s}async executeForRows(e){return this.executeForList(e)}async executeForPage(e,r,n){this.ensureIntent();const o=this.service(e),s=this.toQuery(),d=await o.executeCount(s,this.pageTotalAlias,this.pageTotalAlias?{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}:void 0),a=this.toQuery().offset(r).limit(n),c=new ie(await o.executeQuery(e.prepareQuery(a)),{totalCount:d});return this.pageTotalAlias&&(c.aggregations[this.pageTotalAlias]=d),s.facets.length&&(c.facets=await de(o,m=>e.prepareQuery(m),s,s.facets)),{data:c,totalCount:d,offset:r,limit:n}}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends D{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends D{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new T("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends D{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends D{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class He extends D{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class Ve extends D{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class ue extends D{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),Me,{filter:(o,s)=>o==="status.code"?{status:{$inSubquery:{query:new T("OrderStatus").filter({code:s}),field:"id"}}}:o==="itemList.productName"?{id:{$inSubquery:{query:new T("OrderItem").filter({productName:s}),field:"orderId"}}}:{[o]:s},order:(o,s)=>s==="asc"?R.asc(o):R.desc(o)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new T("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const o=r.toQuery();return o.commentText||o.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>o},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.applyRowCount(),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForList(e)}executeForPage(e,r,n){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForPage(e,r,n)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new ue}static customerOrdersWithMinimalFields(){return new ue(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new He}static shipments(){return new Ve}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),b=document.querySelector("#result"),ge=document.querySelector("#result-title"),fe=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),le=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),$=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),me=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=document.querySelector("#view-tree"),Ae=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let i=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[i]??t}function O(t){return i==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let w="tree",v,Se=0,ee;const A={search:"",page:0,pageSize:4},Ce=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ce==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Ie(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(o=>o.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Ie(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=await r.executeForPage(t.context,A.page*A.pageSize,A.pageSize),o=n.data.facet("statusCounts")??[];return{orders:n.data,totalOrders:Number(n.data.aggregations.totalOrders??n.totalCount),filteredOrders:n.totalCount,statusFacets:o.map(s=>({code:te(s),name:String(s.name??""),color:String(s.color??""),orderCount:Number(s.orderCount??0),orderTotalAmount:Number(s.orderTotalAmount??0)})).filter(s=>s.code&&s.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:r.toQExpression("executeForPage(ctx, pageOffset, pageSize);")}}const we=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最��订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() .selectPlatformWith(Q.platforms().selectName()) .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) .selectStatusWith(Q.orderStatuses().selectName().selectColor()) .orderByOrderDateDescending() .orderByIdDescending() .limit(8) .comment('what: list recent commerce orders') .purpose('why: provide the default order overview') .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() .withOrderNumberIs('TQL-2026-1003') .selectPlatformWith(Q.platforms()) .selectCustomerWith(Q.customers()) .selectStatusWith(Q.orderStatuses().selectName().selectColor()) .selectItemListWith(Q.orderItems().orderByIdAscending()) .selectPaymentListWith(Q.payments().orderByIdAscending()) .selectShipmentListWith(Q.shipments().orderByIdAscending()) .limit(1) .comment('what: load one complete order graph') .purpose('why: inspect items, payment and fulfillment together') .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() .selectPlatformWith(Q.platforms().selectName()) .countOrderListAs('orderCount') .orderByNameAscending() .comment('what: list customers with related order counts') .purpose('why: compare customer activity at a glance') .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() .groupByCurrency().groupByStatus() .countAs('orderCount') .sumTotalAmountAs('grossAmount') .averageTotalAmountAs('averageOrderValue') .comment('what: aggregate orders by currency and status') .purpose('why: show the current order funnel') .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() .groupByProductName() .sumQuantityAs('units') .sumLineAmountAs('revenue') .comment('what: aggregate sold units and line revenue') .purpose('why: identify the strongest products in the demo data') .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() .groupByCurrency().groupByProvider().groupByStatus() .countAs('paymentCount').sumAmountAs('paymentAmount') .orderByCurrencyAscending().orderByProviderAscending() .comment('what: reconcile payment totals by provider') .purpose('why: compare captured, pending and refunded money') .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、���围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() .withStatusIsPendingPayment() .selectStatusWith(Q.orderStatuses().selectName().selectColor()) .selectCustomerWith(Q.customers().selectName()) .selectPaymentListWith(Q.payments()) .comment('what: find orders awaiting payment') .purpose('why: support payment follow-up') .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() .withPlatformIdIs('1') .withTotalAmountGreaterThanOrEqualTo(500) .selectCustomerWith(Q.customers().selectName().selectCity()) .orderByTotalAmountDescending() .comment('what: find high-value domestic orders') .purpose('why: prioritize valuable fulfillment work') .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() .withStatusIn('READY', 'IN_TRANSIT') .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) .orderByStatusAscending().orderByIdAscending() .comment('what: find shipments that are not delivered') .purpose('why: monitor active fulfillment') .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { "filter": { "currency": "CNY", "totalAmount": { "$gte": 250 }, "status": { "$in": ["PAID", "SHIPPED"] } }, "orderBy": [{ "field": "totalAmount", "direction": "desc" }]};const data = await Q.customerOrders() .filterByJson(input) .limit(20) .comment('what: execute a validated browser search') .purpose('why: demonstrate safe dynamic order discovery') .executeForList(ctx);`,run:t=>G(t,{filter:{currency:"CNY",totalAmount:{$gte:250},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { "filter": { "orderDate": { "$gte": "2026-09-15" } }, "orderBy": [{ "field": "orderDate", "direction": "asc" }]};const data = await Q.customerOrders() .filterByJson(input) .limit(20) .comment('what: execute a validated browser search') .purpose('why: demonstrate safe dynamic order discovery') .executeForList(ctx);`,run:t=>G(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { "filter": { "status": "DELIVERED", "internalNote": { "$contains": "not queryable" } }};const request = Q.customerOrders().filterByJson(input);const data = await request .limit(20) .comment('what: execute a validated browser search') .purpose('why: demonstrate safe dynamic order discovery') .executeForList(ctx);const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],pe=we.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ce},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new $e().enableSelect();r.install(new Re(ce,{},{constants:_e})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const o=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),s=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:o,review:(d,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(d=>({policy:d,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(s),await s.ensureSchema(),{client:r,context:s,evidence:n}}async function be(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const o=he.map(s=>n.request({entity:s.entity,action:"Create",id:s.id,payload:s.payload}));for(const s of o)t.client.preflightMutation(s);for(const s of o)await t.client.executeMutation(s)})}function dt(){F.replaceChildren();for(const t of we){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const o=document.createElement("p");o.textContent=O(t.description),r.append(n,o);const s=document.createElement("div");s.className="query-links";for(const d of t.queries){const a=document.createElement("a");a.href=`#${d.id}`,a.dataset.queryId=d.id,a.textContent=O(d.title),a.addEventListener("click",c=>{c.preventDefault(),W=d.id,history.replaceState(null,"",`#${d.id}`),V(),E&&P(d,E).catch(N)}),s.append(a)}e.append(r,s),F.append(e)}V()}function V(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function P(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),b.classList.add("loading"),b.setAttribute("aria-busy","true"),ge.textContent=O(t.title),fe.textContent=O(t.description),le.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Ie(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),b.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),$.textContent=t.view==="dashboard"?i==="en"?"Order management center":"订单管理中心":i==="en"?"Result tree":"结果树",J.textContent=i==="en"?"Running query…":"查询中…";try{const o=await t.run(e);t.view==="dashboard"&&(le.textContent=o.queryExpression),v={data:o,query:t,active:e},w=t.view==="dashboard"||Z(o)?"table":"tree",z();const s=Math.max(1,Math.round(performance.now()-r));Se=s,ee=n;const d=e.evidence.snapshot();Ee(d,n),Pe(o,t,s)}finally{b.classList.remove("loading"),b.removeAttribute("aria-busy")}}function Ee(t,e=ee){me.replaceChildren(),et.textContent=i==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const o=document.createElement("tr");o.className="evidence-row";const s=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),d=document.createElement("td");d.className="evidence-time",d.dataset.executedAt=e?.toISOString()??"",d.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const a=document.createElement("td");a.textContent=`${v?.query.id??"query"} · #${n+1} · ${s?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const h=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${h}`,o.append(d,a,c,m),me.append(o)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!v)return;const{data:t,query:e,active:r}=v,n=e.view==="dashboard"||Z(t);if(n||(w="tree"),Q.disabled=!n,Q.classList.toggle("active",w==="table"),H.classList.toggle("active",w==="tree"),Q.setAttribute("aria-pressed",String(w==="table")),H.setAttribute("aria-pressed",String(w==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",w!=="tree"),w==="table"&&e.view==="dashboard"){$.textContent=i==="en"?"Result table":"结果表格",mt(t,r,e);return}if(w==="table"&&Z(t)){$.textContent=i==="en"?"Result table":"结果表格",ut(t);return}$.textContent=i==="en"?"Result tree":"结果树",Le(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const a=document.createElement("p");a.className="result-table-empty",a.textContent=i==="en"?"The query returned no records.":"查询没有返回记录。",e.append(a),b.replaceChildren(e);return}const r=[...new Set(t.flatMap(a=>Object.keys(a)))],n=document.createElement("table");n.className="result-table";const o=document.createElement("thead"),s=document.createElement("tr");for(const a of r){const c=document.createElement("th");c.scope="col",c.textContent=a,s.append(c)}o.append(s);const d=document.createElement("tbody");for(const a of t){const c=document.createElement("tr");for(const m of r){const h=document.createElement("td");h.textContent=lt(a[m]),c.append(h)}d.append(c)}n.append(o,d),e.append(n),b.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return i==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return Ne(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?i==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const o=document.createElement("div");o.className="order-center-toolbar";const s=document.createElement("div"),d=document.createElement("h3");d.textContent=i==="en"?"Order Management Center":"订单管理中心";const a=document.createElement("p");a.textContent=i==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",s.append(d,a);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=i==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",i==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",i==="en"?"Run order query":"执行订单查询"),h.title=i==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),h.append(l),c.append(m,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=m.value.trim(),A.page=0,P(r,e).catch(N)}),o.append(s,c);const S=document.createElement("div");S.className="order-metrics",S.append(ye(i==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,P(r,e).catch(N)}));for(const p of t.statusFacets)S.append(ye(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,P(r,e).catch(N)},`${i==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const _=document.createElement("div");_.className="order-row order-row-head";const xe=i==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of xe){const x=document.createElement("span");x.textContent=p,_.append(x)}if(g.append(_),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=i==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const M=document.createElement("div");M.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=i==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const q=document.createElement("div");q.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));q.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p<ae;p+=1){const x=j(String(p+1),p,!1,e,r);x.classList.toggle("active",p===t.page),q.append(x)}q.append(j("›",t.page+1,t.page>=ae-1,e,r)),M.append(ne,q),n.append(o,S,g,M),b.replaceChildren(n)}function ye(t,e,r,n,o,s,d){const a=document.createElement("button");a.type="button",a.className=`metric-card metric-${r}`,n&&a.style.setProperty("--metric-color",n),a.classList.toggle("active",o);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),a.append(c,m),d){const h=document.createElement("small");h.textContent=d,a.append(h)}return a.addEventListener("click",s),a}function pt(t){return new Intl.NumberFormat(i==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const s=document.createElement("span"),d=document.createElement("span"),a=te(r);d.className=`status-badge status-${a.toLowerCase()}`,d.textContent=Ne(a)||String(r.name??a);const c=String(r.color??"");c&&(d.style.color=c,d.style.backgroundColor=`${c}18`),s.append(d),e.append(s);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const l=document.createElement("small");l.textContent=`+${h}`,m.append(l)}return e.append(m),e}function j(t,e,r,n,o){const s=document.createElement("button");return s.type="button",s.textContent=t,s.disabled=r,s.addEventListener("click",()=>{A.page=e,P(o,n).catch(N)}),s}function Ne(t){return(i==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Le(t){b.replaceChildren(Oe(t,"result",0))}function Oe(t,e,r){if(t!==null&&typeof t=="object"){const d=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),a=document.createElement("details");a.className="tree-branch",a.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,d.length),c.append(m,h),a.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of d)l.append(Oe(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return a.append(l),a}const n=document.createElement("div");n.className="tree-leaf";const o=document.createElement("span");o.className="tree-key",o.textContent=e;const s=document.createElement("span");return s.className=`tree-value tree-${t===null?"null":typeof t}`,s.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(o,s),n}function ht(t,e){if(Array.isArray(t))return i==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):i==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Pe(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),o=i==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${o} · ${r} ms · ${i==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function De(t){const e=he.filter(r=>r.entity==="CustomerOrder").length;k.textContent=i==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=i==="en"?"en":"zh-CN",document.title=i==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=i==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),Ae.forEach(e=>{const r=e.dataset.locale===i;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",i==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",i==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",i==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",i==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",i==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",i==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",i==="en"?"Result tree actions":"结果树操作"),dt(),v){const{data:e,query:r,active:n}=v;ge.textContent=O(r.title),fe.textContent=O(r.description),z(),Ee(n.evidence.snapshot(),ee),Pe(e,r,Se),De(B.checked?"opfs":"memory")}else k.textContent=i==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return pe.find(t=>t.id===W)??pe[0]}async function qe(t){k.textContent=i==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await be(r),await P(re(),r),De(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),qe(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await be(E),await P(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{b.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(w="table",z())});H.addEventListener("click",()=>{w="tree",z()});tt.addEventListener("click",()=>{b.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});Ae.forEach(t=>{t.addEventListener("click",()=>{i=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",i),ve()})});function N(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=i==="en"?"Query failed":"查询失败",Le({error:e.name,message:e.message})}ve();W=re().id;V();qe(Ce).catch(N);1import{f as u}from"./dynamic-search-BBmdgl4H.js";const i=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class V{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(s,e){this.traces.set(i(s),{key:Object.freeze({...s}),nodes:u(e)})}traceChain(s){return this.traces.get(i(s))?.nodes}set(s,e,t){if(!e.trim())throw new TypeError("field is required");const r=i(s),a=this.changes.get(r)??{key:Object.freeze({...s}),values:{}};a.values[e]=t,this.changes.set(r,a)}snapshot(){return[...this.changes.values()].map(s=>({key:Object.freeze({...s.key}),values:Object.freeze({...s.values})}))}change(s){return Object.freeze({...this.changes.get(i(s))?.values??{}})}mergeFrom(s){if(s!==this){for(const e of s.snapshotVersions())this.requireMatchingVersion(e.key,e.version);for(const e of s.snapshot())for(const[t,r]of Object.entries(e.values))this.set(e.key,t,r);for(const e of s.newKeys.values())this.markAsNew(e);for(const e of s.deletedKeys.values())this.markAsDeleted(e);for(const e of s.snapshotVersions())this.setOriginalVersion(e.key,e.version);for(const e of s.traces.values())this.setTraceChain(e.key,e.nodes)}}mergeEntityFrom(s,e){if(s===this)return;const t=s.originalVersion(e);t!==void 0&&this.requireMatchingVersion(e,t);for(const[a,c]of Object.entries(s.change(e)))this.set(e,a,c);s.isNew(e)&&this.markAsNew(e),s.isDeleted(e)&&this.markAsDeleted(e),t!==void 0&&this.setOriginalVersion(e,t);const r=s.traceChain(e);r&&this.setTraceChain(e,r)}hasPending(s){const e=i(s);return this.newKeys.has(e)||this.deletedKeys.has(e)||Object.keys(this.changes.get(e)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(s,e){const t=i(s),r=i(e);if(t===r)return;const a=this.originalVersion(s);a!==void 0&&this.requireMatchingVersion(e,a);const c=this.changes.get(t);if(c){this.changes.delete(t);for(const[f,g]of Object.entries(c.values))this.set(e,f,g)}const h=this.originalVersions.get(t);h!==void 0&&(this.originalVersions.delete(t),this.originalVersions.set(r,{key:Object.freeze({...e}),version:h.version})),this.newKeys.delete(t)&&this.newKeys.set(r,Object.freeze({...e})),this.deletedKeys.delete(t)&&this.deletedKeys.set(r,Object.freeze({...e}));const l=this.traces.get(t);l&&(this.traces.delete(t),this.setTraceChain(e,l.nodes))}clearEntity(s){const e=i(s);this.changes.delete(e),this.newKeys.delete(e),this.deletedKeys.delete(e),this.traces.delete(e)}requireMatchingVersion(s,e){const t=this.originalVersion(s);if(t!==void 0&&t!==e)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(s,e){this.requireMatchingVersion(s,e),this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}acceptCommittedVersion(s,e){if(this.hasPending(s))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}originalVersion(s){return this.originalVersions.get(i(s))?.version}markAsNew(s){this.newKeys.set(i(s),Object.freeze({...s}))}isNew(s){return this.newKeys.has(i(s))}markAsDeleted(s){const e=i(s);this.changes.delete(e),this.deletedKeys.set(e,Object.freeze({...s}))}isDeleted(s){return this.deletedKeys.has(i(s))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}function d(n){const s=n.split("_");return s[0]+s.slice(1).map(e=>e?e[0].toUpperCase()+e.slice(1):"").join("")}function p(n,s){if(s==="snake_case")return n;const e=d(n);return s==="camelCase"||!e?e:e[0].toUpperCase()+e.slice(1)}function m(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class o{constructor(s){this.segments=s}static root(){return new o([])}static property(s){return o.root().property(s)}property(s){return new o([...this.segments,{kind:"property",name:s}])}index(s){return new o([...this.segments,{kind:"index",index:s}])}prefixedBy(s){return new o([...s.segments,...this.segments])}modelPath(){return this.render(s=>s)}nativePath(){return this.render(d)}instancePath(s="camelCase"){return this.segments.map(e=>e.kind==="index"?String(e.index):m(p(e.name,s))).map(e=>`/${e}`).join("")}toString(){return this.nativePath()}render(s){let e="";for(const t of this.segments)t.kind==="index"?e+=`[${t.index}]`:e+=`${e?".":""}${s(t.name)}`;return e}}export{V as E,o as O};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-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}}1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10}body{margin:0}main{width:min(760px,calc(100% - 40px));margin:10vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button{border:0;border-radius:5px;padding:10px 14px;background:#d9ff52;font-weight:800}#status{color:#aab4c4}pre{min-height:260px;padding:22px;overflow:auto;border:1px solid #2b323e;border-radius:8px;background:#11151c;color:#c6d1df}1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10}body{margin:0}main{width:min(760px,calc(100% - 40px));margin:10vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}a{color:#d9ff52}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button{border:0;border-radius:5px;padding:10px 14px;background:#d9ff52;font-weight:800}#status{color:#aab4c4}pre{min-height:260px;padding:22px;overflow:auto;border:1px solid #2b323e;border-radius:8px;background:#11151c;color:#c6d1df}
1import{S as G,L as c,M as k,C as v,a as I,d as O,e as C,Q as K,R as U,B as z,U as H,D as J,c as Y}from"./dynamic-search-BBmdgl4H.js";import{E as $,O as g}from"./object-location-xgYMemK6.js";class L extends G{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",s=!0,a){return super.relationQuery(t,e,i,r,s,a)}}class m{static teaqlTemporaryId=0;id;title;description;platform;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const i={...t};Object.assign(this,i),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof y?t.platform:y.fromRecord(t.platform),this.markLoaded("platform"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=new m(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new m({id:String(t)})}static teaqlBootstrapNew(t){return new m().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new v([{ruleId:"invalid_type",location:g.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n),n.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"WorkItem",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);for(const[S,f]of Object.entries(n.payload))S!=="id"&&S!=="version"&&this._root.set(this.teaqlEntityKey(),S,f);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();return this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update"),d.scopeFor(p),e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}class y{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--y.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:t?.id?I.empty():new I,writable:!0,enumerable:!1}),t){const i={...t};if(delete i.workItemList,Object.assign(this,i),Array.isArray(t.workItemList)){const r=t.workItemList;this._workItemList=new I(r.map(s=>s instanceof m?s:m.fromRecord(s)),{totalCount:r.totalCount,aggregations:r.aggregations,summary:r.summary,facets:r.facets,isLoaded:r.isLoaded??!0}),this.markLoaded("workItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._workItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const i=new y(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new y({id:String(t)})}static teaqlBootstrapNew(t){return new y().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(h=>!this.isLoaded(h.member));if(u)throw new v([{ruleId:"invalid_type",location:g.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n);const d=n.scopeFor(this.teaqlEntityKey());for(const[u,h]of this._workItemList.entries()){h.teaqlAttachRoot(this._root);const l=h.platform;(this.id===void 0||!h.isLoaded("platform")||(typeof l=="object"&&l!==null?l.id:l)!==this.id)&&h.updatePlatform(this);try{h.teaqlPreflightGraph(t,e,i,d)}catch(p){if(!(p instanceof v))throw p;const S=g.property("work_item_list").index(u);throw new v(p.violations.map(f=>({...f,location:f.location.prefixedBy(S)})))}}}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"Platform",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=d.scopeFor(this.teaqlEntityKey());for(const[q,w]of this._workItemList.entries()){w.teaqlAttachRoot(this._root);const _=w.platform;(this.id===void 0||!w.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&w.updatePlatform(this);try{await w.teaqlSaveWithinGraph(t,e,i,f)}catch(N){if(!(N instanceof v))throw N;const P=g.property("work_item_list").index(q);throw new v(N.violations.map(B=>({...B,location:B.location.prefixedBy(P)})))}}return this}const u=await e.executeMutation(d);for(const[f,q]of Object.entries(n.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,q);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update");const S=d.scopeFor(p);for(const[f,q]of this._workItemList.entries()){q.teaqlAttachRoot(this._root);const w=q.platform;(this.id===void 0||!q.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,i,S)}catch(_){if(!(_ instanceof v))throw _;const N=g.property("work_item_list").index(f);throw new v(_.violations.map(P=>({...P,location:P.location.prefixedBy(N)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const D=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class A{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new X(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({toQuery:()=>new L("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({toQuery:()=>new L("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new L("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof y?n:y.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof y?l:y.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof y?n:y.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class X{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new y}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class x{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Z(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title"),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof m?n:m.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof m?l:m.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof m?n:m.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class Z{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new m}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class R{static platforms(){return new A(!1)}static platformsWithMinimalFields(){return new A(!0)}static workItems(){return new x(!1)}static workItemsWithMinimalFields(){return new x(!0)}}const tt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function et(o){let t=(await R.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(o))[0];t||(t=y.teaqlBootstrapNew("1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(o)),o.withActiveRoot({entity:"Platform",id:t.id})}const it=new U(tt,{Platform:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:g.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:g.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:g.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:g.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:g.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:g.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:g.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:et}),rt={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},F=document.querySelector("#status"),st=document.querySelector("#result"),T=document.querySelector("#persist"),E=document.querySelector("#reset");let b;const M=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";T.checked=M==="opfs";async function nt(o){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await z.open(t,{...rt},{storage:o,databaseName:"teaql-browser-example.sqlite3"});e.install(it);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new H().insertResource("dataService",e).withMutationPolicyRegistry(new J(()=>({identity:i,review:(s,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Y(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Q({context:o}){if(!(await R.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(o)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await new m().updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(o)}async function V(o){const t=await R.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(o.context);st.textContent=JSON.stringify(t,null,2),F.textContent=`${o.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function j(o){F.textContent=`Opening ${o.toUpperCase()} SQLite/WASM…`;const t=b;b=void 0,await t?.client.close();const e=await nt(o);b=e,await Q(e),await V(e)}T.addEventListener("change",()=>{const o=T.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",o),j(o).catch(W)});E.addEventListener("click",async()=>{if(b){E.disabled=!0;try{await b.client.reset(b.context),await Q(b),await V(b)}catch(o){W(o)}finally{E.disabled=!1}}});function W(o){const t=o instanceof Error?o:new Error(String(o));F.textContent=`${t.name}: ${t.message}`}j(M).catch(W);1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10}body{margin:0}main{width:min(760px,calc(100% - 40px));margin:10vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button{border:0;border-radius:5px;padding:10px 14px;background:#d9ff52;font-weight:800}#status{color:#aab4c4}pre{min-height:260px;padding:22px;overflow:auto;border:1px solid #2b323e;border-radius:8px;background:#11151c;color:#c6d1df}.evidence-scroll{overflow-x:auto;margin:24px 0}.evidence-table{border-collapse:collapse;width:100%;text-align:left}.evidence-table th,.evidence-table td{padding:12px;border:1px solid #2b323e;vertical-align:top}.evidence-table td{white-space:pre-wrap;overflow-wrap:anywhere;min-width:110px}.evidence-table td:last-child{min-width:320px;font-family:monospace}1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10;color-scheme:dark}body{margin:0}main{width:min(1120px,calc(100% - 40px));margin:6vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button,select{border:0;border-radius:5px;padding:10px 14px;font:inherit;font-weight:700}button{background:#d9ff52;color:#111;cursor:pointer}button:disabled{cursor:wait;opacity:.55}select{background:#202630;color:#e8edf5}#status{color:#aab4c4}.query-panel,.response-panel{margin-top:22px;border:1px solid #2b323e;border-radius:10px;background:#11151c;overflow:hidden}.query-toolbar,.response-heading{display:flex;gap:12px;align-items:center;padding:14px 16px;border-bottom:1px solid #2b323e}.query-toolbar label{color:#aab4c4;font-size:13px;font-weight:800;text-transform:uppercase;letter-spacing:.08em}.query-toolbar .run{margin-left:auto;min-width:120px}textarea{box-sizing:border-box;width:100%;min-height:330px;resize:vertical;border:0;outline:0;padding:22px;background:#0c1016;color:#d9ff52;font:15px/1.65 ui-monospace,SFMono-Regular,Menlo,monospace;tab-size:2}.hint{margin:0;padding:10px 16px;border-top:1px solid #2b323e;color:#7f8a9a;font-size:13px}.response-heading{justify-content:space-between}.response-heading h2{margin:0;font-size:18px}.response-heading span{color:#8c98a8;font:12px ui-monospace,monospace}pre{box-sizing:border-box;min-height:360px;margin:0;padding:22px;overflow:auto;background:#11151c;color:#c6d1df;font-size:14px}@media(max-width:640px){main{width:min(100% - 24px,1120px);margin:24px auto}.controls,.query-toolbar{align-items:stretch;flex-direction:column}.query-toolbar .run{margin-left:0}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import{S as T,m as Te,a as ie,e as de,O as R,B as Qe,b as $e,R as Re,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-BBmdgl4H.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),_e=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ce={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},he=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(``,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),Me={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,o=n.status,s=d=>{const a=f[String(d)];return a===void 0?d:Number(a)};return o&&typeof o=="object"&&!Array.isArray(o)&&"$in"in o?n.status={$in:Array.isArray(o.$in)?o.$in.map(s):o.$in}:n.status=s(o),e}class D{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new T(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(``)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){this.ensureIntent();const r=this.service(e),n=this.toQuery(),o=await r.executeQuery(e.prepareQuery(n)),s=new ie(o);return n.facets.length&&(s.facets=await de(r,d=>e.prepareQuery(d),n,n.facets)),s}async executeForRows(e){return this.executeForList(e)}async executeForPage(e,r,n){this.ensureIntent();const o=this.service(e),s=this.toQuery(),d=await o.executeCount(s,this.pageTotalAlias,this.pageTotalAlias?{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}:void 0),a=this.toQuery().offset(r).limit(n),c=new ie(await o.executeQuery(e.prepareQuery(a)),{totalCount:d});return this.pageTotalAlias&&(c.aggregations[this.pageTotalAlias]=d),s.facets.length&&(c.facets=await de(o,m=>e.prepareQuery(m),s,s.facets)),{data:c,totalCount:d,offset:r,limit:n}}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends D{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends D{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new T("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends D{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends D{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class He extends D{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class Ve extends D{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class ue extends D{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),Me,{filter:(o,s)=>o==="status.code"?{status:{$inSubquery:{query:new T("OrderStatus").filter({code:s}),field:"id"}}}:o==="itemList.productName"?{id:{$inSubquery:{query:new T("OrderItem").filter({productName:s}),field:"orderId"}}}:{[o]:s},order:(o,s)=>s==="asc"?R.asc(o):R.desc(o)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new T("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const o=r.toQuery();return o.commentText||o.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>o},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.applyRowCount(),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForList(e)}executeForPage(e,r,n){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForPage(e,r,n)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new ue}static customerOrdersWithMinimalFields(){return new ue(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new He}static shipments(){return new Ve}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),b=document.querySelector("#result"),ge=document.querySelector("#result-title"),fe=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),le=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),$=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),me=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=document.querySelector("#view-tree"),Ae=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let i=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[i]??t}function O(t){return i==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let w="tree",v,Se=0,ee;const A={search:"",page:0,pageSize:4},Ce=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ce==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Ie(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(o=>o.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Ie(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=await r.executeForPage(t.context,A.page*A.pageSize,A.pageSize),o=n.data.facet("statusCounts")??[];return{orders:n.data,totalOrders:Number(n.data.aggregations.totalOrders??n.totalCount),filteredOrders:n.totalCount,statusFacets:o.map(s=>({code:te(s),name:String(s.name??""),color:String(s.color??""),orderCount:Number(s.orderCount??0),orderTotalAmount:Number(s.orderTotalAmount??0)})).filter(s=>s.code&&s.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:r.toQExpression("executeForPage(ctx, pageOffset, pageSize);")}}const we=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最��订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() .selectPlatformWith(Q.platforms().selectName()) .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) .selectStatusWith(Q.orderStatuses().selectName().selectColor()) .orderByOrderDateDescending() .orderByIdDescending() .limit(8) .comment('what: list recent commerce orders') .purpose('why: provide the default order overview') .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() .withOrderNumberIs('TQL-2026-1003') .selectPlatformWith(Q.platforms()) .selectCustomerWith(Q.customers()) .selectStatusWith(Q.orderStatuses().selectName().selectColor()) .selectItemListWith(Q.orderItems().orderByIdAscending()) .selectPaymentListWith(Q.payments().orderByIdAscending()) .selectShipmentListWith(Q.shipments().orderByIdAscending()) .limit(1) .comment('what: load one complete order graph') .purpose('why: inspect items, payment and fulfillment together') .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() .selectPlatformWith(Q.platforms().selectName()) .countOrderListAs('orderCount') .orderByNameAscending() .comment('what: list customers with related order counts') .purpose('why: compare customer activity at a glance') .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() .groupByCurrency().groupByStatus() .countAs('orderCount') .sumTotalAmountAs('grossAmount') .averageTotalAmountAs('averageOrderValue') .comment('what: aggregate orders by currency and status') .purpose('why: show the current order funnel') .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() .groupByProductName() .sumQuantityAs('units') .sumLineAmountAs('revenue') .comment('what: aggregate sold units and line revenue') .purpose('why: identify the strongest products in the demo data') .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() .groupByCurrency().groupByProvider().groupByStatus() .countAs('paymentCount').sumAmountAs('paymentAmount') .orderByCurrencyAscending().orderByProviderAscending() .comment('what: reconcile payment totals by provider') .purpose('why: compare captured, pending and refunded money') .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、���围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() .withStatusIsPendingPayment() .selectStatusWith(Q.orderStatuses().selectName().selectColor()) .selectCustomerWith(Q.customers().selectName()) .selectPaymentListWith(Q.payments()) .comment('what: find orders awaiting payment') .purpose('why: support payment follow-up') .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() .withPlatformIdIs('1') .withTotalAmountGreaterThanOrEqualTo(500) .selectCustomerWith(Q.customers().selectName().selectCity()) .orderByTotalAmountDescending() .comment('what: find high-value domestic orders') .purpose('why: prioritize valuable fulfillment work') .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() .withStatusIn('READY', 'IN_TRANSIT') .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) .orderByStatusAscending().orderByIdAscending() .comment('what: find shipments that are not delivered') .purpose('why: monitor active fulfillment') .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { "filter": { "currency": "CNY", "totalAmount": { "$gte": 250 }, "status": { "$in": ["PAID", "SHIPPED"] } }, "orderBy": [{ "field": "totalAmount", "direction": "desc" }]};const data = await Q.customerOrders() .filterByJson(input) .limit(20) .comment('what: execute a validated browser search') .purpose('why: demonstrate safe dynamic order discovery') .executeForList(ctx);`,run:t=>G(t,{filter:{currency:"CNY",totalAmount:{$gte:250},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { "filter": { "orderDate": { "$gte": "2026-09-15" } }, "orderBy": [{ "field": "orderDate", "direction": "asc" }]};const data = await Q.customerOrders() .filterByJson(input) .limit(20) .comment('what: execute a validated browser search') .purpose('why: demonstrate safe dynamic order discovery') .executeForList(ctx);`,run:t=>G(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { "filter": { "status": "DELIVERED", "internalNote": { "$contains": "not queryable" } }};const request = Q.customerOrders().filterByJson(input);const data = await request .limit(20) .comment('what: execute a validated browser search') .purpose('why: demonstrate safe dynamic order discovery') .executeForList(ctx);const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],pe=we.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ce},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new $e().enableSelect();r.install(new Re(ce,{},{constants:_e})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const o=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),s=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:o,review:(d,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(d=>({policy:d,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(s),await s.ensureSchema(),{client:r,context:s,evidence:n}}async function be(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const o=he.map(s=>n.request({entity:s.entity,action:"Create",id:s.id,payload:s.payload}));for(const s of o)t.client.preflightMutation(s);for(const s of o)await t.client.executeMutation(s)})}function dt(){F.replaceChildren();for(const t of we){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const o=document.createElement("p");o.textContent=O(t.description),r.append(n,o);const s=document.createElement("div");s.className="query-links";for(const d of t.queries){const a=document.createElement("a");a.href=`#${d.id}`,a.dataset.queryId=d.id,a.textContent=O(d.title),a.addEventListener("click",c=>{c.preventDefault(),W=d.id,history.replaceState(null,"",`#${d.id}`),V(),E&&P(d,E).catch(N)}),s.append(a)}e.append(r,s),F.append(e)}V()}function V(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function P(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),b.classList.add("loading"),b.setAttribute("aria-busy","true"),ge.textContent=O(t.title),fe.textContent=O(t.description),le.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Ie(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),b.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),$.textContent=t.view==="dashboard"?i==="en"?"Order management center":"订单管理中心":i==="en"?"Result tree":"结果树",J.textContent=i==="en"?"Running query…":"查询中…";try{const o=await t.run(e);t.view==="dashboard"&&(le.textContent=o.queryExpression),v={data:o,query:t,active:e},w=t.view==="dashboard"||Z(o)?"table":"tree",z();const s=Math.max(1,Math.round(performance.now()-r));Se=s,ee=n;const d=e.evidence.snapshot();Ee(d,n),Pe(o,t,s)}finally{b.classList.remove("loading"),b.removeAttribute("aria-busy")}}function Ee(t,e=ee){me.replaceChildren(),et.textContent=i==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const o=document.createElement("tr");o.className="evidence-row";const s=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),d=document.createElement("td");d.className="evidence-time",d.dataset.executedAt=e?.toISOString()??"",d.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const a=document.createElement("td");a.textContent=`${v?.query.id??"query"} · #${n+1} · ${s?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const h=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${h}`,o.append(d,a,c,m),me.append(o)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!v)return;const{data:t,query:e,active:r}=v,n=e.view==="dashboard"||Z(t);if(n||(w="tree"),Q.disabled=!n,Q.classList.toggle("active",w==="table"),H.classList.toggle("active",w==="tree"),Q.setAttribute("aria-pressed",String(w==="table")),H.setAttribute("aria-pressed",String(w==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",w!=="tree"),w==="table"&&e.view==="dashboard"){$.textContent=i==="en"?"Result table":"结果表格",mt(t,r,e);return}if(w==="table"&&Z(t)){$.textContent=i==="en"?"Result table":"结果表格",ut(t);return}$.textContent=i==="en"?"Result tree":"结果树",Le(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const a=document.createElement("p");a.className="result-table-empty",a.textContent=i==="en"?"The query returned no records.":"查询没有返回记录。",e.append(a),b.replaceChildren(e);return}const r=[...new Set(t.flatMap(a=>Object.keys(a)))],n=document.createElement("table");n.className="result-table";const o=document.createElement("thead"),s=document.createElement("tr");for(const a of r){const c=document.createElement("th");c.scope="col",c.textContent=a,s.append(c)}o.append(s);const d=document.createElement("tbody");for(const a of t){const c=document.createElement("tr");for(const m of r){const h=document.createElement("td");h.textContent=lt(a[m]),c.append(h)}d.append(c)}n.append(o,d),e.append(n),b.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return i==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return Ne(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?i==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const o=document.createElement("div");o.className="order-center-toolbar";const s=document.createElement("div"),d=document.createElement("h3");d.textContent=i==="en"?"Order Management Center":"订单管理中心";const a=document.createElement("p");a.textContent=i==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",s.append(d,a);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=i==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",i==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",i==="en"?"Run order query":"执行订单查询"),h.title=i==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),h.append(l),c.append(m,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=m.value.trim(),A.page=0,P(r,e).catch(N)}),o.append(s,c);const S=document.createElement("div");S.className="order-metrics",S.append(ye(i==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,P(r,e).catch(N)}));for(const p of t.statusFacets)S.append(ye(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,P(r,e).catch(N)},`${i==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const _=document.createElement("div");_.className="order-row order-row-head";const xe=i==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of xe){const x=document.createElement("span");x.textContent=p,_.append(x)}if(g.append(_),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=i==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const M=document.createElement("div");M.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=i==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const q=document.createElement("div");q.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));q.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p<ae;p+=1){const x=j(String(p+1),p,!1,e,r);x.classList.toggle("active",p===t.page),q.append(x)}q.append(j("›",t.page+1,t.page>=ae-1,e,r)),M.append(ne,q),n.append(o,S,g,M),b.replaceChildren(n)}function ye(t,e,r,n,o,s,d){const a=document.createElement("button");a.type="button",a.className=`metric-card metric-${r}`,n&&a.style.setProperty("--metric-color",n),a.classList.toggle("active",o);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),a.append(c,m),d){const h=document.createElement("small");h.textContent=d,a.append(h)}return a.addEventListener("click",s),a}function pt(t){return new Intl.NumberFormat(i==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const s=document.createElement("span"),d=document.createElement("span"),a=te(r);d.className=`status-badge status-${a.toLowerCase()}`,d.textContent=Ne(a)||String(r.name??a);const c=String(r.color??"");c&&(d.style.color=c,d.style.backgroundColor=`${c}18`),s.append(d),e.append(s);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const l=document.createElement("small");l.textContent=`+${h}`,m.append(l)}return e.append(m),e}function j(t,e,r,n,o){const s=document.createElement("button");return s.type="button",s.textContent=t,s.disabled=r,s.addEventListener("click",()=>{A.page=e,P(o,n).catch(N)}),s}function Ne(t){return(i==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Le(t){b.replaceChildren(Oe(t,"result",0))}function Oe(t,e,r){if(t!==null&&typeof t=="object"){const d=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),a=document.createElement("details");a.className="tree-branch",a.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,d.length),c.append(m,h),a.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of d)l.append(Oe(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return a.append(l),a}const n=document.createElement("div");n.className="tree-leaf";const o=document.createElement("span");o.className="tree-key",o.textContent=e;const s=document.createElement("span");return s.className=`tree-value tree-${t===null?"null":typeof t}`,s.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(o,s),n}function ht(t,e){if(Array.isArray(t))return i==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):i==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Pe(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),o=i==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${o} · ${r} ms · ${i==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function De(t){const e=he.filter(r=>r.entity==="CustomerOrder").length;k.textContent=i==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=i==="en"?"en":"zh-CN",document.title=i==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=i==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),Ae.forEach(e=>{const r=e.dataset.locale===i;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",i==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",i==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",i==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",i==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",i==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",i==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",i==="en"?"Result tree actions":"结果树操作"),dt(),v){const{data:e,query:r,active:n}=v;ge.textContent=O(r.title),fe.textContent=O(r.description),z(),Ee(n.evidence.snapshot(),ee),Pe(e,r,Se),De(B.checked?"opfs":"memory")}else k.textContent=i==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return pe.find(t=>t.id===W)??pe[0]}async function qe(t){k.textContent=i==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await be(r),await P(re(),r),De(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),qe(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await be(E),await P(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{b.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(w="table",z())});H.addEventListener("click",()=>{w="tree",z()});tt.addEventListener("click",()=>{b.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});Ae.forEach(t=>{t.addEventListener("click",()=>{i=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",i),ve()})});function N(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=i==="en"?"Query failed":"查询失败",Le({error:e.name,message:e.message})}ve();W=re().id;V();qe(Ce).catch(N);1import{f as u}from"./dynamic-search-BBmdgl4H.js";const i=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class V{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(s,e){this.traces.set(i(s),{key:Object.freeze({...s}),nodes:u(e)})}traceChain(s){return this.traces.get(i(s))?.nodes}set(s,e,t){if(!e.trim())throw new TypeError("field is required");const r=i(s),a=this.changes.get(r)??{key:Object.freeze({...s}),values:{}};a.values[e]=t,this.changes.set(r,a)}snapshot(){return[...this.changes.values()].map(s=>({key:Object.freeze({...s.key}),values:Object.freeze({...s.values})}))}change(s){return Object.freeze({...this.changes.get(i(s))?.values??{}})}mergeFrom(s){if(s!==this){for(const e of s.snapshotVersions())this.requireMatchingVersion(e.key,e.version);for(const e of s.snapshot())for(const[t,r]of Object.entries(e.values))this.set(e.key,t,r);for(const e of s.newKeys.values())this.markAsNew(e);for(const e of s.deletedKeys.values())this.markAsDeleted(e);for(const e of s.snapshotVersions())this.setOriginalVersion(e.key,e.version);for(const e of s.traces.values())this.setTraceChain(e.key,e.nodes)}}mergeEntityFrom(s,e){if(s===this)return;const t=s.originalVersion(e);t!==void 0&&this.requireMatchingVersion(e,t);for(const[a,c]of Object.entries(s.change(e)))this.set(e,a,c);s.isNew(e)&&this.markAsNew(e),s.isDeleted(e)&&this.markAsDeleted(e),t!==void 0&&this.setOriginalVersion(e,t);const r=s.traceChain(e);r&&this.setTraceChain(e,r)}hasPending(s){const e=i(s);return this.newKeys.has(e)||this.deletedKeys.has(e)||Object.keys(this.changes.get(e)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(s,e){const t=i(s),r=i(e);if(t===r)return;const a=this.originalVersion(s);a!==void 0&&this.requireMatchingVersion(e,a);const c=this.changes.get(t);if(c){this.changes.delete(t);for(const[f,g]of Object.entries(c.values))this.set(e,f,g)}const h=this.originalVersions.get(t);h!==void 0&&(this.originalVersions.delete(t),this.originalVersions.set(r,{key:Object.freeze({...e}),version:h.version})),this.newKeys.delete(t)&&this.newKeys.set(r,Object.freeze({...e})),this.deletedKeys.delete(t)&&this.deletedKeys.set(r,Object.freeze({...e}));const l=this.traces.get(t);l&&(this.traces.delete(t),this.setTraceChain(e,l.nodes))}clearEntity(s){const e=i(s);this.changes.delete(e),this.newKeys.delete(e),this.deletedKeys.delete(e),this.traces.delete(e)}requireMatchingVersion(s,e){const t=this.originalVersion(s);if(t!==void 0&&t!==e)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(s,e){this.requireMatchingVersion(s,e),this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}acceptCommittedVersion(s,e){if(this.hasPending(s))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(i(s),{key:Object.freeze({...s}),version:e})}originalVersion(s){return this.originalVersions.get(i(s))?.version}markAsNew(s){this.newKeys.set(i(s),Object.freeze({...s}))}isNew(s){return this.newKeys.has(i(s))}markAsDeleted(s){const e=i(s);this.changes.delete(e),this.deletedKeys.set(e,Object.freeze({...s}))}isDeleted(s){return this.deletedKeys.has(i(s))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}function d(n){const s=n.split("_");return s[0]+s.slice(1).map(e=>e?e[0].toUpperCase()+e.slice(1):"").join("")}function p(n,s){if(s==="snake_case")return n;const e=d(n);return s==="camelCase"||!e?e:e[0].toUpperCase()+e.slice(1)}function m(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class o{constructor(s){this.segments=s}static root(){return new o([])}static property(s){return o.root().property(s)}property(s){return new o([...this.segments,{kind:"property",name:s}])}index(s){return new o([...this.segments,{kind:"index",index:s}])}prefixedBy(s){return new o([...s.segments,...this.segments])}modelPath(){return this.render(s=>s)}nativePath(){return this.render(d)}instancePath(s="camelCase"){return this.segments.map(e=>e.kind==="index"?String(e.index):m(p(e.name,s))).map(e=>`/${e}`).join("")}toString(){return this.nativePath()}render(s){let e="";for(const t of this.segments)t.kind==="index"?e+=`[${t.index}]`:e+=`${e?".":""}${s(t.name)}`;return e}}export{V as E,o as O};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-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}}1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10}body{margin:0}main{width:min(760px,calc(100% - 40px));margin:10vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button{border:0;border-radius:5px;padding:10px 14px;background:#d9ff52;font-weight:800}#status{color:#aab4c4}pre{min-height:260px;padding:22px;overflow:auto;border:1px solid #2b323e;border-radius:8px;background:#11151c;color:#c6d1df}1:root{font:16px/1.5 Inter,system-ui,sans-serif;color:#e8edf5;background:#090b10}body{margin:0}main{width:min(760px,calc(100% - 40px));margin:10vh auto}.eyebrow{color:#d9ff52;font-size:12px;font-weight:800;letter-spacing:.16em}h1{margin:8px 0;font-size:clamp(36px,7vw,68px);letter-spacing:-.05em}a{color:#d9ff52}.controls{display:flex;gap:18px;align-items:center;margin:32px 0}button{border:0;border-radius:5px;padding:10px 14px;background:#d9ff52;font-weight:800}#status{color:#aab4c4}pre{min-height:260px;padding:22px;overflow:auto;border:1px solid #2b323e;border-radius:8px;background:#11151c;color:#c6d1df}
1import{S as G,L as c,M as k,C as v,a as I,d as O,e as C,Q as K,R as U,B as z,U as H,D as J,c as Y}from"./dynamic-search-BBmdgl4H.js";import{E as $,O as g}from"./object-location-xgYMemK6.js";class L extends G{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",s=!0,a){return super.relationQuery(t,e,i,r,s,a)}}class m{static teaqlTemporaryId=0;id;title;description;platform;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const i={...t};Object.assign(this,i),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof y?t.platform:y.fromRecord(t.platform),this.markLoaded("platform"))}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=new m(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new m({id:String(t)})}static teaqlBootstrapNew(t){return new m().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new v([{ruleId:"invalid_type",location:g.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n),n.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"WorkItem",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);for(const[S,f]of Object.entries(n.payload))S!=="id"&&S!=="version"&&this._root.set(this.teaqlEntityKey(),S,f);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();return this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update"),d.scopeFor(p),e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}class y{static teaqlTemporaryId=0;id;name;version;constructor(t){if(Object.defineProperty(this,"_action",{value:t&&t.id?"Update":"Create",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:!t||!t.id,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new $,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--y.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:t?.id?I.empty():new I,writable:!0,enumerable:!1}),t){const i={...t};if(delete i.workItemList,Object.assign(this,i),Array.isArray(t.workItemList)){const r=t.workItemList;this._workItemList=new I(r.map(s=>s instanceof m?s:m.fromRecord(s)),{totalCount:r.totalCount,aggregations:r.aggregations,summary:r.summary,facets:r.facets,isLoaded:r.isLoaded??!0}),this.markLoaded("workItemList")}}const e=this.teaqlEntityKey();this._action==="Create"?this._root.markAsNew(e):this.version!==void 0&&this._root.setOriginalVersion(e,Number(this.version)),c.captureFor(this,this.teaqlMutationPayload())}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const e of this._workItemList)e.teaqlAttachRoot(t);return this}static fromRecord(t,e){const i=new y(t);return e?i.teaqlAttachRoot(e):i}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return new y({id:String(t)})}static teaqlBootstrapNew(t){return new y().updateId(String(t))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return new k(t),this._comment=t,this}async save(t){const e=t.requireResource("dataService");return e.executeGraphSave(new k(this._comment),async i=>(this.teaqlPreflightGraph(t,e,i),this.teaqlSaveWithinGraph(t,e,i)))}teaqlPreflightGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&a){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(h=>!this.isLoaded(h.member));if(u)throw new v([{ruleId:"invalid_type",location:g.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const n=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);a&&e.preflightMutation(n);const d=n.scopeFor(this.teaqlEntityKey());for(const[u,h]of this._workItemList.entries()){h.teaqlAttachRoot(this._root);const l=h.platform;(this.id===void 0||!h.isLoaded("platform")||(typeof l=="object"&&l!==null?l.id:l)!==this.id)&&h.updatePlatform(this);try{h.teaqlPreflightGraph(t,e,i,d)}catch(p){if(!(p instanceof v))throw p;const S=g.property("work_item_list").index(u);throw new v(p.violations.map(f=>({...f,location:f.location.prefixedBy(S)})))}}}async teaqlSaveWithinGraph(t,e,i,r){r||new k(this._comment);const s=this._action,a=this._root.change(this.teaqlEntityKey()),n={entity:"Platform",action:this._action,payload:s==="Update"?a:this.teaqlMutationPayload(),id:this.id,version:this.version,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(n,r,this._comment).withLoadedSnapshot(c.forEntity(this)??new c);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const f=d.scopeFor(this.teaqlEntityKey());for(const[q,w]of this._workItemList.entries()){w.teaqlAttachRoot(this._root);const _=w.platform;(this.id===void 0||!w.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&w.updatePlatform(this);try{await w.teaqlSaveWithinGraph(t,e,i,f)}catch(N){if(!(N instanceof v))throw N;const P=g.property("work_item_list").index(q);throw new v(N.violations.map(B=>({...B,location:B.location.prefixedBy(P)})))}}return this}const u=await e.executeMutation(d);for(const[f,q]of Object.entries(n.payload))f!=="id"&&f!=="version"&&this._root.set(this.teaqlEntityKey(),f,q);if(!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const h={payload:this.teaqlMutationPayload(),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:c.forEntity(this)},l=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),c.captureFor(this,this.teaqlMutationPayload()),this._ledgerId=this.id??this._ledgerId;const p=this.teaqlEntityKey();this._root.rekey(l,p),e.afterGraphRollback(()=>{Object.assign(this,h.payload),this._ledgerId=h.ledgerId,this._action=h.action,this._loadedFields=h.loadedFields,this._fullyLoaded=h.fullyLoaded,c.restoreFor(this,h.loadedSnapshot),this._root.rekey(p,l)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,n.action!=="Delete"&&(this._action="Update");const S=d.scopeFor(p);for(const[f,q]of this._workItemList.entries()){q.teaqlAttachRoot(this._root);const w=q.platform;(this.id===void 0||!q.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,i,S)}catch(_){if(!(_ instanceof v))throw _;const N=g.property("work_item_list").index(f);throw new v(_.violations.map(P=>({...P,location:P.location.prefixedBy(N)})))}}return e.afterGraphCommit(()=>{this._root.clearEntity(p),this.version!==void 0&&this._root.acceptCommittedVersion(p,Number(this.version))}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const D=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class A{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new X(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({toQuery:()=>new L("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({toQuery:()=>new L("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new L("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof y?n:y.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof y?l:y.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof y?n:y.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class X{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new y}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class x{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new L("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=O(i,t,D,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Z(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id"),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title"),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description"),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform"),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version"),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=r?[]:i.map(n=>n instanceof m?n:m.fromRecord(n,new $)),a=new I(s);return r&&i[0]&&Object.assign(a.aggregations,i[0]),this.query.facets.length>0&&(a.facets=await C(e,n=>t.prepareQuery(n),this.query,this.query.facets)),a}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new I(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},a=r?void 0:await e.executeCount(i,this._pageCountAlias,s),n=i.clone();n.aggregateItems=n.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this._pageCountAlias));const d=await e.executeQuery(n),u=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:a??await e.executeCount(i,this._pageCountAlias,s),h=new I(d.map(l=>l instanceof m?l:m.fromRecord(l,new $)));return h.totalCount=u,this._pageCountAlias!==void 0&&(h.aggregations[this._pageCountAlias]=u),this.query.facets.length>0&&(h.facets=await C(e,l=>t.prepareQuery(l),i,i.facets)),h}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),s=i.executeForStream(r,e);return(async function*(){for await(const a of s)for(const n of a)yield n instanceof m?n:m.fromRecord(n,new $)})()}ensureIntent(){new K(this._comment,this._purpose)}}class Z{constructor(t,e,i,r,s,a){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=s,this.ensureIntent=a}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}newEntity(t){return this.ensureIntent(),new m}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class R{static platforms(){return new A(!1)}static platformsWithMinimalFields(){return new A(!0)}static workItems(){return new x(!1)}static workItemsWithMinimalFields(){return new x(!0)}}const tt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function et(o){let t=(await R.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(o))[0];t||(t=y.teaqlBootstrapNew("1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(o)),o.withActiveRoot({entity:"Platform",id:t.id})}const it=new U(tt,{Platform:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:g.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:g.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(o,t,e){o.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:g.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:g.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:g.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:g.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:g.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:et}),rt={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},F=document.querySelector("#status"),st=document.querySelector("#result"),T=document.querySelector("#persist"),E=document.querySelector("#reset");let b;const M=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";T.checked=M==="opfs";async function nt(o){const t=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),e=await z.open(t,{...rt},{storage:o,databaseName:"teaql-browser-example.sqlite3"});e.install(it);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new H().insertResource("dataService",e).withMutationPolicyRegistry(new J(()=>({identity:i,review:(s,a)=>a.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Y(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Q({context:o}){if(!(await R.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(o)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await new m().updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(o)}async function V(o){const t=await R.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(o.context);st.textContent=JSON.stringify(t,null,2),F.textContent=`${o.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function j(o){F.textContent=`Opening ${o.toUpperCase()} SQLite/WASM…`;const t=b;b=void 0,await t?.client.close();const e=await nt(o);b=e,await Q(e),await V(e)}T.addEventListener("change",()=>{const o=T.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",o),j(o).catch(W)});E.addEventListener("click",async()=>{if(b){E.disabled=!0;try{await b.client.reset(b.context),await Q(b),await V(b)}catch(o){W(o)}finally{E.disabled=!1}}});function W(o){const t=o instanceof Error?o:new Error(String(o));F.textContent=`${t.name}: ${t.message}`}j(M).catch(W);123456789101112131415161718192021222324252627282930313233343536373839404142434445<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="icon" href="data:," /><title>TeaQL browser order TraceChain</title><script type="module" crossorigin src="/assets/index-CSFBt0NB.js"></script><link rel="stylesheet" crossorigin href="/assets/index-DmPc8xp3.css"></head><body><main><p class="eyebrow">GENERATED Q + E · SQLITE/WASM · NO BACKEND</p><h1>Order query evidence</h1><p>One filtered page, named total, status facets and bounded item previews.</p><p>Entirely browser-local · SQLite/WASM · Generated typed Order Q/E APIs</p><p><a href="https://github.com/teaql/teaql-ts">Runtime source</a> · <a href="https://huggingface.co/spaces/teaql/browser-sqlite-playground/tree/main/source">This demo's source snapshot</a></p><div class="controls"><label><input id="persist" type="checkbox" /> Persist locally with OPFS <span id="opfs-note"></span></label><label><input id="logging" type="checkbox" checked /> Diagnostic logging</label><button id="reset">Reset demo data</button></div><label for="example">Example query</label><select id="example"><option value="filtered">Filtered order page</option><option value="all">All orders</option></select><label for="search">Editable generated TypeScript Q API, parsed into a controlled AST</label><textarea id="search" rows="20" spellcheck="false" style="display:block;width:100%;margin:12px 0"></textarea><p>No eval, imports, assignments or arbitrary JavaScript execution.</p><button id="query">Run query</button><button id="preset">Restore example search</button><p id="status">Starting SQLite/WASM…</p><h2>Response data and metadata</h2><pre id="result"></pre><h2>SQL execution evidence</h2><p>Time is the recorded execution duration. Identity is the request entity from tracePath, not a user or object ID.</p><div class="evidence-scroll"><table class="evidence-table"><thead><tr><th scope="col">Time</th><th scope="col">Identity</th><th scope="col">Trace chain</th><th scope="col">SQL</th></tr></thead><tbody id="evidence-rows"></tbody></table></div><details><summary>Business TraceChain as text</summary><pre id="trace"></pre></details><details><summary>Runtime metadata and physical tracePath</summary><pre id="sql"></pre></details></main></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="icon" href="data:," /><meta name="description" content="A TeaQL order-query playground running entirely in the browser" /><title>TeaQL Order Query Playground</title><script type="module" crossorigin src="/assets/main-gHLGx1pH.js"></script><link rel="modulepreload" crossorigin href="/assets/dynamic-search-BBmdgl4H.js"><link rel="stylesheet" crossorigin href="/assets/style-SCdXWqgK.css"></head><body><div class="page-shell"><header class="site-header"><a class="brand" href="#order-center" aria-label="TeaQL Playground home"><span class="brand-mark">T</span><span>TeaQL Playground</span></a><div class="header-actions"><div class="language-switch" aria-label="Language"><button type="button" data-locale="en" class="active">EN</button><button type="button" data-locale="zh">中文</button></div><a class="docs-link" href="https://teaql.io/" target="_blank" rel="noreferrer">teaql.io ↗</a></div></header><main><section class="hero"><div class="hero-copy"><p class="eyebrow">BROWSER SQLITE · ORDER DOMAIN</p><h1 data-i18n="heroTitle">Understand TeaQL queries through a familiar order model.</h1><p class="hero-intro" data-i18n="heroIntro">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.</p></div><div class="model-map" aria-label="Order domain model"><div class="model-flow"><span class="model-root">Platform<small data-i18n="platform">Platform</small></span><span class="model-arrow">→</span><span>Customer<small data-i18n="customer">Customer</small></span><span class="model-arrow">→</span><span class="model-root">Order<small data-i18n="order">Order</small></span></div><span class="model-arrow model-arrow-split">↓</span><div class="model-leaves"><span>Item<small data-i18n="item">Item</small></span><span>Payment<small data-i18n="payment">Payment</small></span><span>Shipment<small data-i18n="shipment">Shipment</small></span><span>OrderStatus<small data-i18n="constantModel">Constant model</small></span></div></div></section><section class="runtime-bar" aria-label="Runtime settings"><p id="status" role="status">Starting SQLite/WASM…</p><div class="controls"><label class="toggle"><input id="persist" type="checkbox" /><span aria-hidden="true"></span><span data-i18n="persist">Persist locally with OPFS</span></label><button id="reset" class="secondary-button" type="button" data-i18n="reset">Reset demo data</button></div></section><section class="query-browser" aria-labelledby="query-browser-title"><div class="section-heading"><div><p class="section-index">01 / QUERIES</p><h2 id="query-browser-title" data-i18n="chooseQuery">Choose a query</h2></div><p data-i18n="queryIntro">Queries are grouped by purpose and share the same order dataset.</p></div><nav id="query-catalog" aria-label="Example queries"></nav></section><section class="result-panel" aria-labelledby="result-title"><div class="result-heading"><div><p class="section-index">02 / RESULT</p><h2 id="result-title">Comprehensive: Order management center</h2><p id="result-description"></p></div><div class="result-actions"><div class="result-view-switch" aria-label="Result views"><button id="view-table" type="button" data-i18n="table">Table</button><button id="view-tree" type="button" data-i18n="resultTree">Result Tree</button></div><div class="tree-actions" aria-label="Result tree actions"><button id="expand-all" type="button" data-i18n="expandAll">Expand all</button><button id="collapse-all" type="button" data-i18n="collapseAll">Collapse all</button></div></div></div><div id="result-grid" class="result-grid"><div class="tree-card"><div class="tree-card-bar"><span id="result-view-label">Result tree</span><p id="result-meta" data-i18n="waiting">Waiting for query…</p></div><div id="result" class="json-tree" aria-live="polite"></div></div><div class="query-card"><p class="query-card-label">GENERATED Q QUERY</p><pre><code id="query-code"></code></pre><div id="query-params-block" class="query-params hidden"><p class="query-card-label">DYNAMIC PARAMETERS</p><pre><code id="query-params-code"></code></pre></div><p class="query-note" data-i18n="queryNote">The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.</p></div><div class="sql-card"><div class="sql-card-heading"><p class="query-card-label" data-i18n="executionEvidence">EXECUTION EVIDENCE</p><span id="sql-count">0 statements</span></div><div class="execution-evidence-wrap"><table class="execution-evidence"><thead><tr><th data-i18n="evidenceTime">Time</th><th data-i18n="identity">Identity</th><th data-i18n="traceChain">Trace chain</th><th>SQL</th></tr></thead><tbody id="sql-output"></tbody></table></div><p class="query-note" data-i18n="sqlNote">One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.</p></div></div></section></main><footer><span>TeaQL TypeScript Runtime</span><span data-i18n="localData">Data stays in this browser</span></footer></div></body></html>
12345678910111213141516171819202122232425262728293031323334353637383940414243<!doctype html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="data:," /> <title>TeaQL browser order TraceChain</title> <script type="module" crossorigin src="/assets/orders-CQOGX0kN.js"></script> <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BBmdgl4H.js"> <link rel="modulepreload" crossorigin href="/assets/object-location-xgYMemK6.js"> <link rel="stylesheet" crossorigin href="/assets/style-SCdXWqgK.css"></head><body> <main> <p class="eyebrow">GENERATED Q + E · SQLITE/WASM · NO BACKEND</p> <h1>Order query evidence</h1> <p>One filtered page, named total, status facets and bounded item previews.</p> <p><a href="/">WorkItem demo</a> · <a href="https://github.com/teaql/teaql-ts">Runtime source</a></p> <div class="controls"> <label><input id="persist" type="checkbox" /> Persist locally with OPFS</label> <label><input id="logging" type="checkbox" checked /> Diagnostic logging</label> <button id="reset">Reset demo data</button> </div> <label for="search">Search JSON, validated by the generated request</label> <textarea id="search" rows="4" style="display:block;width:100%;margin:12px 0">{"filter":{"orderNumber":{"$contains":"KEEP"}}}</textarea> <button id="query">Run query</button> <button id="preset">Restore example search</button> <p id="status">Starting SQLite/WASM…</p> <h2>Response data and metadata</h2> <pre id="result"></pre> <h2>SQL execution evidence</h2> <p>Time is the recorded execution duration. Identity is the request entity from tracePath, not a user or object ID.</p> <div class="evidence-scroll"> <table class="evidence-table"> <thead><tr><th scope="col">Time</th><th scope="col">Identity</th><th scope="col">Trace chain</th><th scope="col">SQL</th></tr></thead> <tbody id="evidence-rows"></tbody> </table> </div> <details><summary>Business TraceChain as text</summary><pre id="trace"></pre></details> <details><summary>Runtime metadata and physical tracePath</summary><pre id="sql"></pre></details> </main></body></html>12345678910111213141516171819202122232425262728<!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="data:," /> <title>TeaQL Browser SQLite WorkItems</title> <script type="module" crossorigin src="/assets/workItems-DraVJWt7.js"></script> <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BBmdgl4H.js"> <link rel="modulepreload" crossorigin href="/assets/object-location-xgYMemK6.js"> <link rel="stylesheet" crossorigin href="/assets/workItems-5mJKEgxC.css"> </head> <body> <main> <p class="eyebrow">TEAQL TYPESCRIPT RUNTIME</p> <h1>Browser-local Data Service</h1> <p>Generated Q APIs and audited mutations, backed by SQLite/WASM.</p> <p><a href="/">Open the order management center</a></p> <p><a href="/orders.html">Open the generated order TraceChain page</a></p> <div class="controls"> <label><input id="persist" type="checkbox" /> Persist locally with OPFS</label> <button id="reset">Reset demo data</button> </div> <p id="status">Starting SQLite/WASM…</p> <pre id="result"></pre> </main> </body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="icon" href="data:," /><title>TeaQL browser order TraceChain</title><script type="module" crossorigin src="/assets/index-CSFBt0NB.js"></script><link rel="stylesheet" crossorigin href="/assets/index-DmPc8xp3.css"></head><body><main><p class="eyebrow">GENERATED Q + E · SQLITE/WASM · NO BACKEND</p><h1>Order query evidence</h1><p>One filtered page, named total, status facets and bounded item previews.</p><p>Entirely browser-local · SQLite/WASM · Generated typed Order Q/E APIs</p><p><a href="https://github.com/teaql/teaql-ts">Runtime source</a> · <a href="https://huggingface.co/spaces/teaql/browser-sqlite-playground/tree/main/source">This demo's source snapshot</a></p><div class="controls"><label><input id="persist" type="checkbox" /> Persist locally with OPFS <span id="opfs-note"></span></label><label><input id="logging" type="checkbox" checked /> Diagnostic logging</label><button id="reset">Reset demo data</button></div><label for="example">Example query</label><select id="example"><option value="filtered">Filtered order page</option><option value="all">All orders</option></select><label for="search">Editable generated TypeScript Q API, parsed into a controlled AST</label><textarea id="search" rows="20" spellcheck="false" style="display:block;width:100%;margin:12px 0"></textarea><p>No eval, imports, assignments or arbitrary JavaScript execution.</p><button id="query">Run query</button><button id="preset">Restore example search</button><p id="status">Starting SQLite/WASM…</p><h2>Response data and metadata</h2><pre id="result"></pre><h2>SQL execution evidence</h2><p>Time is the recorded execution duration. Identity is the request entity from tracePath, not a user or object ID.</p><div class="evidence-scroll"><table class="evidence-table"><thead><tr><th scope="col">Time</th><th scope="col">Identity</th><th scope="col">Trace chain</th><th scope="col">SQL</th></tr></thead><tbody id="evidence-rows"></tbody></table></div><details><summary>Business TraceChain as text</summary><pre id="trace"></pre></details><details><summary>Runtime metadata and physical tracePath</summary><pre id="sql"></pre></details></main></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="icon" href="data:," /><meta name="description" content="A TeaQL order-query playground running entirely in the browser" /><title>TeaQL Order Query Playground</title><script type="module" crossorigin src="/assets/main-gHLGx1pH.js"></script><link rel="modulepreload" crossorigin href="/assets/dynamic-search-BBmdgl4H.js"><link rel="stylesheet" crossorigin href="/assets/style-SCdXWqgK.css"></head><body><div class="page-shell"><header class="site-header"><a class="brand" href="#order-center" aria-label="TeaQL Playground home"><span class="brand-mark">T</span><span>TeaQL Playground</span></a><div class="header-actions"><div class="language-switch" aria-label="Language"><button type="button" data-locale="en" class="active">EN</button><button type="button" data-locale="zh">中文</button></div><a class="docs-link" href="https://teaql.io/" target="_blank" rel="noreferrer">teaql.io ↗</a></div></header><main><section class="hero"><div class="hero-copy"><p class="eyebrow">BROWSER SQLITE · ORDER DOMAIN</p><h1 data-i18n="heroTitle">Understand TeaQL queries through a familiar order model.</h1><p class="hero-intro" data-i18n="heroIntro">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.</p></div><div class="model-map" aria-label="Order domain model"><div class="model-flow"><span class="model-root">Platform<small data-i18n="platform">Platform</small></span><span class="model-arrow">→</span><span>Customer<small data-i18n="customer">Customer</small></span><span class="model-arrow">→</span><span class="model-root">Order<small data-i18n="order">Order</small></span></div><span class="model-arrow model-arrow-split">↓</span><div class="model-leaves"><span>Item<small data-i18n="item">Item</small></span><span>Payment<small data-i18n="payment">Payment</small></span><span>Shipment<small data-i18n="shipment">Shipment</small></span><span>OrderStatus<small data-i18n="constantModel">Constant model</small></span></div></div></section><section class="runtime-bar" aria-label="Runtime settings"><p id="status" role="status">Starting SQLite/WASM…</p><div class="controls"><label class="toggle"><input id="persist" type="checkbox" /><span aria-hidden="true"></span><span data-i18n="persist">Persist locally with OPFS</span></label><button id="reset" class="secondary-button" type="button" data-i18n="reset">Reset demo data</button></div></section><section class="query-browser" aria-labelledby="query-browser-title"><div class="section-heading"><div><p class="section-index">01 / QUERIES</p><h2 id="query-browser-title" data-i18n="chooseQuery">Choose a query</h2></div><p data-i18n="queryIntro">Queries are grouped by purpose and share the same order dataset.</p></div><nav id="query-catalog" aria-label="Example queries"></nav></section><section class="result-panel" aria-labelledby="result-title"><div class="result-heading"><div><p class="section-index">02 / RESULT</p><h2 id="result-title">Comprehensive: Order management center</h2><p id="result-description"></p></div><div class="result-actions"><div class="result-view-switch" aria-label="Result views"><button id="view-table" type="button" data-i18n="table">Table</button><button id="view-tree" type="button" data-i18n="resultTree">Result Tree</button></div><div class="tree-actions" aria-label="Result tree actions"><button id="expand-all" type="button" data-i18n="expandAll">Expand all</button><button id="collapse-all" type="button" data-i18n="collapseAll">Collapse all</button></div></div></div><div id="result-grid" class="result-grid"><div class="tree-card"><div class="tree-card-bar"><span id="result-view-label">Result tree</span><p id="result-meta" data-i18n="waiting">Waiting for query…</p></div><div id="result" class="json-tree" aria-live="polite"></div></div><div class="query-card"><p class="query-card-label">GENERATED Q QUERY</p><pre><code id="query-code"></code></pre><div id="query-params-block" class="query-params hidden"><p class="query-card-label">DYNAMIC PARAMETERS</p><pre><code id="query-params-code"></code></pre></div><p class="query-note" data-i18n="queryNote">The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.</p></div><div class="sql-card"><div class="sql-card-heading"><p class="query-card-label" data-i18n="executionEvidence">EXECUTION EVIDENCE</p><span id="sql-count">0 statements</span></div><div class="execution-evidence-wrap"><table class="execution-evidence"><thead><tr><th data-i18n="evidenceTime">Time</th><th data-i18n="identity">Identity</th><th data-i18n="traceChain">Trace chain</th><th>SQL</th></tr></thead><tbody id="sql-output"></tbody></table></div><p class="query-note" data-i18n="sqlNote">One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.</p></div></div></section></main><footer><span>TeaQL TypeScript Runtime</span><span data-i18n="localData">Data stays in this browser</span></footer></div></body></html>
12345678910111213141516171819202122232425262728293031323334353637383940414243<!doctype html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="data:," /> <title>TeaQL browser order TraceChain</title> <script type="module" crossorigin src="/assets/orders-CQOGX0kN.js"></script> <link rel="modulepreload" crossorigin href="/assets/dynamic-search-BBmdgl4H.js"> <link rel="modulepreload" crossorigin href="/assets/object-location-xgYMemK6.js"> <link rel="stylesheet" crossorigin href="/assets/style-SCdXWqgK.css"></head><body> <main> <p class="eyebrow">GENERATED Q + E · SQLITE/WASM · NO BACKEND</p> <h1>Order query evidence</h1> <p>One filtered page, named total, status facets and bounded item previews.</p> <p><a href="/">WorkItem demo</a> · <a href="https://github.com/teaql/teaql-ts">Runtime source</a></p> <div class="controls"> <label><input id="persist" type="checkbox" /> Persist locally with OPFS</label> <label><input id="logging" type="checkbox" checked /> Diagnostic logging</label> <button id="reset">Reset demo data</button> </div> <label for="search">Search JSON, validated by the generated request</label> <textarea id="search" rows="4" style="display:block;width:100%;margin:12px 0">{"filter":{"orderNumber":{"$contains":"KEEP"}}}</textarea> <button id="query">Run query</button> <button id="preset">Restore example search</button> <p id="status">Starting SQLite/WASM…</p> <h2>Response data and metadata</h2> <pre id="result"></pre> <h2>SQL execution evidence</h2> <p>Time is the recorded execution duration. Identity is the request entity from tracePath, not a user or object ID.</p> <div class="evidence-scroll"> <table class="evidence-table"> <thead><tr><th scope="col">Time</th><th scope="col">Identity</th><th scope="col">Trace chain</th><th scope="col">SQL</th></tr></thead> <tbody id="evidence-rows"></tbody> </table> </div> <details><summary>Business TraceChain as text</summary><pre id="trace"></pre></details> <details><summary>Runtime metadata and physical tracePath</summary><pre id="sql"></pre></details> </main></body></html>12345678910111213141516171819202122{ "package.json" : "bbfaeef0b7488ec0f44377eecc68375124b8f0c4fcacd7d59df1755b0a127581", "src/generated-bootstrap.ts" : "5f3065c1e4794c0d21ada7c2eef48f4694cec1cbc4771fa48bc7d6ff9221540b", "src/generated-search-models.ts" : "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", "src/generated/E.ts" : "c4c72de70c1b103343390acee51970dd1fa01cdbe1bdebd9b9aa34b3539d2039", "src/generated/Q.ts" : "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", "src/generated/models/Customer.ts" : "d134c6b78e25d86dacea5d4c738178c3629101269413bb45d62a2f490d9b4417", "src/generated/models/CustomerOrder.ts" : "c65e857a6deb99599e34a06bb24ca948cc852e9a15b969ff4ffe21d041fcf05c", "src/generated/models/OrderItem.ts" : "ce43fb172b461b74d53cb73933335a8fa055b6269738f44bf3e1deb04e1d8b85", "src/generated/models/OrderStatus.ts" : "c6e3349c7da21267dee6940b61a9d43bc0413a7d68230b9c600b73ec82f96e16", "src/generated/models/Platform.ts" : "6a2df07a3fc284d02639ecb530d0aaa58e448dbc77de7d97b46dc4e367cd58fd", "src/generated/requests/CustomerOrderRequest.ts" : "0f2a2a3895c7245ea258354e6fc19e24b4e57adc48a29818abe7b8ce8126cb57", "src/generated/requests/CustomerRequest.ts" : "109f1df30ccafb9e4a163fa5f94d8e77d915cd2bb5a2d8bf3e7adeadbe92e262", "src/generated/requests/OrderItemRequest.ts" : "ab3fb698f606c848da983eaabc140268066b8d9bac73b54127733c98e48e19d9", "src/generated/requests/OrderStatusRequest.ts" : "f9087a9084b3aaac46d91cd7006cf5b71214df711bfd0f51e17da83a53e633c9", "src/generated/requests/PlatformRequest.ts" : "8a6dd581be256cad3332ca275ac3652ef1e01a0c4c9f0e6cefd2a6e14fc105e1", "src/runtime-module.ts" : "f92fe9a9474678d26a233eb734b14493b4ddc216ed3b648bfad723b4b6a46eeb", "src/teaql-schemas.ts" : "68cb7cacc725ff041d2289f17d7817ae56f37d035c92f2feb6c1318face6f806", "src/teaql-ts.ts" : "cc705f9f7873450eae541311317db3402dc40b7cf068c440169bd7ba06dcb1ed", "teaql-i18n.json" : "ee5dc28e916a8907555d5d5a4d0e3cf2fa37aad047af37abed0800582af18d96", "tsconfig.json" : "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import assert from 'node:assert/strict';import {writeFileSync} from 'node:fs';import puppeteer from 'puppeteer-core';
const url = process.env.TEAQL_SPACE_URL || 'https://teaql-browser-sqlite-playground.static.hf.space/';const browser = await puppeteer.launch({executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage']});try { const page = await browser.newPage(), errors = []; page.on('pageerror', error => errors.push(error.message)); page.on('console', event => { if (event.type() === 'error') errors.push(event.text()); }); page.on('response', response => { if (response.status() >= 400) errors.push(`${response.status()} ${response.url()}`); }); page.on('requestfailed', request => errors.push(`${request.failure()?.errorText} ${request.url()}`)); await page.goto(url, {waitUntil: 'networkidle0', timeout: 60_000}); const waitReady = () => page.waitForFunction(() => document.querySelector('#status')?.textContent?.includes('ready'), {timeout: 45_000}); await waitReady(); async function inspect(label) { const response = JSON.parse(await page.$eval('#result', element => element.textContent)); const evidence = JSON.parse(await page.$eval('#sql', element => element.textContent)); assert.equal(response.resultCode, 0); assert.equal(response.status, 'YES'); assert.equal(response.recordCount, 3); assert.equal(response.metadata.totalCount, 3); assert.equal(response.data[0].orderNumber, 'KEEP-002'); assert.equal(response.data[0].itemCount, 5); assert.deepEqual(response.data[0].items.map(item => item.productName), ['Box 1', 'Box 2', 'Box 3']); assert.deepEqual(response.facets.statusCounts.map(row => [row.orderCount, row.orderTotalAmount]), [[1, 100], [2, 500], [0, null]]); assert.equal(evidence.length, 8); const chains = evidence.map(entry => entry.traceChain.filter(node => node.kind === 'comment').map(node => node.detail)); for (const expected of [ ['load order list', "countAs('totalOrders')"], ['load order list', 'selectStatusWith(...)', 'load status'], ['load order list', 'selectOrderItemListWith(...)', 'load item previews'], ['load order list', "countOrderItemsAs('itemCount')"], ['load order list', "facetByStatusAs('statusCounts')", 'aggregate status'], ['load order list', "facetByStatusAs('statusCounts')", 'load status facets'], ]) assert.ok(chains.some(chain => JSON.stringify(chain) === JSON.stringify(expected)), JSON.stringify(expected)); const rendered = await page.$$eval('#evidence-rows tr', rows => rows.map(row => [...row.querySelectorAll('td')].map(cell => cell.textContent))); assert.deepEqual(rendered, evidence.map(entry => [`${entry.elapsedMicros} µs`, entry.tracePath.find(node => node.kind === 'request')?.name ?? '—', `${entry.traceChain.find(node => node.kind === 'purpose').detail}: ${entry.traceChain.filter(node => node.kind === 'comment').map(node => node.detail).join(' → ')}`, entry.debugSQL])); return {label, response, evidence, rendered}; } const receipts = [await inspect('first')]; const host = await page.evaluate(() => ({crossOriginIsolated, opfsDisabled: document.querySelector('#persist').disabled})); if (!host.crossOriginIsolated) assert.equal(host.opfsDisabled, true); await page.click('#logging'); await page.waitForFunction(() => document.querySelector('#status')?.textContent?.includes('0 diagnostics')); receipts.push(await inspect('diagnostics-off')); await page.select('#example', 'all'); await page.waitForFunction(() => { const text = document.querySelector('#result')?.textContent; return text && JSON.parse(text).recordCount === 4; }); await page.$eval('#search', element => { element.value = 'Q.constructor("return globalThis")'; }); await page.click('#query'); await page.waitForFunction(() => document.querySelector('#status')?.textContent?.includes('not allowed')); assert.equal(await page.$eval('#sql', element => element.textContent), '[]'); await page.click('#preset'); await waitReady(); receipts.push(await inspect('restored')); await page.click('#reset'); await page.waitForFunction(() => !document.querySelector('#reset').disabled); receipts.push(await inspect('reset')); await page.reload({waitUntil: 'networkidle0'}); await waitReady(); receipts.push(await inspect('refresh')); assert.deepEqual(errors, []); if (process.env.TEAQL_SPACE_EVIDENCE) writeFileSync(process.env.TEAQL_SPACE_EVIDENCE, JSON.stringify({url, host, receipts, queryPresetSwitch: true, forbiddenConstructorRejected: true, errors, passed: true}, null, 2) + '\n', {flag: 'wx'}); console.log(`PASS live Static Space: new TraceChain, 8 SQL records, editor/presets, WebResponse/facets, diagnostics-off, reset/refresh; OPFS disabled=${host.opfsDisabled}`);} finally { await browser.close(); }12345678910111213141516import type { SmartList } from 'teaql-ts';
/** Application response projection; querying and facet computation stay in the runtime. */export function webResponse<T>(rows: SmartList<T>) { const facets = Object.fromEntries(Object.entries(rows.facets) .map(([name, values]) => [name, Array.from(values)])); return { data: Array.from(rows), resultCode: 0, status: 'YES' as const, recordCount: rows.totalCountOrLength(), version: '1.001', ...(Object.keys(facets).length ? {facets} : {}), ...(Object.keys(rows.aggregations).length ? {aggregations: rows.aggregations} : {}), };}123version https://git-lfs.github.com/spec/v1oid sha256:1d4e5cbaecc4fcc06fe3b357a4575d6e5ca4a92673b625ef2c7d5ec7d02b287dsize 34929412345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061{"repository": "https://github.com/teaql/teaql-ts","baseCommit": "b4068dc","branch": "feature/polyglot-request-trace-chain-20261011","runtimeVersion": "0.3.0","unreleasedRequestTreeCandidate": true,"runtimeArchiveSha256": "1d4e5cbaecc4fcc06fe3b357a4575d6e5ca4a92673b625ef2c7d5ec7d02b287d","modelSha256": "dd86f59d512c88f8f0f41957122b18eceeb696dc188b208f42ed7b7b636144ec","runtimeHashes": {"src/core/ast.ts": "75a9756107e1f9ca33847a5107a337666cc400c2b506a8789e7fb861aa068b64","src/core/checker.ts": "ba4d997dc75dd69db810864d4c91f2ab3482eebd1fc0e27f14fac7a737a85ced","src/core/context.ts": "c6a11bb236ba0f4b847e8e9a016bd14b5d7451349875e1eb1464af430db80a62","src/core/dynamic-search.ts": "37fbea226c530af09f92ed7af4b7f3b90a98d2740f8dc38a73f0d57b244f92a7","src/core/entity-root.ts": "fe6b15988efdca2d5c09b5a134cbcf1a423fd6d316b1b4bc5f3917fa21616c32","src/core/facet.ts": "85a8efc8b2960ffb104528c9925e8685f2d2aef1b379cf7c0b0300fe0ff577f2","src/core/i18n.ts": "acbb07afb6aa2960fef0936ade71959309d4ae8bb4b1ac3aca60f476b09572ed","src/core/loaded-scalar-snapshot.ts": "86759e26ac8a0f669a64a1de7564171fa2e1d18bbaa0c9a6ae167ae23399ce7c","src/core/local-cache.ts": "efdccfc0dcb48868761d8ebbc0bb9cf4f158a9ae7dec76fce8a2c076a07b0b92","src/core/log-privacy.ts": "2c5165ca9141ed9d5c84df511102c69b4b492083db3e50fb2e74acd3437f4d16","src/core/mutation-policy.ts": "a5f1c2b6e961f508faebfc0037a257b1f4abbe1437b52b5f09a9c85c71d4efe0","src/core/object-location.ts": "b55ca8e966b25eb505c77181f358b2a8405edc1e60b23a58756ceb9ca6a552dc","src/core/query-snapshot.ts": "eb28bfb42775f26e431c90b3013766afbbfd2d23c855e90eca781601482eef39","src/core/request-intent.ts": "3daf7cf19f3bc94db42a6dcf5750a8af46d03e659113f9d946b9ac985517420e","src/core/runtime-module.ts": "87c082b295c83c5d9ffb5c389bd66a48caca3ee6b792e99fa7f582ea33243a10","src/core/schema-capability.ts": "a0aabc048fc3fc66b6606f5173810e1bb147651423820292cf660d466862bf79","src/core/smart-list.ts": "c7aad0f28417259aa0a89281ba3cb87e623e6db27880387e7061c052165185f8","src/core/telemetry.ts": "6c43a3d5cedcfe75ca195dfc2650a5e868b0c81d58168bfd92b2b210a8ee1964","src/core/tools.ts": "a3df66934678175f43dbe16315446a88fb7c9cd995f2119a37418db6706e3712","src/core/trace-chain.ts": "f0f932e25f5a7ef02e4447ca53a4c4269e1e3a79bd0c5facb652f9c69e3f25b3","src/core/value.ts": "0f3034b1b7ce60ef8fc1120bbe5290ad31def72f04dfad6cc0110188ff829846","src/core/wire-fields.ts": "9a52feef63c32d543af0da5ba91d5a7e199552b33267b3709678fc259011fe8f","src/index.ts": "4b2ba3c022eae0ff0b2f0cf32dd92777fbce855f425a2888f07e84c05b036ee1","src/meta/descriptors.ts": "3f2a1e44c77d411aba98ca233b9ebf111b07156cfb9080f028f8cb2b0421c970","src/parser/dsl.ts": "aaf4519fb1ab982759a615ace7ed67c377df52c8f4b86185685295504ff189d0","src/parser/query-parser.generated.ts": "007b490204d146e205d04e013458105dbe255bbc6a946f9927133c812bb75f97","src/sql/browser-sqlite-protocol.ts": "28df5a79b20c5acc2df345b8c5028c2d1d72657bc42bb432447bb013ae78714d","src/sql/browser-sqlite-worker.ts": "9b0ea0e17983ff924a53f3fde63a6e0a429a533dba2c5c6e86587a69dc250075","src/sql/browser-sqlite.ts": "43e00a5447efc103de4a3a07eb57eee41c265aa0d58a055ed90bd0d4630ad58d","src/sql/core.ts": "bdb9acf1eebd8fa103068e1d06c7e6e232849ecaff4714bb51df9525d9a80a62","src/sql/expo-sqlite.ts": "dfacc52e79dcd13cf61b0f50dffe887422781487e67cd57e65eb0d10c84a150d","src/sql/index.ts": "351d2eeea00f904926390f9c066fc68bbcf09987d8f7dbff5107a8a3586f52b7","src/sql/log-rendering.ts": "15aaa620adf13c4eef06aa43915c85fd9832e0b3715ea00dda307dfa8b64343d","src/sql/mysql.ts": "78132e0b172704d046f953f6350a9b9fccbae4336846c171d330db1f56edd054","src/sql/postgres.ts": "5e3c87839ba9e21a6ec1c924ec06a5dc14261d8ba94dcb684bcfbfee04a0591b","src/sql/sqlite.ts": "f5a9434e396f5aabdc6569eb399f773b25f86a913340be7da74ff1e877172831","src/telemetry/opentelemetry.ts": "330db640ea3da7d8a5894bed0981385b2df52acebbfe535e9bb176b9cb66c7ec","src/tfp/client.ts": "db1392951089179191b8ff10d72e047469ce8eb55ff27691fb6aee5eafde4101","package.json": "513cdc8c3fde7fa043e96562b75f15095e6fa68de88bb86f26ccd12cdebe65f7","package-lock.json": "effe883993399138ebe86c98ccd43fd18cbbee74b464f9bb458b004f218b31c9","tsconfig.json": "e2181002b045e53934f18d4f371236e39b143226f1dea9a671d62a7f42218276","LICENSE": "c95bae1d1ce0235ecccd3560b772ec1efb97f348a79f0fbe0a634f0c2ccefe2c"},"build": {"command": "npm ci && npm run build && npm run smoke","workingDirectory": "source/browser-sqlite"},"limitations": ["No npm/public runtime release implied","No application backend","OPFS requires host cross-origin isolation"]12345678910111213141516171819{"repository": "https://github.com/teaql/teaql-ts","commit": "e87b5d843a1bc2ae5f677f402b6b3177a7d40b50","branch": "main","runtimeVersion": "0.3.1","sourceDirectory": "source/teaql-ts","applicationDirectory": "source/teaql-ts/examples/browser-sqlite","buildDirectory": "dist","validation": {"runtimeSuitesPassed": 56,"runtimeTestsPassed": 604,"runtimeTestsSkipped": 6,"browserSmoke": "passed","generatedOrderSmoke": "passed"},"limitations": ["No application backend","OPFS requires host cross-origin isolation"]
1dist/.sql-root-owned-backup-*/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369# TeaQL TypeScript
An AI-native library and runtime for building reviewable business applications in TypeScript.
TeaQL gives coding agents business-shaped APIs, model-aware guidance andsoftware checks. People review the business operation instead of reconstructingpages of query-building, relationship-loading and persistence code.
Automatic execution logs make those operations easier to debug and operate,without adding logging statements to every business method.
[Try with your coding agent](#try-it-with-your-coding-agent) ·[Run the local example](#run-the-local-example) ·[See automatic logs](#automatic-logs-without-handwritten-logging-code)
## Why this is an AI native library
AI-native does not mean the library was written by AI, or that every querycalls an LLM. It means the APIs, knowledge delivery and verification workfloware designed for how coding agents work: limited context, incomplete knowledgeof a project and a tendency to guess unfamiliar operations.
The semantic model describes your business objects, fields, relationships andstates. A generated domain library turns those words into language-native**Q** queries, **E** expressions and mutation methods. This repository providesthe reusable, domain-independent **runtime** that executes them throughmetadata, Context, Checker, Policy and database providers.
The application workspace keeps business code and concise project guidancetogether. Progressive **Assist** supplies the exact API guidance needed forthe next operation, instead of asking the agent to explore the entire generatedlibrary. Compilation, runtime checks and tests provide feedback beyond a prompt.
## Less code for a reviewer to reconstruct
The benefit is visible in the application code: the query, data access pathand audited change stay together, while shared mechanics live in the libraryand runtime.
| Application code to review | Shared work handled by TeaQL || --- | --- || A composed Q request | SQL construction and selected relation loading || An E access path | Loaded-field checks and explicit NULL handling || A mutation with an audit reason | Change tracking, Checker and configured Policy execution || Business intent and audit reason | Automatic execution logs and trace context without per-operation logging code |
Reviewers still decide whether the requested data, business rules andauthorization policy are correct. They have less application plumbing totrace before making that decision; reuse does not make business logic correctautomatically.
**Token savings have not yet been measured in a controlled comparison.**We make no numerical token-saving claim. Loading guidance only when neededis a context-management strategy; the smaller application review surface isvisible in the examples, not a measured percentage reduction in review time.
## See a business operation execute
The [Robot Task Board showcase](https://teaql.io/blog/robot-task-board-showcase/)makes the idea concrete: move a task and follow the state change, generatedSQL, field-level audit and refreshed board.

Explore the [open-source demo](https://github.com/teaql/robot-task-board).The showcase is a Rust application; the examples below use this repository'sown TypeScript APIs.
## Q API composes business queries
These application-code excerpts assume the example's generated imports, trustedContext and an existing object identity. `Q` and `E` belong to the generateddomain library, not a generic runtime object with arbitrary field strings.See the [application source](examples/school-management/app.ts) for complete setup.
```typescriptconst schoolTypeDetails = Q.schoolTypesWithMinimalFields().selectName().selectCode();
const school = await Q.schools() .withIdIs(schoolId) .selectPlatformWith(Q.platformsWithMinimalFields().selectName().selectBaseUrl()) .selectSchoolTypeWith(schoolTypeDetails) .comment("what: load the school and its reference data") .purpose("why: review a school before editing") .executeForOne(context);if (!school) throw new Error("School not found");```
The child request is a query in its own right. Give it a business name,extract it into a helper and compose it into other requests like a Lego brick.The reviewer can see which relationships are loaded without following aseparate set of SQL loops. `comment` describes **what**; `purpose` describes**why**. Both must be non-empty, even when logging is disabled.
## E API protects business reads
```typescriptconst schoolTypeId = E.school(school).schoolTypeId().eval();```
E reads the loaded graph without implicitly querying the database. A loadedNULL and a field that was **NotLoaded** are different facts. A business rulemust not conclude that a value is absent merely because the query neverrequested it.
The access path is explicit, so the reviewer checks whether Q loaded therequired data and whether the code handles a real NULL appropriately.Unloaded access produces the language-specific diagnostic; a NULL fallbackis not permission to ignore an unloaded property.
## Mutation API keeps changes behind one Save boundary
The application declares the change and its reason instead of writing its ownpersistence loop. A graph can stage additions, updates and deletions before Save.
Load the complete scalar fields of every persisted object you actually modify.A display-only partial projection is not a complete mutation input. Unmodifiedreference objects do not have to become fully loaded just to save their parent.
```typescriptschool.updateName("Riverside Academy");await school.auditAs("Rename the reviewed school").save(context);```
Save traverses the reached mutation graph, runs Checker/Fix and the configuredcustomer Mutation Policy, then uses the provider transaction boundary.An explicit policy denial blocks persistence. Missing customer policy or exactapproval emits a warning; it is not automatic rejection. Marking for deletionstages a change—the audited Save performs it. Atomicity is provider/route scoped,not a distributed transaction across unrelated databases.
## Automatic logs without handwritten logging code
**Debuggability and operability are core design goals.** The Q and Saveexamples above contain no logging calls: you declare the business intent,and the runtime produces the execution diagnostics and trace context.Configured audit sinks receive change events without each applicationmethod having to construct its own field-level diff.
The intent declarations already belong to the business operation:
- `comment` describes what the query does.- `purpose` explains why it runs.- `auditAs` gives the reason for a saved change.
No-code logging means no handwritten logger calls in each business method,not an application without code or intent declarations. Runtime startupstill configures any required sink; custom formats and destinations use thelogging extension points rather than edits to every business operation.
- **Debugging:** connect a query's intent to generated SQL, execution outcome and the trace path when a screen or business operation behaves unexpectedly.- **Operations:** follow query and mutation activity and use audit reasons and safely exposed changes to investigate incidents.- **Review:** inspect the business operation without separately checking that every TeaQL execution path has a matching application logging statement.
Query and Mutation diagnostic logs are enabled by default and can be switchedoff independently. Logging off does not disable intent validation or Policy.
Illustrative, shortened view of the rename operation, not a literal loggerformat or a captured test result; the SQL excerpt omits additional selected fields:
```textquery entity=School comment="load the reviewed object" purpose="edit form" outcome=successSQL: SELECT id, version, name FROM school_data WHERE id = 42;trace: School -> request -> sqlite -> selectmutation entity=School auditReason="Rename the reviewed school" outcome=committedchange: name "Riverside Primary School" -> "Riverside Academy"lineage: School#42("Rename the reviewed school")```
The declarations explain **why**; SQL and audit evidence show **what happened**.Together they help locate the relevant operation without reconstructing theentire call path from scattered application code.
SQL execution stays parameterized. Diagnostic SQL has parameters substitutedafter field-aware masking; it is not a question-mark template you must manuallyreconstruct. Ordinary bindings stay visible, sensitive bindings use the sharedmask algorithm, and credentials/unknown bindings stay hidden. A masked statementis labeled `MASKED; NOT REPLAYABLE`; SQL that cannot be safely rendered is omitted.Application mutation audits are delivered after commit and discarded on rollback.This is not a durable audit outbox. Do not put secrets in comment or purpose.
### Standard Node telemetry
The local source candidate provides optional environment-driven telemetry forNode applications. It is separate from default-on SQL logging and committedbusiness audit. No SDK setup or logging calls are needed in each business method.
```bashexport TEAQL_TELEMETRY_ENABLED=trueexport TEAQL_TELEMETRY_SERVICE_NAME=payment-serviceexport TEAQL_TELEMETRY_OTLP_ENDPOINT=http://localhost:4318```
Without enablement, startup reports support and these three settings withoutloading the SDK or creating export resources. Enabled startup reports fullrecording and masked SQL. The module owns its providers and HTTP agents; itdoes not replace customer globals. Telemetry uses official SDK protobufserialization and bounded acknowledgements. Remote error text is never logged;fixed diagnostics and loss/rejection counters explain export problems withoutchanging business outcomes. Partial acceptance never resends the entire batch,following the [OTLP response contract](https://opentelemetry.io/docs/specs/otlp/#partial-success).
Install the optional SDK cohort listed in this checkout's `package.json`,including its pinned `@opentelemetry/otlp-transformer`, when using the standardNode entry. Browser SQLite does not enable this Node-only module. Run`bash scripts/verify-standard-telemetry.sh` for local startup and graph checks;`bash scripts/verify-examples.sh` also verifies rollback, retry, selective updateand deletion. This is an unreleased source capability, not a published-packageinstallation claim. Local production-capacity tests qualify queue saturation,recovery and backlogged shutdown. Span/log admission includes queued and exportingrecords; fixed counters distinguish overflow, failed export, queued retirementand late handoff. Flush waits for the records accepted before that call. Shutdownhas a six-second budget and closes only module-owned resources; closing telemetrydoes not disable database operations or committed audit. Advanced graph/streamand private artifact installation remain separate acceptance gates.
## Discover only the API needed next
A coding agent does not need every generated method in its context. Start withthe generated application's `AGENTS.md` and workspace guidance, request anentity/action Assist, then ask for field-specific help only for the fieldbeing used.
For a model in `models/`, the TypeScript query path is:
```bashcargo teaql typescript-assist-query/school --input models/cargo teaql typescript-assist-query/school.established_date --input models/```
These commands call the model-aware service; the model must match the generatedlibrary. Assist uses canonical KSML entity and field names, even when thelanguage-native API uses a different naming style. Cargo TeaQL is a serviceclient for multiple languages, not just Rust.
Use Assist to discover operations instead of reading generated library sourceor guessing names. If the required operation is missing, report`MISSING_ASSIST` rather than inventing an API. The[Agent Kit](https://github.com/teaql/teaql-agent-kit) defines this progressiveworkflow. Library and runtime maintenance are separate from application coding.
## Software checks complement agent instructions
AI proposes the model and application logic; software checks the parts thatcan be verified mechanically. The library is one part of the TeaQL harness,not a replacement for business review.
| Stage | TeaQL support | Feedback to inspect || --- | --- | --- || Model and repair | Semantic model evaluation | Errors, warnings and repair guidance || Generate | Domain library combined with this runtime | Language tooling checks the generated API contract || Customize the workspace | Progressive Assist, Q, E and mutation APIs | Build diagnostics, Checker and configured Policy results || Verify and operate | Tests, runtime startup, intent and audit evidence | Actual outcomes, remaining failures and execution paths |
Build checks verify API use, not whether the business decision is right.Tests must still verify the application's behavior. A prompt, successfulgeneration or a clean build alone does not prove the finished application correct.
## Try it with your coding agent
You can start with an agent you already use. Paste this prompt:
```textFollow the current instructions at https://github.com/teaql/teaql-agent-kit.Build a small school-management application in TypeScript using SQLite.Evaluate and repair the model, generate the domain library and prepare a runnableapplication workspace. Verify Q, E, Checker and audited Save.Finish with a report of commands, results andremaining frictions. Include Q/E examples and relevant intent/audit logs.Do not claim token savings without a measured comparison.```
The [Agent Kit](https://github.com/teaql/teaql-agent-kit) guides modeling,evaluation/repair, generation and application customization. It may installtoolchains and download dependencies; review installation permissions and thefinal execution report. It is a workflow, not a guarantee of unattended correctness.
## Run the local example
Node.js/npm for the repository examples. Browser SQLite runs in a Web Worker with SQLite/WASM. From a checkout of this repository:
```bashcd examples/school-managementnpm installnpx ts-node app.ts```
The [School example](examples/school-management/README.md)exercises SQLite schema/bootstrap and generated application APIs against thisrepository's local runtime. No external database server or generator is neededto run the retained generated example. Use only the example's test database;reset/repeated-run behavior is documented in its README.
## Use the published runtime
Current documented runtime: **0.3.0**. Keep domain-library and runtimeversions compatible; regenerate older libraries when their provider or graphadapter SPI has changed.
```bashnpm install @teaql/teaql@0.3.0```
Use scoped imports such as `@teaql/teaql` or`@teaql/teaql/sql/sqlite`. The default entry point is driver-free; choose onlythe required profile and install its optional driver. Browser SQLite defaultsto memory; OPFS is an explicit persistence choice.
Generation is a separate service; see the [Agent Kit](https://github.com/teaql/teaql-agent-kit)for producing the application-specific library and workspace. Repository examplesuse local source; isolated released-package regression is a separate gate.
## Supported scope
TypeScript supports browser/TFP, Node SQL, Expo SQLite and browser SQLite/WASM profiles. The browser is not a trusted server authorization boundary or a backend key store. Peggy parses a controlled query AST; it does not execute arbitrary JavaScript with eval or new Function.
One semantic model can produce language-native applications across[Java](https://github.com/teaql/teaql-java),[Rust](https://github.com/teaql/teaql-rs),[TypeScript](https://github.com/teaql/teaql-ts),[Go](https://github.com/teaql/teaql-golang),[Swift](https://github.com/teaql/teaql-swift),[.NET](https://github.com/teaql/teaql-dotnet) and[Python](https://github.com/teaql/teaql-python).That does not imply identical APIs, providers or complete cross-language feature parity.The semantic model defines business objects, fields, relationships and states;it is not the language model used by a coding agent.The [conformance matrices](https://github.com/teaql/teaql-conformance)distinguish implemented source, executed examples, artifact verification and release.
## Verification and customization
```bashnpm test -- --runInBandbash scripts/verify-examples.sh```
The full example gate is the acceptance entry point for local runtime changes.External-provider tests need their configured services; skips are not live-providerevidence. A committed-operation error after audit delivery failure must not beretried as if the business transaction rolled back.
Install application-owned policies, ID/business-ID services, logging sinks,transports and other supported SPIs through trusted runtime/Context setup.Request JSON is not allowed to replace those trusted capabilities.
- [Runtime guide: modules, SPI and advanced verification](RUNTIME_GUIDE.md)- [Runtime profiles](RUNTIME_GUIDE.md#runtime-profiles)- [Browser SQLite example](examples/browser-sqlite/README.md)- [Facet example](examples/facet-trace/README.md)- [Trace Chain example](examples/trace-chain/README.md)
## Safe troubleshooting
Default diagnostics do not authorize plaintext sensitive data. Controlleddebugging requires the exact acknowledgement below and any sensitive sinkrequired by the runtime:
```bashexport TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS=I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK```
Debug output is explicitly labeled. Credentials and unknown bindings remainprotected; the flag does not erase old files or govern application/driverprints outside TeaQL. Restrict access and retention, then unset it and restart.See the [runtime guide](RUNTIME_GUIDE.md) for log switches and extension details.12345678910# Browser SQLite example
- Keep the existing WorkItem page and the generated Order page independently usable.- Application-owned code lives in `src/`, HTML, and `scripts/`. Never hand-edit `orders-lib/`.- Use `assist/query-*.md`, the required field help, and create/expression/debug Assist for API discovery. Do not inspect generated library source or guess method names.- Order queries must remain bounded and carry non-empty comment/purpose; seeding uses generated audited mutation APIs with the trusted context.- Search input is validated JSON. Never execute it with `eval` or `new Function`.- Read actual statement `traceChain` and `tracePath`; UI rendering must not manufacture lineage from SQL, routes or known aliases.- Dependencies resolve this repository's runtime, not a published package.- Run `npm run build`, `npm run smoke`, and `npm run smoke:orders`. The latter checks generated-library hashes; the repository example gate runs both smoke tests.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118# Browser SQLite/WASM order playground
This executable example uses a familiar commerce domain—platform, customer,order, item, payment, and shipment—to demonstrate TeaQL queries entirely in adedicated browser worker. It includes deterministic, internally consistent demodata and thirteen runnable examples organized as basic, aggregate, filtered,and dynamic queries.
`OrderStatus` is a seventh, constant model object rather than a string field.Its five fixed values are reconciled through `RuntimeModule` bootstrap, ordersstore the status object ID, and generated Q expressions select, filter, andfacet through the `status` relation. Visible status projections select `name`and `color`—not `code`—and the queried color drives the metric cards and statusbadges. Embedded relation Q expressions are displayed on one line so they alignwith the horizontal element they populate.
The interface defaults to English and can be switched to Chinese withoutre-running the active query. Tabular results use a table by default and remainavailable as an expandable Result Tree instead of a raw JSON text block.Dynamic examples pass user-shaped filters through TeaQL's validated fieldmetadata and do not use `eval`.
The first example is a complete order management center. Its status metrics,search (including product-name subqueries), item previews, and pagination areall driven by one generated `Q.customerOrders()` expression. Application codeuses the generated domain request API; the lower-level `SelectQuery` is confinedto `src/generated`. Every example shows the exact Q expression used by the pageand the parameterized SQL statements that SQLite executed, including timing,row counts, and policy-safe bindings. The execution evidence table prints thecaptured time, identity, intent, `tracePath`, and parameterized SQL on one rowper statement. Each trace is plain text with arrows between its original pathsteps; no JSON metadata or decorative visualization is added, and noapplication tracing code is required.
The order-center Q expression is stable across free-text search, status-cardselection, and pagination. Those interactions only replace `searchParams`,`pageOffset`, and `pageSize`; generated dynamic-search bindings compile ordernumber, `OrderStatus.code`, and item product-name paths without changing thepage query.
The order-center projection intentionally contains only the four visible tablecolumns: order number, order date, the `OrderStatus` object, and item preview.It does not load Platform or Customer. The Q chain follows the page vertically:dynamic filter, `countAs('totalOrders')`, status facet, four table projections, then pageexecution.
```bashnpm installnpm run dev```
Memory storage is the deterministic default. Refreshing recreates the data. Theoptional OPFS mode persists within the current browser origin. Reset drops thebrowser-local schema, explicitly runs `context.ensureSchema()` again, andre-seeds the six mutable entities through governed, audited mutations; the five`OrderStatus` constants are restored by runtime bootstrap.
The same application-approved mutation policy is used by both storage profiles.A denied plan is rejected before SQL is posted to the worker.
The previous WorkItem example remains independently available at`/work-items.html`. The Vite development server emits the COOP/COEP headers required by the SQLiteOPFS implementation. A production host must emit the same headers. This firstprofile intentionally excludes multi-tab database coordination and true rowstreaming.
## Generated order TraceChain page
Open `/orders.html` to run the shared request-tree Order model in the samebrowser SQLite/WASM provider. The WorkItem page remains available at`/work-items.html`, while `/` presents the full order management center.`order-model.xml` defines the model; `orders-lib/` is generated by the localModel-Aware Services producer, not handwritten Q or entity code. Model-awareAssist outputs are retained under `assist/`.
The order page uses generated audited mutation APIs to create four orders andfive items per order. Generated bootstrap provisions the platform and threestatus constants. The example search matches three orders and loads the secondone: KEEP-002, Paid, three item previews, and a full item count of five. Statusfacets retain counts and sums `(1,100)`, `(2,500)`, `(0,null)`.
The textarea accepts runtime-validated search JSON, not executable JavaScript.The actual query is compiled application code using the generated Q API. Theview reads selected fields through generated E expressions and displays data,page metadata and facets. Business TraceChain rendering uses only each actualstatement's `traceChain`; `tracePath` is displayed separately. No SQL parsing,known-alias branches or UI-owned lineage is used.
Diagnostic logging is on by default. Disabling it suppresses the diagnosticsink, while the explicitly installed evidence store still supplies the eightactual statements for the view. Memory refresh resets the data; OPFS survivesrefresh. Reset re-runs context-owned schema/bootstrap and generated mutations.
```bashnpm run buildnpm run smokenpm run smoke:orders```
The order smoke test runs real Chromium against the built deployment andchecks memory/OPFS refresh/reset, both diagnostic modes, Q/E results, exactfacet values, native operation comments, actual SQL count and unchangedgenerated-library hashes. The repository's `scripts/verify-examples.sh` runsboth browser smoke tests.
For maintainers with the generator checkout, regenerate the library and Assist:
```bashcd /path/to/teaql-code-genTEAQL_TEST_TYPESCRIPT_RUNTIME_PATH=/path/to/teaql-ts \ mvn -q -pl generator -am \ -Dtest=PolyglotRequestTreeSqliteTest#sharedOrderFixtureExportsBrowserLibraryAndAssist \ -Dsurefire.failIfNoSpecifiedTests=false test```
The generated library's local dependency points to this runtime repository.Do not manually repair `orders-lib/`; change the model or upstream templatesand regenerate instead.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182<!-- ephemeral -->
# TypeScript Assist — Create `Customer`
Use the exact generated `Q.customers()` entry point. Thetrusted `UserContext` supplies actor, tenant, policy, provider, and audit sink;none of those values may be accepted from the writable input.
```typescriptimport { UserContext } from '../teaql-ts';import { Q } from './Q';import { Customer } from './models/Customer';
export interface CreateCustomerInput { platform: string | number; name: string;
}
export async function createCustomer( input: CreateCustomerInput, context: UserContext,): Promise<Customer> { const entity = Q.customers() .comment('what: initialize Customer') .purpose('why: create Customer') .newEntity(context);
entity.updatePlatform(input.platform); entity.updateName(input.name);
await entity .auditAs('Create Customer for the requested business operation') .save(context); return entity;}```
Only the generated updater methods above are writable. Constant relationcandidates, when present, are also generated and must be copied exactly:
Compile the result unchanged. Test persistence and query-back, and prove thatblank/missing intent, blank/missing audit reason, unknown fields, and attemptedtrusted-context overrides fail. Do not edit generated sources.
---
## TeaQL seven-language assist contract
Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated andruntime APIs. Discover APIs through the generated application AGENTS.md and progressivemodel-aware Assist. Do not inspect generated domain-library source.
- Do not create plurals by appending `s` or `es`; use the centralized generated plural.- Human and non-human entities use different generated predicate vocabularies. Preserve forms such as “who are active” and “whose email is”; never infer them from English.- Configure filters, projection, paging, and other query options before `purpose(...)`. Comment may appear anywhere in the chain. Purpose enters the executable stage; execution requires both values, but comment does not have to immediately precede purpose.- Every execute/list/stream and every save accepts exactly one context argument: `UserContext`. Name that argument `context`, never `runtime`; data services and global policy are injected when the context is built. Reserve `runtime` for process-level runtime ownership, provider/pool setup, and module assembly.- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.- If the required operation is absent after current entity/action and required field Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the generated library as a fallback.- Create each application-owned source file once. After its first compile attempt, repair only the smallest block identified by the exact compiler or test diagnostic. Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.- Before a repair that would replace more than 25% of an existing application file, stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and estimated scope. Initial creation and model-driven regeneration are not repairs.
Capability: `create`.
- Validate and allow-list writable business fields; never mass-assign dynamic JSON.- Create through the generated request/entity API, attach a non-empty audit reason, save with the same UserContext, and return the runtime's native save result.- Add a negative test proving a missing audit reason cannot write.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192<!-- ephemeral -->
# TypeScript Assist — Create `Customer Order`
Use the exact generated `Q.customerOrders()` entry point. Thetrusted `UserContext` supplies actor, tenant, policy, provider, and audit sink;none of those values may be accepted from the writable input.
```typescriptimport { UserContext } from '../teaql-ts';import { Q } from './Q';import { CustomerOrder } from './models/CustomerOrder';
export interface CreateCustomerOrderInput { customer: string | number; status: string | number; orderNumber: string; orderDate: string; totalAmount: number;
}
export async function createCustomerOrder( input: CreateCustomerOrderInput, context: UserContext,): Promise<CustomerOrder> { const entity = Q.customerOrders() .comment('what: initialize Customer Order') .purpose('why: create Customer Order') .newEntity(context);
entity.updateCustomer(input.customer); entity.updateStatus(input.status); entity.updateOrderNumber(input.orderNumber); entity.updateOrderDate(input.orderDate); entity.updateTotalAmount(input.totalAmount);
await entity .auditAs('Create Customer Order for the requested business operation') .save(context); return entity;}```
Only the generated updater methods above are writable. Constant relationcandidates, when present, are also generated and must be copied exactly:- `updateStatusToNew()`- `updateStatusToPaid()`- `updateStatusToCancelled()`
Compile the result unchanged. Test persistence and query-back, and prove thatblank/missing intent, blank/missing audit reason, unknown fields, and attemptedtrusted-context overrides fail. Do not edit generated sources.
---
## TeaQL seven-language assist contract
Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated andruntime APIs. Discover APIs through the generated application AGENTS.md and progressivemodel-aware Assist. Do not inspect generated domain-library source.
- Do not create plurals by appending `s` or `es`; use the centralized generated plural.- Human and non-human entities use different generated predicate vocabularies. Preserve forms such as “who are active” and “whose email is”; never infer them from English.- Configure filters, projection, paging, and other query options before `purpose(...)`. Comment may appear anywhere in the chain. Purpose enters the executable stage; execution requires both values, but comment does not have to immediately precede purpose.- Every execute/list/stream and every save accepts exactly one context argument: `UserContext`. Name that argument `context`, never `runtime`; data services and global policy are injected when the context is built. Reserve `runtime` for process-level runtime ownership, provider/pool setup, and module assembly.- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.- If the required operation is absent after current entity/action and required field Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the generated library as a fallback.- Create each application-owned source file once. After its first compile attempt, repair only the smallest block identified by the exact compiler or test diagnostic. Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.- Before a repair that would replace more than 25% of an existing application file, stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and estimated scope. Initial creation and model-driven regeneration are not repairs.
Capability: `create`.
- Validate and allow-list writable business fields; never mass-assign dynamic JSON.- Create through the generated request/entity API, attach a non-empty audit reason, save with the same UserContext, and return the runtime's native save result.- Add a negative test proving a missing audit reason cannot write.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586<!-- ephemeral -->
# TypeScript Assist — Create `Order Item`
Use the exact generated `Q.orderItems()` entry point. Thetrusted `UserContext` supplies actor, tenant, policy, provider, and audit sink;none of those values may be accepted from the writable input.
```typescriptimport { UserContext } from '../teaql-ts';import { Q } from './Q';import { OrderItem } from './models/OrderItem';
export interface CreateOrderItemInput { customerOrder: string | number; productName: string; quantity: number; unitPrice: number;
}
export async function createOrderItem( input: CreateOrderItemInput, context: UserContext,): Promise<OrderItem> { const entity = Q.orderItems() .comment('what: initialize Order Item') .purpose('why: create Order Item') .newEntity(context);
entity.updateCustomerOrder(input.customerOrder); entity.updateProductName(input.productName); entity.updateQuantity(input.quantity); entity.updateUnitPrice(input.unitPrice);
await entity .auditAs('Create Order Item for the requested business operation') .save(context); return entity;}```
Only the generated updater methods above are writable. Constant relationcandidates, when present, are also generated and must be copied exactly:
Compile the result unchanged. Test persistence and query-back, and prove thatblank/missing intent, blank/missing audit reason, unknown fields, and attemptedtrusted-context overrides fail. Do not edit generated sources.
---
## TeaQL seven-language assist contract
Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated andruntime APIs. Discover APIs through the generated application AGENTS.md and progressivemodel-aware Assist. Do not inspect generated domain-library source.
- Do not create plurals by appending `s` or `es`; use the centralized generated plural.- Human and non-human entities use different generated predicate vocabularies. Preserve forms such as “who are active” and “whose email is”; never infer them from English.- Configure filters, projection, paging, and other query options before `purpose(...)`. Comment may appear anywhere in the chain. Purpose enters the executable stage; execution requires both values, but comment does not have to immediately precede purpose.- Every execute/list/stream and every save accepts exactly one context argument: `UserContext`. Name that argument `context`, never `runtime`; data services and global policy are injected when the context is built. Reserve `runtime` for process-level runtime ownership, provider/pool setup, and module assembly.- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.- If the required operation is absent after current entity/action and required field Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the generated library as a fallback.- Create each application-owned source file once. After its first compile attempt, repair only the smallest block identified by the exact compiler or test diagnostic. Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.- Before a repair that would replace more than 25% of an existing application file, stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and estimated scope. Initial creation and model-driven regeneration are not repairs.
Capability: `create`.
- Validate and allow-list writable business fields; never mass-assign dynamic JSON.- Create through the generated request/entity API, attach a non-empty audit reason, save with the same UserContext, and return the runtime's native save result.- Add a negative test proving a missing audit reason cannot write.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101<!-- ephemeral -->
# TeaQL safe SQL execution evidence (TypeScript)
Attach a trusted evidence store to the server-created SQL client and projectonly bounded fields before returning diagnostics to an application or CodingAgent.
```typescriptimport type { SQLExecutionMetadata, SQLExecutionOperation } from 'teaql-ts/sql/core';
export type SafeSQLExecutionEvidence = Readonly<{ operation: SQLExecutionOperation; parameterizedSQL: string; parameterCount: number; elapsedMicros: number; resultCount?: number; affectedRows?: number; resultSummary: string; traceChain?: SQLExecutionMetadata['traceChain']; tracePath: SQLExecutionMetadata['tracePath'];}>;
export function safeSQLEvidence( entries: readonly SQLExecutionMetadata[],): readonly SafeSQLExecutionEvidence[] { return entries.map(entry => Object.freeze({ operation: entry.operation, parameterizedSQL: entry.parameterizedSQL, parameterCount: entry.parameters.length, elapsedMicros: entry.elapsedMicros, resultCount: entry.resultCount, affectedRows: entry.affectedRows, resultSummary: entry.resultSummary, traceChain: entry.traceChain, tracePath: entry.tracePath, }));}```
Create `SQLExecutionEvidenceStore`, attach it with`client.setRuntimeTelemetrySink(store)`, and select `enableAll`, `enableSelect`,`enableMutation`, or `disable`. Mode changes clear earlier entries. Rawparameters, credentials, connection strings, and interpolated SQL remain insidethe trusted boundary and are intentionally absent above.
Query and mutation logs, including the text diagnostic sink, are enabled by default.The default sink is `new TextDiagnosticSQLLogSink()` and may bereplaced with `client.setDiagnosticSQLLogSink(...)`. Disable the two operationfamilies independently with`client.setQueryLoggingEnabled(false)` and`client.setMutationLoggingEnabled(false)`; passing `undefined` to`setDiagnosticSQLLogSink` removes operator output entirely. Each metadata entryretains structured `comment`, `purpose`, `auditReason`, typed multi-level`tracePath`, business `traceChain`, parameterized SQL, copy-paste `debugSQL`, elapsedtime, result count, and affected rows. `traceChain` follows the root purpose andrequest-parent comments, preserving both the native Q operation and a nestedexplicit/default comment. `tracePath` describes the physical provider/SQL route;do not derive one from the other or reconstruct either from SQL text. Runtimeevidence is policy-projected by default; keep that projection when exposing it.Explicit debug plaintext is not ordinary telemetry and must not leave the trusteddebugging boundary.
---
## TeaQL seven-language assist contract
Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated andruntime APIs. Discover APIs through the generated application AGENTS.md and progressivemodel-aware Assist. Do not inspect generated domain-library source.
- Do not create plurals by appending `s` or `es`; use the centralized generated plural.- Human and non-human entities use different generated predicate vocabularies. Preserve forms such as “who are active” and “whose email is”; never infer them from English.- Configure filters, projection, paging, and other query options before `purpose(...)`. Comment may appear anywhere in the chain. Purpose enters the executable stage; execution requires both values, but comment does not have to immediately precede purpose.- Every execute/list/stream and every save accepts exactly one context argument: `UserContext`. Name that argument `context`, never `runtime`; data services and global policy are injected when the context is built. Reserve `runtime` for process-level runtime ownership, provider/pool setup, and module assembly.- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.- If the required operation is absent after current entity/action and required field Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the generated library as a fallback.- Create each application-owned source file once. After its first compile attempt, repair only the smallest block identified by the exact compiler or test diagnostic. Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.- Before a repair that would replace more than 25% of an existing application file, stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and estimated scope. Initial creation and model-driven regeneration are not repairs.
Capability: `debug`.
- Capture purpose, comment, trace/correlation id, parameterized SQL summary, duration, row count, provider, and the runtime's native response when available.- Preserve the immutable row audit event and the customizable App Audit Sink as separate paths. Redact credentials, tokens, connection strings, and customer data.- Document only switches and hooks present in the selected runtime source.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135<!-- ephemeral -->
# TypeScript Assist — Expression `Customer Order`
The generated E facade preserves Value, loaded null/undefined, and NotLoaded.`eval()` returns a native value for the first two and throws`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hidesNotLoaded.
```typescriptimport { E } from './E';import { CustomerOrder } from './models/CustomerOrder';
export function extractId(entity: CustomerOrder) { return E.customerOrder(entity).id().eval();}
export function extractIdOrElse( entity: CustomerOrder, fallback: NonNullable<CustomerOrder['id']>,) { return E.customerOrder(entity).id().orElse(fallback);}
export function extractOrderNumber(entity: CustomerOrder) { return E.customerOrder(entity).orderNumber().eval();}
export function extractOrderNumberOrElse( entity: CustomerOrder, fallback: NonNullable<CustomerOrder['orderNumber']>,) { return E.customerOrder(entity).orderNumber().orElse(fallback);}
export function extractOrderDate(entity: CustomerOrder) { return E.customerOrder(entity).orderDate().eval();}
export function extractOrderDateOrElse( entity: CustomerOrder, fallback: NonNullable<CustomerOrder['orderDate']>,) { return E.customerOrder(entity).orderDate().orElse(fallback);}
export function extractTotalAmount(entity: CustomerOrder) { return E.customerOrder(entity).totalAmount().eval();}
export function extractTotalAmountOrElse( entity: CustomerOrder, fallback: NonNullable<CustomerOrder['totalAmount']>,) { return E.customerOrder(entity).totalAmount().orElse(fallback);}
export function extractVersion(entity: CustomerOrder) { return E.customerOrder(entity).version().eval();}
export function extractVersionOrElse( entity: CustomerOrder, fallback: NonNullable<CustomerOrder['version']>,) { return E.customerOrder(entity).version().orElse(fallback);}
export function extractCustomerId(entity: CustomerOrder) { return E.customerOrder(entity).customerId().eval();}
export function traverseCustomer(entity: CustomerOrder) { return E.customerOrder(entity).customer().eval();}
export function extractStatusId(entity: CustomerOrder) { return E.customerOrder(entity).statusId().eval();}
export function traverseStatus(entity: CustomerOrder) { return E.customerOrder(entity).status().eval();}
export function aggregateOrderItemListSize(entity: CustomerOrder) { return E.customerOrder(entity).orderItemList().size().eval();}
export function firstOrderItemListId(entity: CustomerOrder) { return E.customerOrder(entity).orderItemList().first().id().eval();}
export function getOrderItemListId(entity: CustomerOrder, index: number) { return E.customerOrder(entity).orderItemList().get(index).id().eval();}
```
Select every traversed field and relation. Never catch`TeaQLNotLoadedError` merely to supply a default, and never replace generated Eaccessors with optional chaining.
---
## TeaQL seven-language assist contract
Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated andruntime APIs. Discover APIs through the generated application AGENTS.md and progressivemodel-aware Assist. Do not inspect generated domain-library source.
- Do not create plurals by appending `s` or `es`; use the centralized generated plural.- Human and non-human entities use different generated predicate vocabularies. Preserve forms such as “who are active” and “whose email is”; never infer them from English.- Configure filters, projection, paging, and other query options before `purpose(...)`. Comment may appear anywhere in the chain. Purpose enters the executable stage; execution requires both values, but comment does not have to immediately precede purpose.- Every execute/list/stream and every save accepts exactly one context argument: `UserContext`. Name that argument `context`, never `runtime`; data services and global policy are injected when the context is built. Reserve `runtime` for process-level runtime ownership, provider/pool setup, and module assembly.- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.- If the required operation is absent after current entity/action and required field Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the generated library as a fallback.- Create each application-owned source file once. After its first compile attempt, repair only the smallest block identified by the exact compiler or test diagnostic. Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.- Before a repair that would replace more than 25% of an existing application file, stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and estimated scope. Initial creation and model-driven regeneration are not repairs.
Capability: `expression`.
- Distinguish a loaded null from a field or relation that was not projected. A NotLoaded/coding error must remain visible; do not turn it into an ordinary null.- Select every traversed relation first and use the generated E/expression API for scalar, object, and list traversal. Do not translate Java accessor names by guess..gitattributes+5
README.md+30-40
assets/dynamic-search-BBmdgl4H.jsAdded
assets/index-3Oa_Nwum.jsDeleted
assets/index-CSFBt0NB.jsDeleted
assets/index-DTZ5iA72.jsDeleted
assets/index-DmPc8xp3.cssDeleted-1
assets/index-LiMSU-HT.jsDeleted
assets/index-inj2slTy.cssDeleted-1
assets/main-gHLGx1pH.jsAdded+102
assets/object-location-xgYMemK6.jsAdded+1
assets/orders-CQOGX0kN.jsAdded
assets/style-SCdXWqgK.cssAdded+1
assets/index-BMClFIER.css → assets/workItems-5mJKEgxC.cssRenamed+1-1
assets/workItems-DraVJWt7.jsAdded+1
dist/assets/dynamic-search-BBmdgl4H.jsAdded
dist/assets/index-3Oa_Nwum.jsDeleted
dist/assets/index-CSFBt0NB.jsDeleted
dist/assets/index-DTZ5iA72.jsDeleted
dist/assets/index-DmPc8xp3.cssDeleted-1
dist/assets/index-LiMSU-HT.jsDeleted
dist/assets/index-inj2slTy.cssDeleted-1
dist/assets/main-gHLGx1pH.jsAdded+102
dist/assets/object-location-xgYMemK6.jsAdded+1
dist/assets/orders-CQOGX0kN.jsAdded
dist/assets/style-SCdXWqgK.cssAdded+1
dist/assets/index-BMClFIER.css → dist/assets/workItems-5mJKEgxC.cssRenamed+1-1
dist/assets/workItems-DraVJWt7.jsAdded+1
dist/index.html+138-41
dist/orders.htmlAdded+43
dist/work-items.htmlAdded+28
evidence/live-browser.jsonDeleted
evidence/local-browser.jsonDeleted
index.html+138-41
orders.htmlAdded+43
source/browser-sqlite/generated-order-hashes.jsonDeleted-22
source/browser-sqlite/scripts/verify-space.mjsDeleted-63
source/browser-sqlite/src/web-response.tsDeleted-16
source/browser-sqlite/vendor/teaql-teaql-0.3.0.tgzDeleted-3
source/provenance.json+12-54
source/teaql-ts/.npmignoreAdded+1
source/teaql-ts/LICENSEAdded+202
source/teaql-ts/README.mdAdded+369
source/teaql-ts/examples/browser-sqlite/AGENTS.mdAdded+10
source/teaql-ts/examples/browser-sqlite/README.mdAdded+118
source/teaql-ts/examples/browser-sqlite/assist/create-customer.mdAdded+82
source/teaql-ts/examples/browser-sqlite/assist/create-customer_order.mdAdded+92
source/teaql-ts/examples/browser-sqlite/assist/create-order_item.mdAdded+86
source/teaql-ts/examples/browser-sqlite/assist/debug.mdAdded+101
source/teaql-ts/examples/browser-sqlite/assist/expression-customer_order.mdAdded+135