philipgreat commited on
Commit
c793c14
·
verified ·
1 Parent(s): a5a71e1

Deploy generated Order console with request-tree TraceChain and reproducible runtime snapshot

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +54 -13
  2. assets/index-CSFBt0NB.js +0 -0
  3. assets/index-DmPc8xp3.css +1 -0
  4. dist/assets/index-CSFBt0NB.js +0 -0
  5. dist/assets/index-DmPc8xp3.css +1 -0
  6. dist/index.html +42 -41
  7. index.html +43 -17
  8. source/browser-sqlite/assist/create-customer.md +82 -0
  9. source/browser-sqlite/assist/create-customer_order.md +92 -0
  10. source/browser-sqlite/assist/create-order_item.md +86 -0
  11. source/browser-sqlite/assist/debug.md +101 -0
  12. source/browser-sqlite/assist/expression-customer_order.md +135 -0
  13. source/browser-sqlite/assist/query-customer_order.md +104 -0
  14. source/browser-sqlite/assist/query-customer_order.order_item_list.md +66 -0
  15. source/browser-sqlite/assist/query-customer_order.status.md +72 -0
  16. source/browser-sqlite/assist/query-order_item.md +97 -0
  17. source/browser-sqlite/assist/query-order_status.customer_order_list.md +66 -0
  18. source/browser-sqlite/assist/query-order_status.md +104 -0
  19. source/browser-sqlite/generated-order-hashes.json +22 -0
  20. source/browser-sqlite/index.html +44 -0
  21. source/browser-sqlite/order-model.xml +21 -0
  22. source/browser-sqlite/orders-lib/package.json +15 -0
  23. source/browser-sqlite/orders-lib/src/generated-bootstrap.ts +69 -0
  24. source/browser-sqlite/orders-lib/src/generated-search-models.ts +124 -0
  25. source/browser-sqlite/orders-lib/src/generated/E.ts +859 -0
  26. source/browser-sqlite/orders-lib/src/generated/Q.ts +44 -0
  27. source/browser-sqlite/orders-lib/src/generated/models/Customer.ts +252 -0
  28. source/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts +305 -0
  29. source/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts +231 -0
  30. source/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts +279 -0
  31. source/browser-sqlite/orders-lib/src/generated/models/Platform.ts +276 -0
  32. source/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts +1206 -0
  33. source/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts +795 -0
  34. source/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts +909 -0
  35. source/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts +1162 -0
  36. source/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts +791 -0
  37. source/browser-sqlite/orders-lib/src/runtime-module.ts +150 -0
  38. source/browser-sqlite/orders-lib/src/teaql-schemas.ts +34 -0
  39. source/browser-sqlite/orders-lib/src/teaql-ts.ts +308 -0
  40. source/browser-sqlite/orders-lib/teaql-i18n.json +128 -0
  41. source/browser-sqlite/orders-lib/tsconfig.json +12 -0
  42. source/browser-sqlite/package-lock.json +1624 -0
  43. source/browser-sqlite/package.json +20 -0
  44. source/browser-sqlite/scripts/smoke.mjs +130 -0
  45. source/browser-sqlite/src/main.ts +185 -0
  46. source/browser-sqlite/src/sqlite.worker.ts +4 -0
  47. source/browser-sqlite/src/style.css +14 -0
  48. source/browser-sqlite/src/web-response.ts +16 -0
  49. source/browser-sqlite/tsconfig.json +12 -0
  50. source/browser-sqlite/vendor/teaql-teaql-0.3.0.tgz +3 -0
README.md CHANGED
@@ -7,25 +7,66 @@ sdk: static
7
  app_file: dist/index.html
8
  pinned: false
9
  license: apache-2.0
10
- short_description: TeaQL and SQLite, entirely in your browser.
 
 
 
 
 
11
  ---
12
 
13
  # TeaQL Browser SQLite Playground
14
 
15
- This playground runs entirely inside your browser:
 
 
16
 
17
- - SQLite runs as WebAssembly in a dedicated Web Worker.
18
- - Generated TeaQL Q APIs execute against that browser-local database.
19
- - Demo records are created through audited generated mutation APIs.
20
- - Memory mode resets on refresh and gives every visitor the same starting point.
21
- - Optional OPFS mode persists data within the current browser origin when the host supports it.
22
- - Reset drops the local schema, recreates it, and seeds the demo again.
23
 
24
- There is no application backend and no server-side business database. The
25
- Space only serves static HTML, JavaScript, CSS, and WASM assets. Query and
26
- mutation data remain in the visitor's browser.
27
 
28
- The complete source and executable browser smoke test are maintained in the
29
- [`teaql-ts` browser-sqlite example](https://github.com/teaql/teaql-ts/tree/main/examples/browser-sqlite).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  Learn more at [teaql.io](https://teaql.io/).
 
7
  app_file: dist/index.html
8
  pinned: false
9
  license: apache-2.0
10
+ short_description: Typed queries and real TraceChain, entirely in your browser.
11
+ tags:
12
+ - teaql
13
+ - sqlite
14
+ - webassembly
15
+ - typescript
16
  ---
17
 
18
  # TeaQL Browser SQLite Playground
19
 
20
+ Edit a generated TypeScript Q query and inspect its data, facets and actual SQL
21
+ execution evidence. SQLite/WASM runs in a browser worker; there is no application
22
+ backend or server-side business database. Query data stays in your browser.
23
 
24
+ The deterministic fixture contains four synthetic orders, twenty items and three
25
+ statuses. The default query demonstrates filtered pagination, named totals,
26
+ status COUNT/SUM facets, status details and three-item previews with full counts.
27
+ Switch the example, edit the query, or restore the preset. Peggy parses a controlled
28
+ query AST; it does not evaluate arbitrary JavaScript, imports or assignments.
 
29
 
30
+ ## Request TraceChain
 
 
31
 
32
+ Each SQL record retains its root purpose, root comment, native Q-operation parents
33
+ and nested business comments. The browser only renders runtime `traceChain`;
34
+ physical `tracePath` remains separate. For example:
35
+
36
+ ```text
37
+ render order list page: load order list → selectStatusWith(...) → load status
38
+ render order list page: load order list → facetByStatusAs('statusCounts') → load status facets
39
+ ```
40
+
41
+ The table displays `Time | Identity | Trace chain | SQL`. Time is recorded execution
42
+ duration; Identity is the request entity, not an invented user or object ID. SQL is
43
+ the runtime's parameter-filled diagnostic text, with its masking policy intact.
44
+ An explicit execution observer retains evidence even when diagnostic logging is off.
45
+
46
+ ## Storage and reproducibility
47
+
48
+ Memory is the default and resets on refresh. Audited generated mutation APIs seed
49
+ the data; Reset recreates it. OPFS is enabled only when the hosting origin provides
50
+ cross-origin isolation. When unavailable on Hugging Face, the option is disabled
51
+ and memory mode remains fully usable.
52
+
53
+ This demo uses a tested **unreleased request-tree runtime snapshot**, based on
54
+ the [TeaQL TypeScript repository](https://github.com/teaql/teaql-ts). Its package
55
+ version remains 0.3.0; this is not a claim that published npm 0.3.0 contains the new
56
+ TraceChain design. Exact source, model, generated library, packaged runtime and
57
+ hashes are retained in [source](https://huggingface.co/spaces/teaql/browser-sqlite-playground/tree/main/source).
58
+
59
+ ```bash
60
+ hf download teaql/browser-sqlite-playground --repo-type space --include 'source/**' --local-dir teaql-demo
61
+ cd teaql-demo/source/browser-sqlite
62
+ npm ci
63
+ npm run build
64
+ npm run smoke
65
+ npm run dev
66
+ ```
67
+
68
+ The included browser test checks memory/OPFS, refresh/reset, logging modes, exact
69
+ facets/counts/previews, real TraceChain rows, query presets and rejected constructor
70
+ access. This first profile does not implement multi-tab coordination or true streaming.
71
 
72
  Learn more at [teaql.io](https://teaql.io/).
assets/index-CSFBt0NB.js ADDED
The diff for this file is too large to render. See raw diff
 
assets/index-DmPc8xp3.css ADDED
@@ -0,0 +1 @@
 
 
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}
dist/assets/index-CSFBt0NB.js ADDED
The diff for this file is too large to render. See raw diff
 
dist/assets/index-DmPc8xp3.css ADDED
@@ -0,0 +1 @@
 
 
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}
dist/index.html CHANGED
@@ -1,44 +1,45 @@
1
  <!doctype html>
2
  <html lang="en">
3
- <head>
4
- <meta charset="UTF-8" />
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
- <link rel="icon" href="data:," />
7
- <title>TeaQL Browser SQLite</title>
8
- <script type="module" crossorigin src="/assets/index-DTZ5iA72.js"></script>
9
- <link rel="stylesheet" crossorigin href="/assets/index-inj2slTy.css">
10
- </head>
11
- <body>
12
- <main>
13
- <p class="eyebrow">TEAQL TYPESCRIPT RUNTIME</p>
14
- <h1>Browser-local Data Service</h1>
15
- <p>Write the same generated Q API used by an application. Peggy parses it into a controlled AST; no arbitrary JavaScript is evaluated.</p>
16
- <p><strong>Everything runs in this browser.</strong> There is no application backend and no server-side business database.</p>
17
- <div class="controls">
18
- <label><input id="persist" type="checkbox" /> Persist locally with OPFS <span id="opfs-note"></span></label>
19
- <button id="reset">Reset demo data</button>
20
- </div>
21
- <p id="status">Starting SQLite/WASM…</p>
22
- <section class="query-panel">
23
- <div class="query-toolbar">
24
- <label for="preset">Example</label>
25
- <select id="preset">
26
- <option value="facet">Rows + relation facet</option>
27
- <option value="filter">String filter</option>
28
- <option value="all">Bounded list</option>
29
- </select>
30
- <button id="run" class="run">Run query</button>
31
- </div>
32
- <textarea id="query" spellcheck="false" aria-label="TeaQL query"></textarea>
33
- <p class="hint">Accepted input is the generated TypeScript Q API. Execution, imports, assignments, and browser APIs are not part of the grammar.</p>
34
- </section>
35
- <section class="response-panel">
36
- <div class="response-heading">
37
- <h2>Web Response</h2>
38
- <span>data · metadata · facets</span>
39
- </div>
40
- <pre id="result"></pre>
41
- </section>
42
- </main>
43
- </body>
 
44
  </html>
 
1
  <!doctype html>
2
  <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <link rel="icon" href="data:," />
7
+ <title>TeaQL browser order TraceChain</title>
8
+ <script type="module" crossorigin src="/assets/index-CSFBt0NB.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/assets/index-DmPc8xp3.css">
10
+ </head>
11
+ <body>
12
+ <main>
13
+ <p class="eyebrow">GENERATED Q + E · SQLITE/WASM · NO BACKEND</p>
14
+ <h1>Order query evidence</h1>
15
+ <p>One filtered page, named total, status facets and bounded item previews.</p>
16
+ <p>Entirely browser-local · SQLite/WASM · Generated typed Order Q/E APIs</p>
17
+ <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>
18
+ <div class="controls">
19
+ <label><input id="persist" type="checkbox" /> Persist locally with OPFS <span id="opfs-note"></span></label>
20
+ <label><input id="logging" type="checkbox" checked /> Diagnostic logging</label>
21
+ <button id="reset">Reset demo data</button>
22
+ </div>
23
+ <label for="example">Example query</label>
24
+ <select id="example"><option value="filtered">Filtered order page</option><option value="all">All orders</option></select>
25
+ <label for="search">Editable generated TypeScript Q API, parsed into a controlled AST</label>
26
+ <textarea id="search" rows="20" spellcheck="false" style="display:block;width:100%;margin:12px 0"></textarea>
27
+ <p>No eval, imports, assignments or arbitrary JavaScript execution.</p>
28
+ <button id="query">Run query</button>
29
+ <button id="preset">Restore example search</button>
30
+ <p id="status">Starting SQLite/WASM…</p>
31
+ <h2>Response data and metadata</h2>
32
+ <pre id="result"></pre>
33
+ <h2>SQL execution evidence</h2>
34
+ <p>Time is the recorded execution duration. Identity is the request entity from tracePath, not a user or object ID.</p>
35
+ <div class="evidence-scroll">
36
+ <table class="evidence-table">
37
+ <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>
38
+ <tbody id="evidence-rows"></tbody>
39
+ </table>
40
+ </div>
41
+ <details><summary>Business TraceChain as text</summary><pre id="trace"></pre></details>
42
+ <details><summary>Runtime metadata and physical tracePath</summary><pre id="sql"></pre></details>
43
+ </main>
44
+ </body>
45
  </html>
index.html CHANGED
@@ -1,19 +1,45 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <link rel="icon" href="data:," />
7
+ <title>TeaQL browser order TraceChain</title>
8
+ <script type="module" crossorigin src="/assets/index-CSFBt0NB.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/assets/index-DmPc8xp3.css">
10
+ </head>
11
+ <body>
12
+ <main>
13
+ <p class="eyebrow">GENERATED Q + E · SQLITE/WASM · NO BACKEND</p>
14
+ <h1>Order query evidence</h1>
15
+ <p>One filtered page, named total, status facets and bounded item previews.</p>
16
+ <p>Entirely browser-local · SQLite/WASM · Generated typed Order Q/E APIs</p>
17
+ <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>
18
+ <div class="controls">
19
+ <label><input id="persist" type="checkbox" /> Persist locally with OPFS <span id="opfs-note"></span></label>
20
+ <label><input id="logging" type="checkbox" checked /> Diagnostic logging</label>
21
+ <button id="reset">Reset demo data</button>
22
+ </div>
23
+ <label for="example">Example query</label>
24
+ <select id="example"><option value="filtered">Filtered order page</option><option value="all">All orders</option></select>
25
+ <label for="search">Editable generated TypeScript Q API, parsed into a controlled AST</label>
26
+ <textarea id="search" rows="20" spellcheck="false" style="display:block;width:100%;margin:12px 0"></textarea>
27
+ <p>No eval, imports, assignments or arbitrary JavaScript execution.</p>
28
+ <button id="query">Run query</button>
29
+ <button id="preset">Restore example search</button>
30
+ <p id="status">Starting SQLite/WASM…</p>
31
+ <h2>Response data and metadata</h2>
32
+ <pre id="result"></pre>
33
+ <h2>SQL execution evidence</h2>
34
+ <p>Time is the recorded execution duration. Identity is the request entity from tracePath, not a user or object ID.</p>
35
+ <div class="evidence-scroll">
36
+ <table class="evidence-table">
37
+ <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>
38
+ <tbody id="evidence-rows"></tbody>
39
+ </table>
40
+ </div>
41
+ <details><summary>Business TraceChain as text</summary><pre id="trace"></pre></details>
42
+ <details><summary>Runtime metadata and physical tracePath</summary><pre id="sql"></pre></details>
43
+ </main>
44
+ </body>
45
  </html>
source/browser-sqlite/assist/create-customer.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Assist — Create `Customer`
4
+
5
+ Use the exact generated `Q.customers()` entry point. The
6
+ trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink;
7
+ none of those values may be accepted from the writable input.
8
+
9
+ ```typescript
10
+ import { UserContext } from '../teaql-ts';
11
+ import { Q } from './Q';
12
+ import { Customer } from './models/Customer';
13
+
14
+ export interface CreateCustomerInput {
15
+ platform: string | number;
16
+ name: string;
17
+
18
+ }
19
+
20
+ export async function createCustomer(
21
+ input: CreateCustomerInput,
22
+ context: UserContext,
23
+ ): Promise<Customer> {
24
+ const entity = Q.customers()
25
+ .comment('what: initialize Customer')
26
+ .purpose('why: create Customer')
27
+ .newEntity(context);
28
+
29
+ entity.updatePlatform(input.platform);
30
+ entity.updateName(input.name);
31
+
32
+ await entity
33
+ .auditAs('Create Customer for the requested business operation')
34
+ .save(context);
35
+ return entity;
36
+ }
37
+ ```
38
+
39
+ Only the generated updater methods above are writable. Constant relation
40
+ candidates, when present, are also generated and must be copied exactly:
41
+
42
+ Compile the result unchanged. Test persistence and query-back, and prove that
43
+ blank/missing intent, blank/missing audit reason, unknown fields, and attempted
44
+ trusted-context overrides fail. Do not edit generated sources.
45
+
46
+
47
+ ---
48
+
49
+ ## TeaQL seven-language assist contract
50
+
51
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
52
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
53
+ model-aware Assist. Do not inspect generated domain-library source.
54
+
55
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
56
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
57
+ forms such as “who are active” and “whose email is”; never infer them from English.
58
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
59
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
60
+ requires both values, but comment does not have to immediately precede purpose.
61
+ - Every execute/list/stream and every save accepts exactly one context argument:
62
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
63
+ policy are injected when the context is built. Reserve `runtime` for process-level
64
+ runtime ownership, provider/pool setup, and module assembly.
65
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
66
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
67
+ - If the required operation is absent after current entity/action and required field
68
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
69
+ generated library as a fallback.
70
+ - Create each application-owned source file once. After its first compile attempt,
71
+ repair only the smallest block identified by the exact compiler or test diagnostic.
72
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
73
+ - Before a repair that would replace more than 25% of an existing application file,
74
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
75
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
76
+
77
+ Capability: `create`.
78
+
79
+ - Validate and allow-list writable business fields; never mass-assign dynamic JSON.
80
+ - Create through the generated request/entity API, attach a non-empty audit reason,
81
+ save with the same UserContext, and return the runtime's native save result.
82
+ - Add a negative test proving a missing audit reason cannot write.
source/browser-sqlite/assist/create-customer_order.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Assist — Create `Customer Order`
4
+
5
+ Use the exact generated `Q.customerOrders()` entry point. The
6
+ trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink;
7
+ none of those values may be accepted from the writable input.
8
+
9
+ ```typescript
10
+ import { UserContext } from '../teaql-ts';
11
+ import { Q } from './Q';
12
+ import { CustomerOrder } from './models/CustomerOrder';
13
+
14
+ export interface CreateCustomerOrderInput {
15
+ customer: string | number;
16
+ status: string | number;
17
+ orderNumber: string;
18
+ orderDate: string;
19
+ totalAmount: number;
20
+
21
+ }
22
+
23
+ export async function createCustomerOrder(
24
+ input: CreateCustomerOrderInput,
25
+ context: UserContext,
26
+ ): Promise<CustomerOrder> {
27
+ const entity = Q.customerOrders()
28
+ .comment('what: initialize Customer Order')
29
+ .purpose('why: create Customer Order')
30
+ .newEntity(context);
31
+
32
+ entity.updateCustomer(input.customer);
33
+ entity.updateStatus(input.status);
34
+ entity.updateOrderNumber(input.orderNumber);
35
+ entity.updateOrderDate(input.orderDate);
36
+ entity.updateTotalAmount(input.totalAmount);
37
+
38
+ await entity
39
+ .auditAs('Create Customer Order for the requested business operation')
40
+ .save(context);
41
+ return entity;
42
+ }
43
+ ```
44
+
45
+ Only the generated updater methods above are writable. Constant relation
46
+ candidates, when present, are also generated and must be copied exactly:
47
+ - `updateStatusToNew()`
48
+ - `updateStatusToPaid()`
49
+ - `updateStatusToCancelled()`
50
+
51
+
52
+ Compile the result unchanged. Test persistence and query-back, and prove that
53
+ blank/missing intent, blank/missing audit reason, unknown fields, and attempted
54
+ trusted-context overrides fail. Do not edit generated sources.
55
+
56
+
57
+ ---
58
+
59
+ ## TeaQL seven-language assist contract
60
+
61
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
62
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
63
+ model-aware Assist. Do not inspect generated domain-library source.
64
+
65
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
66
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
67
+ forms such as “who are active” and “whose email is”; never infer them from English.
68
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
69
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
70
+ requires both values, but comment does not have to immediately precede purpose.
71
+ - Every execute/list/stream and every save accepts exactly one context argument:
72
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
73
+ policy are injected when the context is built. Reserve `runtime` for process-level
74
+ runtime ownership, provider/pool setup, and module assembly.
75
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
76
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
77
+ - If the required operation is absent after current entity/action and required field
78
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
79
+ generated library as a fallback.
80
+ - Create each application-owned source file once. After its first compile attempt,
81
+ repair only the smallest block identified by the exact compiler or test diagnostic.
82
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
83
+ - Before a repair that would replace more than 25% of an existing application file,
84
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
85
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
86
+
87
+ Capability: `create`.
88
+
89
+ - Validate and allow-list writable business fields; never mass-assign dynamic JSON.
90
+ - Create through the generated request/entity API, attach a non-empty audit reason,
91
+ save with the same UserContext, and return the runtime's native save result.
92
+ - Add a negative test proving a missing audit reason cannot write.
source/browser-sqlite/assist/create-order_item.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Assist — Create `Order Item`
4
+
5
+ Use the exact generated `Q.orderItems()` entry point. The
6
+ trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink;
7
+ none of those values may be accepted from the writable input.
8
+
9
+ ```typescript
10
+ import { UserContext } from '../teaql-ts';
11
+ import { Q } from './Q';
12
+ import { OrderItem } from './models/OrderItem';
13
+
14
+ export interface CreateOrderItemInput {
15
+ customerOrder: string | number;
16
+ productName: string;
17
+ quantity: number;
18
+ unitPrice: number;
19
+
20
+ }
21
+
22
+ export async function createOrderItem(
23
+ input: CreateOrderItemInput,
24
+ context: UserContext,
25
+ ): Promise<OrderItem> {
26
+ const entity = Q.orderItems()
27
+ .comment('what: initialize Order Item')
28
+ .purpose('why: create Order Item')
29
+ .newEntity(context);
30
+
31
+ entity.updateCustomerOrder(input.customerOrder);
32
+ entity.updateProductName(input.productName);
33
+ entity.updateQuantity(input.quantity);
34
+ entity.updateUnitPrice(input.unitPrice);
35
+
36
+ await entity
37
+ .auditAs('Create Order Item for the requested business operation')
38
+ .save(context);
39
+ return entity;
40
+ }
41
+ ```
42
+
43
+ Only the generated updater methods above are writable. Constant relation
44
+ candidates, when present, are also generated and must be copied exactly:
45
+
46
+ Compile the result unchanged. Test persistence and query-back, and prove that
47
+ blank/missing intent, blank/missing audit reason, unknown fields, and attempted
48
+ trusted-context overrides fail. Do not edit generated sources.
49
+
50
+
51
+ ---
52
+
53
+ ## TeaQL seven-language assist contract
54
+
55
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
56
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
57
+ model-aware Assist. Do not inspect generated domain-library source.
58
+
59
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
60
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
61
+ forms such as “who are active” and “whose email is”; never infer them from English.
62
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
63
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
64
+ requires both values, but comment does not have to immediately precede purpose.
65
+ - Every execute/list/stream and every save accepts exactly one context argument:
66
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
67
+ policy are injected when the context is built. Reserve `runtime` for process-level
68
+ runtime ownership, provider/pool setup, and module assembly.
69
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
70
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
71
+ - If the required operation is absent after current entity/action and required field
72
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
73
+ generated library as a fallback.
74
+ - Create each application-owned source file once. After its first compile attempt,
75
+ repair only the smallest block identified by the exact compiler or test diagnostic.
76
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
77
+ - Before a repair that would replace more than 25% of an existing application file,
78
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
79
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
80
+
81
+ Capability: `create`.
82
+
83
+ - Validate and allow-list writable business fields; never mass-assign dynamic JSON.
84
+ - Create through the generated request/entity API, attach a non-empty audit reason,
85
+ save with the same UserContext, and return the runtime's native save result.
86
+ - Add a negative test proving a missing audit reason cannot write.
source/browser-sqlite/assist/debug.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TeaQL safe SQL execution evidence (TypeScript)
4
+
5
+ Attach a trusted evidence store to the server-created SQL client and project
6
+ only bounded fields before returning diagnostics to an application or Coding
7
+ Agent.
8
+
9
+ ```typescript
10
+ import type { SQLExecutionMetadata, SQLExecutionOperation } from 'teaql-ts/sql/core';
11
+
12
+ export type SafeSQLExecutionEvidence = Readonly<{
13
+ operation: SQLExecutionOperation;
14
+ parameterizedSQL: string;
15
+ parameterCount: number;
16
+ elapsedMicros: number;
17
+ resultCount?: number;
18
+ affectedRows?: number;
19
+ resultSummary: string;
20
+ traceChain?: SQLExecutionMetadata['traceChain'];
21
+ tracePath: SQLExecutionMetadata['tracePath'];
22
+ }>;
23
+
24
+ export function safeSQLEvidence(
25
+ entries: readonly SQLExecutionMetadata[],
26
+ ): readonly SafeSQLExecutionEvidence[] {
27
+ return entries.map(entry => Object.freeze({
28
+ operation: entry.operation,
29
+ parameterizedSQL: entry.parameterizedSQL,
30
+ parameterCount: entry.parameters.length,
31
+ elapsedMicros: entry.elapsedMicros,
32
+ resultCount: entry.resultCount,
33
+ affectedRows: entry.affectedRows,
34
+ resultSummary: entry.resultSummary,
35
+ traceChain: entry.traceChain,
36
+ tracePath: entry.tracePath,
37
+ }));
38
+ }
39
+ ```
40
+
41
+ Create `SQLExecutionEvidenceStore`, attach it with
42
+ `client.setRuntimeTelemetrySink(store)`, and select `enableAll`, `enableSelect`,
43
+ `enableMutation`, or `disable`. Mode changes clear earlier entries. Raw
44
+ parameters, credentials, connection strings, and interpolated SQL remain inside
45
+ the trusted boundary and are intentionally absent above.
46
+
47
+ Query and mutation logs, including the text diagnostic sink, are enabled by default.
48
+ The default sink is `new TextDiagnosticSQLLogSink()` and may be
49
+ replaced with `client.setDiagnosticSQLLogSink(...)`. Disable the two operation
50
+ families independently with
51
+ `client.setQueryLoggingEnabled(false)` and
52
+ `client.setMutationLoggingEnabled(false)`; passing `undefined` to
53
+ `setDiagnosticSQLLogSink` removes operator output entirely. Each metadata entry
54
+ retains structured `comment`, `purpose`, `auditReason`, typed multi-level
55
+ `tracePath`, business `traceChain`, parameterized SQL, copy-paste `debugSQL`, elapsed
56
+ time, result count, and affected rows. `traceChain` follows the root purpose and
57
+ request-parent comments, preserving both the native Q operation and a nested
58
+ explicit/default comment. `tracePath` describes the physical provider/SQL route;
59
+ do not derive one from the other or reconstruct either from SQL text. Runtime
60
+ evidence is policy-projected by default; keep that projection when exposing it.
61
+ Explicit debug plaintext is not ordinary telemetry and must not leave the trusted
62
+ debugging boundary.
63
+
64
+
65
+ ---
66
+
67
+ ## TeaQL seven-language assist contract
68
+
69
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
70
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
71
+ model-aware Assist. Do not inspect generated domain-library source.
72
+
73
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
74
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
75
+ forms such as “who are active” and “whose email is”; never infer them from English.
76
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
77
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
78
+ requires both values, but comment does not have to immediately precede purpose.
79
+ - Every execute/list/stream and every save accepts exactly one context argument:
80
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
81
+ policy are injected when the context is built. Reserve `runtime` for process-level
82
+ runtime ownership, provider/pool setup, and module assembly.
83
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
84
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
85
+ - If the required operation is absent after current entity/action and required field
86
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
87
+ generated library as a fallback.
88
+ - Create each application-owned source file once. After its first compile attempt,
89
+ repair only the smallest block identified by the exact compiler or test diagnostic.
90
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
91
+ - Before a repair that would replace more than 25% of an existing application file,
92
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
93
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
94
+
95
+ Capability: `debug`.
96
+
97
+ - Capture purpose, comment, trace/correlation id, parameterized SQL summary,
98
+ duration, row count, provider, and the runtime's native response when available.
99
+ - Preserve the immutable row audit event and the customizable App Audit Sink as
100
+ separate paths. Redact credentials, tokens, connection strings, and customer data.
101
+ - Document only switches and hooks present in the selected runtime source.
source/browser-sqlite/assist/expression-customer_order.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Assist — Expression `Customer Order`
4
+
5
+ The generated E facade preserves Value, loaded null/undefined, and NotLoaded.
6
+ `eval()` returns a native value for the first two and throws
7
+ `TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides
8
+ NotLoaded.
9
+
10
+ ```typescript
11
+ import { E } from './E';
12
+ import { CustomerOrder } from './models/CustomerOrder';
13
+
14
+ export function extractId(entity: CustomerOrder) {
15
+ return E.customerOrder(entity).id().eval();
16
+ }
17
+
18
+ export function extractIdOrElse(
19
+ entity: CustomerOrder, fallback: NonNullable<CustomerOrder['id']>,
20
+ ) {
21
+ return E.customerOrder(entity).id().orElse(fallback);
22
+ }
23
+
24
+ export function extractOrderNumber(entity: CustomerOrder) {
25
+ return E.customerOrder(entity).orderNumber().eval();
26
+ }
27
+
28
+ export function extractOrderNumberOrElse(
29
+ entity: CustomerOrder, fallback: NonNullable<CustomerOrder['orderNumber']>,
30
+ ) {
31
+ return E.customerOrder(entity).orderNumber().orElse(fallback);
32
+ }
33
+
34
+ export function extractOrderDate(entity: CustomerOrder) {
35
+ return E.customerOrder(entity).orderDate().eval();
36
+ }
37
+
38
+ export function extractOrderDateOrElse(
39
+ entity: CustomerOrder, fallback: NonNullable<CustomerOrder['orderDate']>,
40
+ ) {
41
+ return E.customerOrder(entity).orderDate().orElse(fallback);
42
+ }
43
+
44
+ export function extractTotalAmount(entity: CustomerOrder) {
45
+ return E.customerOrder(entity).totalAmount().eval();
46
+ }
47
+
48
+ export function extractTotalAmountOrElse(
49
+ entity: CustomerOrder, fallback: NonNullable<CustomerOrder['totalAmount']>,
50
+ ) {
51
+ return E.customerOrder(entity).totalAmount().orElse(fallback);
52
+ }
53
+
54
+ export function extractVersion(entity: CustomerOrder) {
55
+ return E.customerOrder(entity).version().eval();
56
+ }
57
+
58
+ export function extractVersionOrElse(
59
+ entity: CustomerOrder, fallback: NonNullable<CustomerOrder['version']>,
60
+ ) {
61
+ return E.customerOrder(entity).version().orElse(fallback);
62
+ }
63
+
64
+ export function extractCustomerId(entity: CustomerOrder) {
65
+ return E.customerOrder(entity).customerId().eval();
66
+ }
67
+
68
+ export function traverseCustomer(entity: CustomerOrder) {
69
+ return E.customerOrder(entity).customer().eval();
70
+ }
71
+
72
+ export function extractStatusId(entity: CustomerOrder) {
73
+ return E.customerOrder(entity).statusId().eval();
74
+ }
75
+
76
+ export function traverseStatus(entity: CustomerOrder) {
77
+ return E.customerOrder(entity).status().eval();
78
+ }
79
+
80
+ export function aggregateOrderItemListSize(entity: CustomerOrder) {
81
+ return E.customerOrder(entity).orderItemList().size().eval();
82
+ }
83
+
84
+ export function firstOrderItemListId(entity: CustomerOrder) {
85
+ return E.customerOrder(entity).orderItemList().first().id().eval();
86
+ }
87
+
88
+ export function getOrderItemListId(entity: CustomerOrder, index: number) {
89
+ return E.customerOrder(entity).orderItemList().get(index).id().eval();
90
+ }
91
+
92
+
93
+ ```
94
+
95
+ Select every traversed field and relation. Never catch
96
+ `TeaQLNotLoadedError` merely to supply a default, and never replace generated E
97
+ accessors with optional chaining.
98
+
99
+
100
+ ---
101
+
102
+ ## TeaQL seven-language assist contract
103
+
104
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
105
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
106
+ model-aware Assist. Do not inspect generated domain-library source.
107
+
108
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
109
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
110
+ forms such as “who are active” and “whose email is”; never infer them from English.
111
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
112
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
113
+ requires both values, but comment does not have to immediately precede purpose.
114
+ - Every execute/list/stream and every save accepts exactly one context argument:
115
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
116
+ policy are injected when the context is built. Reserve `runtime` for process-level
117
+ runtime ownership, provider/pool setup, and module assembly.
118
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
119
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
120
+ - If the required operation is absent after current entity/action and required field
121
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
122
+ generated library as a fallback.
123
+ - Create each application-owned source file once. After its first compile attempt,
124
+ repair only the smallest block identified by the exact compiler or test diagnostic.
125
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
126
+ - Before a repair that would replace more than 25% of an existing application file,
127
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
128
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
129
+
130
+ Capability: `expression`.
131
+
132
+ - Distinguish a loaded null from a field or relation that was not projected. A
133
+ NotLoaded/coding error must remain visible; do not turn it into an ordinary null.
134
+ - Select every traversed relation first and use the generated E/expression API for
135
+ scalar, object, and list traversal. Do not translate Java accessor names by guess.
source/browser-sqlite/assist/query-customer_order.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Assist — Query `Customer Order`
4
+
5
+ Use the exact generated `Q.customerOrdersWithMinimalFields()`
6
+ entry point. Trusted runtime and policy state comes only from `UserContext`.
7
+
8
+ ```typescript
9
+ import { Q } from './Q';
10
+ import { CustomerOrder } from './models/CustomerOrder';
11
+ import { SmartList, UserContext } from '../teaql-ts';
12
+
13
+ export async function queryCustomerOrderById(
14
+ context: UserContext,
15
+ entityId: string,
16
+ ): Promise<SmartList<CustomerOrder>> {
17
+ return Q.customerOrdersWithMinimalFields()
18
+ .withIdIs(entityId)
19
+ .orderByIdAscending()
20
+ .limit(20)
21
+ .comment('what: load the requested Customer Order row')
22
+ .purpose('why: serve the authorized Customer Order view')
23
+ .executeForList(context);
24
+ }
25
+ ```
26
+
27
+ Compile and execute this source unchanged. Use only generated projection,
28
+ predicate, ordering, and relation-selection APIs. Missing or blank intent,
29
+ unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated
30
+ relation loading rather than handwritten child-query loops; never guess a plural.
31
+
32
+
33
+ ## Field-specific Query Assist
34
+
35
+ Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column.
36
+
37
+ | KSML field | Type | Field help |
38
+ | --- | --- | --- |
39
+ | `id` | `id` | `typescript-assist-query/customer_order.id` |
40
+ | `customer` | `relation<customer>` | `typescript-assist-query/customer_order.customer` |
41
+ | `status` | `relation<order_status>` | `typescript-assist-query/customer_order.status` |
42
+ | `order_number` | `string` | `typescript-assist-query/customer_order.order_number` |
43
+ | `order_date` | `date` | `typescript-assist-query/customer_order.order_date` |
44
+ | `total_amount` | `number` | `typescript-assist-query/customer_order.total_amount` |
45
+ | `version` | `version` | `typescript-assist-query/customer_order.version` |
46
+
47
+ Generated reverse relations are derived from referencing KSML fields. Use their exact generated location for relation selection and access:
48
+
49
+ | Generated reverse relation | Child entity | Field help |
50
+ | --- | --- | --- |
51
+ | `order_item_list` | `order_item` | `typescript-assist-query/customer_order.order_item_list` |
52
+
53
+
54
+ ---
55
+
56
+ ## TeaQL seven-language assist contract
57
+
58
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
59
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
60
+ model-aware Assist. Do not inspect generated domain-library source.
61
+
62
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
63
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
64
+ forms such as “who are active” and “whose email is”; never infer them from English.
65
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
66
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
67
+ requires both values, but comment does not have to immediately precede purpose.
68
+ - Every execute/list/stream and every save accepts exactly one context argument:
69
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
70
+ policy are injected when the context is built. Reserve `runtime` for process-level
71
+ runtime ownership, provider/pool setup, and module assembly.
72
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
73
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
74
+ - If the required operation is absent after current entity/action and required field
75
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
76
+ generated library as a fallback.
77
+ - Create each application-owned source file once. After its first compile attempt,
78
+ repair only the smallest block identified by the exact compiler or test diagnostic.
79
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
80
+ - Before a repair that would replace more than 25% of an existing application file,
81
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
82
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
83
+
84
+ Capability: `query`.
85
+
86
+ - Use generated projection, relation, predicate, sort, and aggregate APIs; never
87
+ concatenate application SQL or silently ignore an unsupported filter.
88
+ - Rows, record count, facets, and aggregates must share the same active filter.
89
+ - Add negative tests for missing purpose/comment and forbidden dynamic fields.
90
+
91
+ ### Optional per-parent Top-N optimization
92
+
93
+ - Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution
94
+ stage. Use the field-specific relation Assist for the exact generated selector.
95
+ - Give the child a per-parent limit and deterministic ordering with an ID tie-breaker;
96
+ bound the parent query separately. A single-parent detail query is not batch Top-N.
97
+ - Server providers default to a window query (`threshold = 0`). A positive threshold
98
+ permits bounded probes only when the already-loaded parent count is at or below it;
99
+ above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default.
100
+ - Measure before opting in. Do not infer a threshold from table size or execute COUNT
101
+ or statistics queries to choose a plan. Keep an index on foreign key + sort + ID.
102
+ - Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry.
103
+ Runtime-managed probes are not application-owned N+1 loops; neither strategy changes
104
+ authorization, loaded-state semantics or the required comment/purpose.
source/browser-sqlite/assist/query-customer_order.order_item_list.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # Query Reverse-Relation Assist — `customer_order.order_item_list`
4
+
5
+ KSML entity: `customer_order`
6
+ Derived reverse relation: `order_item_list`
7
+ Child entity: `order_item`
8
+
9
+ | Capability | Generated API |
10
+ | --- | --- |
11
+ | Select | `.selectOrderItemListWith(Q.orderItemsWithMinimalFields())` |
12
+
13
+ Reverse relations are model-derived and never perform an implicit database query. Select the relation explicitly before expression access. Apply query methods before the executable purpose stage, then execute with exactly one trusted context.
14
+
15
+
16
+ ---
17
+
18
+ ## TeaQL seven-language assist contract
19
+
20
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
21
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
22
+ model-aware Assist. Do not inspect generated domain-library source.
23
+
24
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
25
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
26
+ forms such as “who are active” and “whose email is”; never infer them from English.
27
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
28
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
29
+ requires both values, but comment does not have to immediately precede purpose.
30
+ - Every execute/list/stream and every save accepts exactly one context argument:
31
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
32
+ policy are injected when the context is built. Reserve `runtime` for process-level
33
+ runtime ownership, provider/pool setup, and module assembly.
34
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
35
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
36
+ - If the required operation is absent after current entity/action and required field
37
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
38
+ generated library as a fallback.
39
+ - Create each application-owned source file once. After its first compile attempt,
40
+ repair only the smallest block identified by the exact compiler or test diagnostic.
41
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
42
+ - Before a repair that would replace more than 25% of an existing application file,
43
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
44
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
45
+
46
+ Capability: `query`.
47
+
48
+ - Use generated projection, relation, predicate, sort, and aggregate APIs; never
49
+ concatenate application SQL or silently ignore an unsupported filter.
50
+ - Rows, record count, facets, and aggregates must share the same active filter.
51
+ - Add negative tests for missing purpose/comment and forbidden dynamic fields.
52
+
53
+ ### Optional per-parent Top-N optimization
54
+
55
+ - Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution
56
+ stage. Use the field-specific relation Assist for the exact generated selector.
57
+ - Give the child a per-parent limit and deterministic ordering with an ID tie-breaker;
58
+ bound the parent query separately. A single-parent detail query is not batch Top-N.
59
+ - Server providers default to a window query (`threshold = 0`). A positive threshold
60
+ permits bounded probes only when the already-loaded parent count is at or below it;
61
+ above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default.
62
+ - Measure before opting in. Do not infer a threshold from table size or execute COUNT
63
+ or statistics queries to choose a plan. Keep an index on foreign key + sort + ID.
64
+ - Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry.
65
+ Runtime-managed probes are not application-owned N+1 loops; neither strategy changes
66
+ authorization, loaded-state semantics or the required comment/purpose.
source/browser-sqlite/assist/query-customer_order.status.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Query Field Assist — `customer_order.status`
4
+
5
+ KSML entity: `Customer Order`
6
+ KSML field: `Order Status`
7
+ Type: `Order Status`
8
+
9
+ | Capability | Generated API |
10
+ | --- | --- |
11
+ | Select | `selectStatusWith(request)`` |
12
+ | Filter identity | `withStatusIs(id)`, `withStatusIn(ids)` |
13
+ | Filter nested request | `withStatusMatching(request)`, `withoutStatusMatching(request)` |
14
+ | Constant | `withStatusIs()` |
15
+ | Constant | `withStatusIs()` |
16
+ | Constant | `withStatusIs()` |
17
+ | Group | `groupByStatus()`, `groupByStatusAs(alias)` |
18
+ | Facet | `facetByStatusAs(name, request, includeAllFacets)` |
19
+ Execution requires `comment(...)`, `purpose(...)`, and exactly one `context`.
20
+
21
+
22
+ ---
23
+
24
+ ## TeaQL seven-language assist contract
25
+
26
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
27
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
28
+ model-aware Assist. Do not inspect generated domain-library source.
29
+
30
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
31
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
32
+ forms such as “who are active” and “whose email is”; never infer them from English.
33
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
34
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
35
+ requires both values, but comment does not have to immediately precede purpose.
36
+ - Every execute/list/stream and every save accepts exactly one context argument:
37
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
38
+ policy are injected when the context is built. Reserve `runtime` for process-level
39
+ runtime ownership, provider/pool setup, and module assembly.
40
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
41
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
42
+ - If the required operation is absent after current entity/action and required field
43
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
44
+ generated library as a fallback.
45
+ - Create each application-owned source file once. After its first compile attempt,
46
+ repair only the smallest block identified by the exact compiler or test diagnostic.
47
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
48
+ - Before a repair that would replace more than 25% of an existing application file,
49
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
50
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
51
+
52
+ Capability: `query`.
53
+
54
+ - Use generated projection, relation, predicate, sort, and aggregate APIs; never
55
+ concatenate application SQL or silently ignore an unsupported filter.
56
+ - Rows, record count, facets, and aggregates must share the same active filter.
57
+ - Add negative tests for missing purpose/comment and forbidden dynamic fields.
58
+
59
+ ### Optional per-parent Top-N optimization
60
+
61
+ - Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution
62
+ stage. Use the field-specific relation Assist for the exact generated selector.
63
+ - Give the child a per-parent limit and deterministic ordering with an ID tie-breaker;
64
+ bound the parent query separately. A single-parent detail query is not batch Top-N.
65
+ - Server providers default to a window query (`threshold = 0`). A positive threshold
66
+ permits bounded probes only when the already-loaded parent count is at or below it;
67
+ above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default.
68
+ - Measure before opting in. Do not infer a threshold from table size or execute COUNT
69
+ or statistics queries to choose a plan. Keep an index on foreign key + sort + ID.
70
+ - Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry.
71
+ Runtime-managed probes are not application-owned N+1 loops; neither strategy changes
72
+ authorization, loaded-state semantics or the required comment/purpose.
source/browser-sqlite/assist/query-order_item.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Assist — Query `Order Item`
4
+
5
+ Use the exact generated `Q.orderItemsWithMinimalFields()`
6
+ entry point. Trusted runtime and policy state comes only from `UserContext`.
7
+
8
+ ```typescript
9
+ import { Q } from './Q';
10
+ import { OrderItem } from './models/OrderItem';
11
+ import { SmartList, UserContext } from '../teaql-ts';
12
+
13
+ export async function queryOrderItemById(
14
+ context: UserContext,
15
+ entityId: string,
16
+ ): Promise<SmartList<OrderItem>> {
17
+ return Q.orderItemsWithMinimalFields()
18
+ .withIdIs(entityId)
19
+ .orderByIdAscending()
20
+ .limit(20)
21
+ .comment('what: load the requested Order Item row')
22
+ .purpose('why: serve the authorized Order Item view')
23
+ .executeForList(context);
24
+ }
25
+ ```
26
+
27
+ Compile and execute this source unchanged. Use only generated projection,
28
+ predicate, ordering, and relation-selection APIs. Missing or blank intent,
29
+ unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated
30
+ relation loading rather than handwritten child-query loops; never guess a plural.
31
+
32
+
33
+ ## Field-specific Query Assist
34
+
35
+ Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column.
36
+
37
+ | KSML field | Type | Field help |
38
+ | --- | --- | --- |
39
+ | `id` | `id` | `typescript-assist-query/order_item.id` |
40
+ | `customer_order` | `relation<customer_order>` | `typescript-assist-query/order_item.customer_order` |
41
+ | `product_name` | `string` | `typescript-assist-query/order_item.product_name` |
42
+ | `quantity` | `integer` | `typescript-assist-query/order_item.quantity` |
43
+ | `unit_price` | `number` | `typescript-assist-query/order_item.unit_price` |
44
+ | `version` | `version` | `typescript-assist-query/order_item.version` |
45
+
46
+
47
+ ---
48
+
49
+ ## TeaQL seven-language assist contract
50
+
51
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
52
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
53
+ model-aware Assist. Do not inspect generated domain-library source.
54
+
55
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
56
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
57
+ forms such as “who are active” and “whose email is”; never infer them from English.
58
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
59
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
60
+ requires both values, but comment does not have to immediately precede purpose.
61
+ - Every execute/list/stream and every save accepts exactly one context argument:
62
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
63
+ policy are injected when the context is built. Reserve `runtime` for process-level
64
+ runtime ownership, provider/pool setup, and module assembly.
65
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
66
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
67
+ - If the required operation is absent after current entity/action and required field
68
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
69
+ generated library as a fallback.
70
+ - Create each application-owned source file once. After its first compile attempt,
71
+ repair only the smallest block identified by the exact compiler or test diagnostic.
72
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
73
+ - Before a repair that would replace more than 25% of an existing application file,
74
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
75
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
76
+
77
+ Capability: `query`.
78
+
79
+ - Use generated projection, relation, predicate, sort, and aggregate APIs; never
80
+ concatenate application SQL or silently ignore an unsupported filter.
81
+ - Rows, record count, facets, and aggregates must share the same active filter.
82
+ - Add negative tests for missing purpose/comment and forbidden dynamic fields.
83
+
84
+ ### Optional per-parent Top-N optimization
85
+
86
+ - Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution
87
+ stage. Use the field-specific relation Assist for the exact generated selector.
88
+ - Give the child a per-parent limit and deterministic ordering with an ID tie-breaker;
89
+ bound the parent query separately. A single-parent detail query is not batch Top-N.
90
+ - Server providers default to a window query (`threshold = 0`). A positive threshold
91
+ permits bounded probes only when the already-loaded parent count is at or below it;
92
+ above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default.
93
+ - Measure before opting in. Do not infer a threshold from table size or execute COUNT
94
+ or statistics queries to choose a plan. Keep an index on foreign key + sort + ID.
95
+ - Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry.
96
+ Runtime-managed probes are not application-owned N+1 loops; neither strategy changes
97
+ authorization, loaded-state semantics or the required comment/purpose.
source/browser-sqlite/assist/query-order_status.customer_order_list.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # Query Reverse-Relation Assist — `order_status.customer_order_list`
4
+
5
+ KSML entity: `order_status`
6
+ Derived reverse relation: `customer_order_list`
7
+ Child entity: `customer_order`
8
+
9
+ | Capability | Generated API |
10
+ | --- | --- |
11
+ | Select | `.selectCustomerOrderListWith(Q.customerOrdersWithMinimalFields())` |
12
+
13
+ Reverse relations are model-derived and never perform an implicit database query. Select the relation explicitly before expression access. Apply query methods before the executable purpose stage, then execute with exactly one trusted context.
14
+
15
+
16
+ ---
17
+
18
+ ## TeaQL seven-language assist contract
19
+
20
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
21
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
22
+ model-aware Assist. Do not inspect generated domain-library source.
23
+
24
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
25
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
26
+ forms such as “who are active” and “whose email is”; never infer them from English.
27
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
28
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
29
+ requires both values, but comment does not have to immediately precede purpose.
30
+ - Every execute/list/stream and every save accepts exactly one context argument:
31
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
32
+ policy are injected when the context is built. Reserve `runtime` for process-level
33
+ runtime ownership, provider/pool setup, and module assembly.
34
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
35
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
36
+ - If the required operation is absent after current entity/action and required field
37
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
38
+ generated library as a fallback.
39
+ - Create each application-owned source file once. After its first compile attempt,
40
+ repair only the smallest block identified by the exact compiler or test diagnostic.
41
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
42
+ - Before a repair that would replace more than 25% of an existing application file,
43
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
44
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
45
+
46
+ Capability: `query`.
47
+
48
+ - Use generated projection, relation, predicate, sort, and aggregate APIs; never
49
+ concatenate application SQL or silently ignore an unsupported filter.
50
+ - Rows, record count, facets, and aggregates must share the same active filter.
51
+ - Add negative tests for missing purpose/comment and forbidden dynamic fields.
52
+
53
+ ### Optional per-parent Top-N optimization
54
+
55
+ - Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution
56
+ stage. Use the field-specific relation Assist for the exact generated selector.
57
+ - Give the child a per-parent limit and deterministic ordering with an ID tie-breaker;
58
+ bound the parent query separately. A single-parent detail query is not batch Top-N.
59
+ - Server providers default to a window query (`threshold = 0`). A positive threshold
60
+ permits bounded probes only when the already-loaded parent count is at or below it;
61
+ above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default.
62
+ - Measure before opting in. Do not infer a threshold from table size or execute COUNT
63
+ or statistics queries to choose a plan. Keep an index on foreign key + sort + ID.
64
+ - Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry.
65
+ Runtime-managed probes are not application-owned N+1 loops; neither strategy changes
66
+ authorization, loaded-state semantics or the required comment/purpose.
source/browser-sqlite/assist/query-order_status.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ephemeral -->
2
+
3
+ # TypeScript Assist — Query `Order Status`
4
+
5
+ Use the exact generated `Q.orderStatusesWithMinimalFields()`
6
+ entry point. Trusted runtime and policy state comes only from `UserContext`.
7
+
8
+ ```typescript
9
+ import { Q } from './Q';
10
+ import { OrderStatus } from './models/OrderStatus';
11
+ import { SmartList, UserContext } from '../teaql-ts';
12
+
13
+ export async function queryOrderStatusById(
14
+ context: UserContext,
15
+ entityId: string,
16
+ ): Promise<SmartList<OrderStatus>> {
17
+ return Q.orderStatusesWithMinimalFields()
18
+ .withIdIs(entityId)
19
+ .orderByIdAscending()
20
+ .limit(20)
21
+ .comment('what: load the requested Order Status row')
22
+ .purpose('why: serve the authorized Order Status view')
23
+ .executeForList(context);
24
+ }
25
+ ```
26
+
27
+ Compile and execute this source unchanged. Use only generated projection,
28
+ predicate, ordering, and relation-selection APIs. Missing or blank intent,
29
+ unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated
30
+ relation loading rather than handwritten child-query loops; never guess a plural.
31
+
32
+
33
+ ## Field-specific Query Assist
34
+
35
+ Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column.
36
+
37
+ | KSML field | Type | Field help |
38
+ | --- | --- | --- |
39
+ | `platform` | `relation<platform>` | `typescript-assist-query/order_status.platform` |
40
+ | `id` | `id` | `typescript-assist-query/order_status.id` |
41
+ | `name` | `string` | `typescript-assist-query/order_status.name` |
42
+ | `code` | `string` | `typescript-assist-query/order_status.code` |
43
+ | `color` | `string` | `typescript-assist-query/order_status.color` |
44
+ | `display_order` | `integer` | `typescript-assist-query/order_status.display_order` |
45
+ | `version` | `version` | `typescript-assist-query/order_status.version` |
46
+
47
+ Generated reverse relations are derived from referencing KSML fields. Use their exact generated location for relation selection and access:
48
+
49
+ | Generated reverse relation | Child entity | Field help |
50
+ | --- | --- | --- |
51
+ | `customer_order_list` | `customer_order` | `typescript-assist-query/order_status.customer_order_list` |
52
+
53
+
54
+ ---
55
+
56
+ ## TeaQL seven-language assist contract
57
+
58
+ Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and
59
+ runtime APIs. Discover APIs through the generated application AGENTS.md and progressive
60
+ model-aware Assist. Do not inspect generated domain-library source.
61
+
62
+ - Do not create plurals by appending `s` or `es`; use the centralized generated plural.
63
+ - Human and non-human entities use different generated predicate vocabularies. Preserve
64
+ forms such as “who are active” and “whose email is”; never infer them from English.
65
+ - Configure filters, projection, paging, and other query options before `purpose(...)`.
66
+ Comment may appear anywhere in the chain. Purpose enters the executable stage; execution
67
+ requires both values, but comment does not have to immediately precede purpose.
68
+ - Every execute/list/stream and every save accepts exactly one context argument:
69
+ `UserContext`. Name that argument `context`, never `runtime`; data services and global
70
+ policy are injected when the context is built. Reserve `runtime` for process-level
71
+ runtime ownership, provider/pool setup, and module assembly.
72
+ - Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit,
73
+ and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP.
74
+ - If the required operation is absent after current entity/action and required field
75
+ Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the
76
+ generated library as a fallback.
77
+ - Create each application-owned source file once. After its first compile attempt,
78
+ repair only the smallest block identified by the exact compiler or test diagnostic.
79
+ Preserve unrelated code; do not rewrite the complete file as an error-recovery loop.
80
+ - Before a repair that would replace more than 25% of an existing application file,
81
+ stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and
82
+ estimated scope. Initial creation and model-driven regeneration are not repairs.
83
+
84
+ Capability: `query`.
85
+
86
+ - Use generated projection, relation, predicate, sort, and aggregate APIs; never
87
+ concatenate application SQL or silently ignore an unsupported filter.
88
+ - Rows, record count, facets, and aggregates must share the same active filter.
89
+ - Add negative tests for missing purpose/comment and forbidden dynamic fields.
90
+
91
+ ### Optional per-parent Top-N optimization
92
+
93
+ - Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution
94
+ stage. Use the field-specific relation Assist for the exact generated selector.
95
+ - Give the child a per-parent limit and deterministic ordering with an ID tie-breaker;
96
+ bound the parent query separately. A single-parent detail query is not batch Top-N.
97
+ - Server providers default to a window query (`threshold = 0`). A positive threshold
98
+ permits bounded probes only when the already-loaded parent count is at or below it;
99
+ above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default.
100
+ - Measure before opting in. Do not infer a threshold from table size or execute COUNT
101
+ or statistics queries to choose a plan. Keep an index on foreign key + sort + ID.
102
+ - Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry.
103
+ Runtime-managed probes are not application-owned N+1 loops; neither strategy changes
104
+ authorization, loaded-state semantics or the required comment/purpose.
source/browser-sqlite/generated-order-hashes.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "package.json" : "bbfaeef0b7488ec0f44377eecc68375124b8f0c4fcacd7d59df1755b0a127581",
3
+ "src/generated-bootstrap.ts" : "5f3065c1e4794c0d21ada7c2eef48f4694cec1cbc4771fa48bc7d6ff9221540b",
4
+ "src/generated-search-models.ts" : "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3",
5
+ "src/generated/E.ts" : "c4c72de70c1b103343390acee51970dd1fa01cdbe1bdebd9b9aa34b3539d2039",
6
+ "src/generated/Q.ts" : "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f",
7
+ "src/generated/models/Customer.ts" : "d134c6b78e25d86dacea5d4c738178c3629101269413bb45d62a2f490d9b4417",
8
+ "src/generated/models/CustomerOrder.ts" : "c65e857a6deb99599e34a06bb24ca948cc852e9a15b969ff4ffe21d041fcf05c",
9
+ "src/generated/models/OrderItem.ts" : "ce43fb172b461b74d53cb73933335a8fa055b6269738f44bf3e1deb04e1d8b85",
10
+ "src/generated/models/OrderStatus.ts" : "c6e3349c7da21267dee6940b61a9d43bc0413a7d68230b9c600b73ec82f96e16",
11
+ "src/generated/models/Platform.ts" : "6a2df07a3fc284d02639ecb530d0aaa58e448dbc77de7d97b46dc4e367cd58fd",
12
+ "src/generated/requests/CustomerOrderRequest.ts" : "0f2a2a3895c7245ea258354e6fc19e24b4e57adc48a29818abe7b8ce8126cb57",
13
+ "src/generated/requests/CustomerRequest.ts" : "109f1df30ccafb9e4a163fa5f94d8e77d915cd2bb5a2d8bf3e7adeadbe92e262",
14
+ "src/generated/requests/OrderItemRequest.ts" : "ab3fb698f606c848da983eaabc140268066b8d9bac73b54127733c98e48e19d9",
15
+ "src/generated/requests/OrderStatusRequest.ts" : "f9087a9084b3aaac46d91cd7006cf5b71214df711bfd0f51e17da83a53e633c9",
16
+ "src/generated/requests/PlatformRequest.ts" : "8a6dd581be256cad3332ca275ac3652ef1e01a0c4c9f0e6cefd2a6e14fc105e1",
17
+ "src/runtime-module.ts" : "f92fe9a9474678d26a233eb734b14493b4ddc216ed3b648bfad723b4b6a46eeb",
18
+ "src/teaql-schemas.ts" : "68cb7cacc725ff041d2289f17d7817ae56f37d035c92f2feb6c1318face6f806",
19
+ "src/teaql-ts.ts" : "cc705f9f7873450eae541311317db3402dc40b7cf068c440169bd7ba06dcb1ed",
20
+ "teaql-i18n.json" : "ee5dc28e916a8907555d5d5a4d0e3cf2fa37aad047af37abed0800582af18d96",
21
+ "tsconfig.json" : "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037"
22
+ }
source/browser-sqlite/index.html ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <link rel="icon" href="data:," />
7
+ <title>TeaQL browser order TraceChain</title>
8
+ </head>
9
+ <body>
10
+ <main>
11
+ <p class="eyebrow">GENERATED Q + E · SQLITE/WASM · NO BACKEND</p>
12
+ <h1>Order query evidence</h1>
13
+ <p>One filtered page, named total, status facets and bounded item previews.</p>
14
+ <p>Entirely browser-local · SQLite/WASM · Generated typed Order Q/E APIs</p>
15
+ <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>
16
+ <div class="controls">
17
+ <label><input id="persist" type="checkbox" /> Persist locally with OPFS <span id="opfs-note"></span></label>
18
+ <label><input id="logging" type="checkbox" checked /> Diagnostic logging</label>
19
+ <button id="reset">Reset demo data</button>
20
+ </div>
21
+ <label for="example">Example query</label>
22
+ <select id="example"><option value="filtered">Filtered order page</option><option value="all">All orders</option></select>
23
+ <label for="search">Editable generated TypeScript Q API, parsed into a controlled AST</label>
24
+ <textarea id="search" rows="20" spellcheck="false" style="display:block;width:100%;margin:12px 0"></textarea>
25
+ <p>No eval, imports, assignments or arbitrary JavaScript execution.</p>
26
+ <button id="query">Run query</button>
27
+ <button id="preset">Restore example search</button>
28
+ <p id="status">Starting SQLite/WASM…</p>
29
+ <h2>Response data and metadata</h2>
30
+ <pre id="result"></pre>
31
+ <h2>SQL execution evidence</h2>
32
+ <p>Time is the recorded execution duration. Identity is the request entity from tracePath, not a user or object ID.</p>
33
+ <div class="evidence-scroll">
34
+ <table class="evidence-table">
35
+ <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>
36
+ <tbody id="evidence-rows"></tbody>
37
+ </table>
38
+ </div>
39
+ <details><summary>Business TraceChain as text</summary><pre id="trace"></pre></details>
40
+ <details><summary>Runtime metadata and physical tracePath</summary><pre id="sql"></pre></details>
41
+ </main>
42
+ <script type="module" src="/src/main.ts"></script>
43
+ </body>
44
+ </html>
source/browser-sqlite/order-model.xml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <root name="request-tree-order-service" org="example" data_service="sqlite" _module_key="root">
3
+ <platform _name="Commerce Platform" _module="Commerce" _module_key="commerce"
4
+ name="Commerce Test Platform"/>
5
+ <order_status _name="Order Status" _module="Commerce" _module_key="commerce"
6
+ platform="platform()" id="id()" name="string()" code="string()"
7
+ color="string()" display_order="1" _constant="true" _identifier="code">
8
+ <_value id="1001" name="New" code="NEW" color="#94A3B8" display_order="1"/>
9
+ <_value id="1002" name="Paid" code="PAID" color="#22C55E" display_order="2"/>
10
+ <_value id="1003" name="Cancelled" code="CANCELLED" color="#EF4444" display_order="3"/>
11
+ </order_status>
12
+ <customer _name="Customer" _module="Commerce" _module_key="commerce"
13
+ platform="platform()" name="North Star Retail"/>
14
+ <customer_order _name="Customer Order" _module="Commerce" _module_key="commerce"
15
+ customer="customer()" status="order_status()"
16
+ order_number="CO-20261011-000001" order_date="2026-10-11"
17
+ total_amount="100.00"/>
18
+ <order_item _name="Order Item" _module="Commerce" _module_key="commerce"
19
+ customer_order="customer_order()" product_name="Packing Box"
20
+ quantity="5" unit_price="20.00"/>
21
+ </root>
source/browser-sqlite/orders-lib/package.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name" : "request-tree-order-service-lib",
3
+ "version" : "1.0.0",
4
+ "description" : "Generated typescript library",
5
+ "main" : "src/generated/Q.ts",
6
+ "scripts" : {
7
+ "build" : "tsc --noEmit"
8
+ },
9
+ "dependencies" : {
10
+ "teaql-ts" : "file:../../.."
11
+ },
12
+ "devDependencies" : {
13
+ "typescript" : "^5.0.0"
14
+ }
15
+ }
source/browser-sqlite/orders-lib/src/generated-bootstrap.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { UserContext } from './teaql-ts';
2
+ import { Q } from './generated/Q';
3
+ import { Platform } from './generated/models/Platform';
4
+ import { OrderStatus } from './generated/models/OrderStatus';
5
+
6
+ /** @internal Generated typed Mutation bootstrap; never call from application code. */
7
+ export async function ensureGeneratedBootstrap(context: UserContext): Promise<void> {
8
+ let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
9
+ if (!domainRoot) {
10
+ domainRoot = Platform.teaqlBootstrapNew('1');
11
+ domainRoot.updateName("Commerce Test Platform");
12
+ await domainRoot.auditAs('create generated Domain Root Platform').save(context);
13
+ }
14
+ context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! });
15
+ let constantOrderStatus1001 = (await Q.orderStatuses().withIdIs("1001").comment('what: locate generated constant OrderStatus(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
16
+ if (!constantOrderStatus1001) {
17
+ constantOrderStatus1001 = OrderStatus.teaqlBootstrapNew("1001");
18
+ constantOrderStatus1001.updatePlatform(domainRoot);
19
+ constantOrderStatus1001.updateName("New");
20
+ constantOrderStatus1001.updateCode("NEW");
21
+ constantOrderStatus1001.updateColor("#94A3B8");
22
+ constantOrderStatus1001.updateDisplayOrder(1);
23
+ await constantOrderStatus1001.auditAs('create model constant OrderStatus(1001)').save(context);
24
+ } else {
25
+ let changed = false;
26
+ if (String((constantOrderStatus1001.platform as any)?.id ?? constantOrderStatus1001.platform) !== String(domainRoot.id)) { constantOrderStatus1001.updatePlatform(domainRoot); changed = true; }
27
+ if (constantOrderStatus1001.name !== "New") { constantOrderStatus1001.updateName("New"); changed = true; }
28
+ if (constantOrderStatus1001.code !== "NEW") { constantOrderStatus1001.updateCode("NEW"); changed = true; }
29
+ if (constantOrderStatus1001.color !== "#94A3B8") { constantOrderStatus1001.updateColor("#94A3B8"); changed = true; }
30
+ if (constantOrderStatus1001.displayOrder !== 1) { constantOrderStatus1001.updateDisplayOrder(1); changed = true; }
31
+ if (changed) await constantOrderStatus1001.auditAs('reconcile model constant OrderStatus(1001)').save(context);
32
+ }
33
+ let constantOrderStatus1002 = (await Q.orderStatuses().withIdIs("1002").comment('what: locate generated constant OrderStatus(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
34
+ if (!constantOrderStatus1002) {
35
+ constantOrderStatus1002 = OrderStatus.teaqlBootstrapNew("1002");
36
+ constantOrderStatus1002.updatePlatform(domainRoot);
37
+ constantOrderStatus1002.updateName("Paid");
38
+ constantOrderStatus1002.updateCode("PAID");
39
+ constantOrderStatus1002.updateColor("#22C55E");
40
+ constantOrderStatus1002.updateDisplayOrder(2);
41
+ await constantOrderStatus1002.auditAs('create model constant OrderStatus(1002)').save(context);
42
+ } else {
43
+ let changed = false;
44
+ if (String((constantOrderStatus1002.platform as any)?.id ?? constantOrderStatus1002.platform) !== String(domainRoot.id)) { constantOrderStatus1002.updatePlatform(domainRoot); changed = true; }
45
+ if (constantOrderStatus1002.name !== "Paid") { constantOrderStatus1002.updateName("Paid"); changed = true; }
46
+ if (constantOrderStatus1002.code !== "PAID") { constantOrderStatus1002.updateCode("PAID"); changed = true; }
47
+ if (constantOrderStatus1002.color !== "#22C55E") { constantOrderStatus1002.updateColor("#22C55E"); changed = true; }
48
+ if (constantOrderStatus1002.displayOrder !== 2) { constantOrderStatus1002.updateDisplayOrder(2); changed = true; }
49
+ if (changed) await constantOrderStatus1002.auditAs('reconcile model constant OrderStatus(1002)').save(context);
50
+ }
51
+ let constantOrderStatus1003 = (await Q.orderStatuses().withIdIs("1003").comment('what: locate generated constant OrderStatus(1003)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
52
+ if (!constantOrderStatus1003) {
53
+ constantOrderStatus1003 = OrderStatus.teaqlBootstrapNew("1003");
54
+ constantOrderStatus1003.updatePlatform(domainRoot);
55
+ constantOrderStatus1003.updateName("Cancelled");
56
+ constantOrderStatus1003.updateCode("CANCELLED");
57
+ constantOrderStatus1003.updateColor("#EF4444");
58
+ constantOrderStatus1003.updateDisplayOrder(3);
59
+ await constantOrderStatus1003.auditAs('create model constant OrderStatus(1003)').save(context);
60
+ } else {
61
+ let changed = false;
62
+ if (String((constantOrderStatus1003.platform as any)?.id ?? constantOrderStatus1003.platform) !== String(domainRoot.id)) { constantOrderStatus1003.updatePlatform(domainRoot); changed = true; }
63
+ if (constantOrderStatus1003.name !== "Cancelled") { constantOrderStatus1003.updateName("Cancelled"); changed = true; }
64
+ if (constantOrderStatus1003.code !== "CANCELLED") { constantOrderStatus1003.updateCode("CANCELLED"); changed = true; }
65
+ if (constantOrderStatus1003.color !== "#EF4444") { constantOrderStatus1003.updateColor("#EF4444"); changed = true; }
66
+ if (constantOrderStatus1003.displayOrder !== 3) { constantOrderStatus1003.updateDisplayOrder(3); changed = true; }
67
+ if (changed) await constantOrderStatus1003.auditAs('reconcile model constant OrderStatus(1003)').save(context);
68
+ }
69
+ }
source/browser-sqlite/orders-lib/src/generated-search-models.ts ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GeneratedSearchModel } from "teaql-ts";
2
+
3
+ /** Generated trusted naming/type metadata. No query execution or authorization lives here. */
4
+ export const GENERATED_SEARCH_MODELS: Readonly<Record<string, GeneratedSearchModel>> = Object.freeze({
5
+ "Platform": Object.freeze({
6
+ fields: Object.freeze({
7
+ "id": "integer" as const,
8
+ "name": "string" as const,
9
+ "version": "integer" as const,
10
+ }),
11
+ queryFields: Object.freeze({
12
+ "id": "id",
13
+ "name": "name",
14
+ "version": "version",
15
+ }),
16
+ relations: Object.freeze({
17
+ "orderStatusList": "OrderStatus",
18
+ "customerList": "Customer",
19
+ }),
20
+ }),
21
+ "OrderStatus": Object.freeze({
22
+ fields: Object.freeze({
23
+ "platform": "integer" as const,
24
+ "id": "integer" as const,
25
+ "name": "string" as const,
26
+ "code": "string" as const,
27
+ "color": "string" as const,
28
+ "display_order": "integer" as const,
29
+ "displayOrder": "integer" as const,
30
+ "version": "integer" as const,
31
+ }),
32
+ queryFields: Object.freeze({
33
+ "platform": "platform",
34
+ "id": "id",
35
+ "name": "name",
36
+ "code": "code",
37
+ "color": "color",
38
+ "display_order": "displayOrder",
39
+ "displayOrder": "displayOrder",
40
+ "version": "version",
41
+ }),
42
+ relations: Object.freeze({
43
+ "platform": "Platform",
44
+ "customerOrderList": "CustomerOrder",
45
+ }),
46
+ }),
47
+ "Customer": Object.freeze({
48
+ fields: Object.freeze({
49
+ "id": "integer" as const,
50
+ "platform": "integer" as const,
51
+ "name": "string" as const,
52
+ "version": "integer" as const,
53
+ }),
54
+ queryFields: Object.freeze({
55
+ "id": "id",
56
+ "platform": "platform",
57
+ "name": "name",
58
+ "version": "version",
59
+ }),
60
+ relations: Object.freeze({
61
+ "platform": "Platform",
62
+ "customerOrderList": "CustomerOrder",
63
+ }),
64
+ }),
65
+ "CustomerOrder": Object.freeze({
66
+ fields: Object.freeze({
67
+ "id": "integer" as const,
68
+ "customer": "integer" as const,
69
+ "status": "integer" as const,
70
+ "order_number": "string" as const,
71
+ "orderNumber": "string" as const,
72
+ "order_date": "date" as const,
73
+ "orderDate": "date" as const,
74
+ "total_amount": "decimal" as const,
75
+ "totalAmount": "decimal" as const,
76
+ "version": "integer" as const,
77
+ }),
78
+ queryFields: Object.freeze({
79
+ "id": "id",
80
+ "customer": "customer",
81
+ "status": "status",
82
+ "order_number": "orderNumber",
83
+ "orderNumber": "orderNumber",
84
+ "order_date": "orderDate",
85
+ "orderDate": "orderDate",
86
+ "total_amount": "totalAmount",
87
+ "totalAmount": "totalAmount",
88
+ "version": "version",
89
+ }),
90
+ relations: Object.freeze({
91
+ "customer": "Customer",
92
+ "status": "OrderStatus",
93
+ "orderItemList": "OrderItem",
94
+ }),
95
+ }),
96
+ "OrderItem": Object.freeze({
97
+ fields: Object.freeze({
98
+ "id": "integer" as const,
99
+ "customer_order": "integer" as const,
100
+ "customerOrder": "integer" as const,
101
+ "product_name": "string" as const,
102
+ "productName": "string" as const,
103
+ "quantity": "integer" as const,
104
+ "unit_price": "decimal" as const,
105
+ "unitPrice": "decimal" as const,
106
+ "version": "integer" as const,
107
+ }),
108
+ queryFields: Object.freeze({
109
+ "id": "id",
110
+ "customer_order": "customerOrder",
111
+ "customerOrder": "customerOrder",
112
+ "product_name": "productName",
113
+ "productName": "productName",
114
+ "quantity": "quantity",
115
+ "unit_price": "unitPrice",
116
+ "unitPrice": "unitPrice",
117
+ "version": "version",
118
+ }),
119
+ relations: Object.freeze({
120
+ "customer_order": "CustomerOrder",
121
+ "customerOrder": "CustomerOrder",
122
+ }),
123
+ }),
124
+ });
source/browser-sqlite/orders-lib/src/generated/E.ts ADDED
@@ -0,0 +1,859 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Platform } from './models/Platform';
2
+ import { OrderStatus } from './models/OrderStatus';
3
+ import { Customer } from './models/Customer';
4
+ import { CustomerOrder } from './models/CustomerOrder';
5
+ import { OrderItem } from './models/OrderItem';
6
+
7
+ export class TeaQLNotLoadedError extends Error {
8
+ readonly details: Record<string, unknown>;
9
+
10
+ constructor(
11
+ readonly root: string,
12
+ readonly accessPath: string,
13
+ readonly breakPoint: string,
14
+ ) {
15
+ const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`;
16
+ const details = {
17
+ error: 'TeaQLNotLoadedError',
18
+ root,
19
+ accessPath: accessPath.split('.'),
20
+ breakPoint,
21
+ missingPreload: [breakPoint],
22
+ suggestedFix,
23
+ severity: 'error',
24
+ humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`,
25
+ };
26
+ super(JSON.stringify(details));
27
+ this.name = 'TeaQLNotLoadedError';
28
+ this.details = details;
29
+ }
30
+ }
31
+
32
+ function expressionPath(prefix: string, field: string): string {
33
+ return prefix ? `${prefix}.${field}` : field;
34
+ }
35
+
36
+ export class ValueExpression<T> {
37
+ constructor(
38
+ private readonly value: T | null | undefined,
39
+ private readonly present = true,
40
+ private readonly notLoaded?: TeaQLNotLoadedError,
41
+ ) {}
42
+
43
+ static missing<T>(): ValueExpression<T> {
44
+ return new ValueExpression<T>(undefined, false);
45
+ }
46
+
47
+ static notLoaded<T>(error: TeaQLNotLoadedError): ValueExpression<T> {
48
+ return new ValueExpression<T>(undefined, false, error);
49
+ }
50
+
51
+ eval(): T | null | undefined {
52
+ if (this.notLoaded) throw this.notLoaded;
53
+ return this.present ? this.value : undefined;
54
+ }
55
+
56
+ isPresent(): boolean {
57
+ if (this.notLoaded) throw this.notLoaded;
58
+ return this.present;
59
+ }
60
+
61
+ orElse(fallback: T): T {
62
+ const value = this.eval();
63
+ return this.present && value != null ? value : fallback;
64
+ }
65
+ }
66
+
67
+ export class PlatformExpression {
68
+ constructor(
69
+ private readonly value: Platform | null | undefined,
70
+ private readonly root = 'Platform(null)',
71
+ private readonly path = '',
72
+ private readonly notLoaded?: TeaQLNotLoadedError,
73
+ ) {}
74
+
75
+ eval(): Platform | null | undefined {
76
+ if (this.notLoaded) throw this.notLoaded;
77
+ return this.value;
78
+ }
79
+
80
+ id(): ValueExpression<string> {
81
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
82
+ if (!this.value) return ValueExpression.missing<string>();
83
+ const path = expressionPath(this.path, 'id');
84
+ if (!this.value.isLoaded('id')) {
85
+ return ValueExpression.notLoaded<string>(
86
+ new TeaQLNotLoadedError(this.root, path, 'id'),
87
+ );
88
+ }
89
+ return new ValueExpression<string>(this.value.id);
90
+ }
91
+
92
+ name(): ValueExpression<string> {
93
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
94
+ if (!this.value) return ValueExpression.missing<string>();
95
+ const path = expressionPath(this.path, 'name');
96
+ if (!this.value.isLoaded('name')) {
97
+ return ValueExpression.notLoaded<string>(
98
+ new TeaQLNotLoadedError(this.root, path, 'name'),
99
+ );
100
+ }
101
+ return new ValueExpression<string>(this.value.name);
102
+ }
103
+
104
+ version(): ValueExpression<number> {
105
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
106
+ if (!this.value) return ValueExpression.missing<number>();
107
+ const path = expressionPath(this.path, 'version');
108
+ if (!this.value.isLoaded('version')) {
109
+ return ValueExpression.notLoaded<number>(
110
+ new TeaQLNotLoadedError(this.root, path, 'version'),
111
+ );
112
+ }
113
+ return new ValueExpression<number>(this.value.version);
114
+ }
115
+
116
+
117
+
118
+ orderStatusList(): OrderStatusListExpression {
119
+ const path = expressionPath(this.path, 'orderStatusList');
120
+ if (this.notLoaded) {
121
+ return new OrderStatusListExpression([], this.root, path, false, this.notLoaded);
122
+ }
123
+ if (!this.value) return OrderStatusListExpression.missing(this.root, path);
124
+ if (!this.value.isLoaded('orderStatusList')) {
125
+ return new OrderStatusListExpression([], this.root, path, false,
126
+ new TeaQLNotLoadedError(this.root, path, 'orderStatusList'));
127
+ }
128
+ return new OrderStatusListExpression(
129
+ this.value.orderStatusList(), this.root, path,
130
+ );
131
+ }
132
+
133
+ customerList(): CustomerListExpression {
134
+ const path = expressionPath(this.path, 'customerList');
135
+ if (this.notLoaded) {
136
+ return new CustomerListExpression([], this.root, path, false, this.notLoaded);
137
+ }
138
+ if (!this.value) return CustomerListExpression.missing(this.root, path);
139
+ if (!this.value.isLoaded('customerList')) {
140
+ return new CustomerListExpression([], this.root, path, false,
141
+ new TeaQLNotLoadedError(this.root, path, 'customerList'));
142
+ }
143
+ return new CustomerListExpression(
144
+ this.value.customerList(), this.root, path,
145
+ );
146
+ }
147
+ }
148
+
149
+ export class OrderStatusExpression {
150
+ constructor(
151
+ private readonly value: OrderStatus | null | undefined,
152
+ private readonly root = 'OrderStatus(null)',
153
+ private readonly path = '',
154
+ private readonly notLoaded?: TeaQLNotLoadedError,
155
+ ) {}
156
+
157
+ eval(): OrderStatus | null | undefined {
158
+ if (this.notLoaded) throw this.notLoaded;
159
+ return this.value;
160
+ }
161
+
162
+ id(): ValueExpression<string> {
163
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
164
+ if (!this.value) return ValueExpression.missing<string>();
165
+ const path = expressionPath(this.path, 'id');
166
+ if (!this.value.isLoaded('id')) {
167
+ return ValueExpression.notLoaded<string>(
168
+ new TeaQLNotLoadedError(this.root, path, 'id'),
169
+ );
170
+ }
171
+ return new ValueExpression<string>(this.value.id);
172
+ }
173
+
174
+ name(): ValueExpression<string> {
175
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
176
+ if (!this.value) return ValueExpression.missing<string>();
177
+ const path = expressionPath(this.path, 'name');
178
+ if (!this.value.isLoaded('name')) {
179
+ return ValueExpression.notLoaded<string>(
180
+ new TeaQLNotLoadedError(this.root, path, 'name'),
181
+ );
182
+ }
183
+ return new ValueExpression<string>(this.value.name);
184
+ }
185
+
186
+ code(): ValueExpression<string> {
187
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
188
+ if (!this.value) return ValueExpression.missing<string>();
189
+ const path = expressionPath(this.path, 'code');
190
+ if (!this.value.isLoaded('code')) {
191
+ return ValueExpression.notLoaded<string>(
192
+ new TeaQLNotLoadedError(this.root, path, 'code'),
193
+ );
194
+ }
195
+ return new ValueExpression<string>(this.value.code);
196
+ }
197
+
198
+ color(): ValueExpression<string> {
199
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
200
+ if (!this.value) return ValueExpression.missing<string>();
201
+ const path = expressionPath(this.path, 'color');
202
+ if (!this.value.isLoaded('color')) {
203
+ return ValueExpression.notLoaded<string>(
204
+ new TeaQLNotLoadedError(this.root, path, 'color'),
205
+ );
206
+ }
207
+ return new ValueExpression<string>(this.value.color);
208
+ }
209
+
210
+ displayOrder(): ValueExpression<number> {
211
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
212
+ if (!this.value) return ValueExpression.missing<number>();
213
+ const path = expressionPath(this.path, 'displayOrder');
214
+ if (!this.value.isLoaded('displayOrder')) {
215
+ return ValueExpression.notLoaded<number>(
216
+ new TeaQLNotLoadedError(this.root, path, 'displayOrder'),
217
+ );
218
+ }
219
+ return new ValueExpression<number>(this.value.displayOrder);
220
+ }
221
+
222
+ version(): ValueExpression<number> {
223
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
224
+ if (!this.value) return ValueExpression.missing<number>();
225
+ const path = expressionPath(this.path, 'version');
226
+ if (!this.value.isLoaded('version')) {
227
+ return ValueExpression.notLoaded<number>(
228
+ new TeaQLNotLoadedError(this.root, path, 'version'),
229
+ );
230
+ }
231
+ return new ValueExpression<number>(this.value.version);
232
+ }
233
+
234
+ platformId(): ValueExpression<string | number> {
235
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
236
+ if (!this.value) return ValueExpression.missing<string | number>();
237
+ const path = expressionPath(this.path, 'platform');
238
+ if (!this.value.isLoaded('platform')) {
239
+ return ValueExpression.notLoaded<string | number>(
240
+ new TeaQLNotLoadedError(this.root, path, 'platform'),
241
+ );
242
+ }
243
+ return new ValueExpression<string | number>(
244
+ this.value.platform as string | number | undefined,
245
+ );
246
+ }
247
+
248
+ platform(): PlatformExpression {
249
+ const path = expressionPath(this.path, 'platform');
250
+ if (this.notLoaded) {
251
+ return new PlatformExpression(undefined, this.root, path, this.notLoaded);
252
+ }
253
+ if (!this.value) return new PlatformExpression(undefined, this.root, path);
254
+ if (!this.value.isLoaded('platform')) {
255
+ return new PlatformExpression(undefined, this.root, path,
256
+ new TeaQLNotLoadedError(this.root, path, 'platform'));
257
+ }
258
+ const relation = this.value.platform;
259
+ const target = relation == null
260
+ ? undefined
261
+ : relation instanceof Platform
262
+ ? relation
263
+ : Platform.fromRecord({ id: relation });
264
+ return new PlatformExpression(target, this.root, path);
265
+ }
266
+
267
+ customerOrderList(): CustomerOrderListExpression {
268
+ const path = expressionPath(this.path, 'customerOrderList');
269
+ if (this.notLoaded) {
270
+ return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded);
271
+ }
272
+ if (!this.value) return CustomerOrderListExpression.missing(this.root, path);
273
+ if (!this.value.isLoaded('customerOrderList')) {
274
+ return new CustomerOrderListExpression([], this.root, path, false,
275
+ new TeaQLNotLoadedError(this.root, path, 'customerOrderList'));
276
+ }
277
+ return new CustomerOrderListExpression(
278
+ this.value.customerOrderList(), this.root, path,
279
+ );
280
+ }
281
+ }
282
+
283
+ export class CustomerExpression {
284
+ constructor(
285
+ private readonly value: Customer | null | undefined,
286
+ private readonly root = 'Customer(null)',
287
+ private readonly path = '',
288
+ private readonly notLoaded?: TeaQLNotLoadedError,
289
+ ) {}
290
+
291
+ eval(): Customer | null | undefined {
292
+ if (this.notLoaded) throw this.notLoaded;
293
+ return this.value;
294
+ }
295
+
296
+ id(): ValueExpression<string> {
297
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
298
+ if (!this.value) return ValueExpression.missing<string>();
299
+ const path = expressionPath(this.path, 'id');
300
+ if (!this.value.isLoaded('id')) {
301
+ return ValueExpression.notLoaded<string>(
302
+ new TeaQLNotLoadedError(this.root, path, 'id'),
303
+ );
304
+ }
305
+ return new ValueExpression<string>(this.value.id);
306
+ }
307
+
308
+ name(): ValueExpression<string> {
309
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
310
+ if (!this.value) return ValueExpression.missing<string>();
311
+ const path = expressionPath(this.path, 'name');
312
+ if (!this.value.isLoaded('name')) {
313
+ return ValueExpression.notLoaded<string>(
314
+ new TeaQLNotLoadedError(this.root, path, 'name'),
315
+ );
316
+ }
317
+ return new ValueExpression<string>(this.value.name);
318
+ }
319
+
320
+ version(): ValueExpression<number> {
321
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
322
+ if (!this.value) return ValueExpression.missing<number>();
323
+ const path = expressionPath(this.path, 'version');
324
+ if (!this.value.isLoaded('version')) {
325
+ return ValueExpression.notLoaded<number>(
326
+ new TeaQLNotLoadedError(this.root, path, 'version'),
327
+ );
328
+ }
329
+ return new ValueExpression<number>(this.value.version);
330
+ }
331
+
332
+ platformId(): ValueExpression<string | number> {
333
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
334
+ if (!this.value) return ValueExpression.missing<string | number>();
335
+ const path = expressionPath(this.path, 'platform');
336
+ if (!this.value.isLoaded('platform')) {
337
+ return ValueExpression.notLoaded<string | number>(
338
+ new TeaQLNotLoadedError(this.root, path, 'platform'),
339
+ );
340
+ }
341
+ return new ValueExpression<string | number>(
342
+ this.value.platform as string | number | undefined,
343
+ );
344
+ }
345
+
346
+ platform(): PlatformExpression {
347
+ const path = expressionPath(this.path, 'platform');
348
+ if (this.notLoaded) {
349
+ return new PlatformExpression(undefined, this.root, path, this.notLoaded);
350
+ }
351
+ if (!this.value) return new PlatformExpression(undefined, this.root, path);
352
+ if (!this.value.isLoaded('platform')) {
353
+ return new PlatformExpression(undefined, this.root, path,
354
+ new TeaQLNotLoadedError(this.root, path, 'platform'));
355
+ }
356
+ const relation = this.value.platform;
357
+ const target = relation == null
358
+ ? undefined
359
+ : relation instanceof Platform
360
+ ? relation
361
+ : Platform.fromRecord({ id: relation });
362
+ return new PlatformExpression(target, this.root, path);
363
+ }
364
+
365
+ customerOrderList(): CustomerOrderListExpression {
366
+ const path = expressionPath(this.path, 'customerOrderList');
367
+ if (this.notLoaded) {
368
+ return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded);
369
+ }
370
+ if (!this.value) return CustomerOrderListExpression.missing(this.root, path);
371
+ if (!this.value.isLoaded('customerOrderList')) {
372
+ return new CustomerOrderListExpression([], this.root, path, false,
373
+ new TeaQLNotLoadedError(this.root, path, 'customerOrderList'));
374
+ }
375
+ return new CustomerOrderListExpression(
376
+ this.value.customerOrderList(), this.root, path,
377
+ );
378
+ }
379
+ }
380
+
381
+ export class CustomerOrderExpression {
382
+ constructor(
383
+ private readonly value: CustomerOrder | null | undefined,
384
+ private readonly root = 'CustomerOrder(null)',
385
+ private readonly path = '',
386
+ private readonly notLoaded?: TeaQLNotLoadedError,
387
+ ) {}
388
+
389
+ eval(): CustomerOrder | null | undefined {
390
+ if (this.notLoaded) throw this.notLoaded;
391
+ return this.value;
392
+ }
393
+
394
+ id(): ValueExpression<string> {
395
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
396
+ if (!this.value) return ValueExpression.missing<string>();
397
+ const path = expressionPath(this.path, 'id');
398
+ if (!this.value.isLoaded('id')) {
399
+ return ValueExpression.notLoaded<string>(
400
+ new TeaQLNotLoadedError(this.root, path, 'id'),
401
+ );
402
+ }
403
+ return new ValueExpression<string>(this.value.id);
404
+ }
405
+
406
+ orderNumber(): ValueExpression<string> {
407
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
408
+ if (!this.value) return ValueExpression.missing<string>();
409
+ const path = expressionPath(this.path, 'orderNumber');
410
+ if (!this.value.isLoaded('orderNumber')) {
411
+ return ValueExpression.notLoaded<string>(
412
+ new TeaQLNotLoadedError(this.root, path, 'orderNumber'),
413
+ );
414
+ }
415
+ return new ValueExpression<string>(this.value.orderNumber);
416
+ }
417
+
418
+ orderDate(): ValueExpression<string> {
419
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
420
+ if (!this.value) return ValueExpression.missing<string>();
421
+ const path = expressionPath(this.path, 'orderDate');
422
+ if (!this.value.isLoaded('orderDate')) {
423
+ return ValueExpression.notLoaded<string>(
424
+ new TeaQLNotLoadedError(this.root, path, 'orderDate'),
425
+ );
426
+ }
427
+ return new ValueExpression<string>(this.value.orderDate);
428
+ }
429
+
430
+ totalAmount(): ValueExpression<number> {
431
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
432
+ if (!this.value) return ValueExpression.missing<number>();
433
+ const path = expressionPath(this.path, 'totalAmount');
434
+ if (!this.value.isLoaded('totalAmount')) {
435
+ return ValueExpression.notLoaded<number>(
436
+ new TeaQLNotLoadedError(this.root, path, 'totalAmount'),
437
+ );
438
+ }
439
+ return new ValueExpression<number>(this.value.totalAmount);
440
+ }
441
+
442
+ version(): ValueExpression<number> {
443
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
444
+ if (!this.value) return ValueExpression.missing<number>();
445
+ const path = expressionPath(this.path, 'version');
446
+ if (!this.value.isLoaded('version')) {
447
+ return ValueExpression.notLoaded<number>(
448
+ new TeaQLNotLoadedError(this.root, path, 'version'),
449
+ );
450
+ }
451
+ return new ValueExpression<number>(this.value.version);
452
+ }
453
+
454
+ customerId(): ValueExpression<string | number> {
455
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
456
+ if (!this.value) return ValueExpression.missing<string | number>();
457
+ const path = expressionPath(this.path, 'customer');
458
+ if (!this.value.isLoaded('customer')) {
459
+ return ValueExpression.notLoaded<string | number>(
460
+ new TeaQLNotLoadedError(this.root, path, 'customer'),
461
+ );
462
+ }
463
+ return new ValueExpression<string | number>(
464
+ this.value.customer as string | number | undefined,
465
+ );
466
+ }
467
+
468
+ statusId(): ValueExpression<string | number> {
469
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
470
+ if (!this.value) return ValueExpression.missing<string | number>();
471
+ const path = expressionPath(this.path, 'status');
472
+ if (!this.value.isLoaded('status')) {
473
+ return ValueExpression.notLoaded<string | number>(
474
+ new TeaQLNotLoadedError(this.root, path, 'status'),
475
+ );
476
+ }
477
+ return new ValueExpression<string | number>(
478
+ this.value.status as string | number | undefined,
479
+ );
480
+ }
481
+
482
+ customer(): CustomerExpression {
483
+ const path = expressionPath(this.path, 'customer');
484
+ if (this.notLoaded) {
485
+ return new CustomerExpression(undefined, this.root, path, this.notLoaded);
486
+ }
487
+ if (!this.value) return new CustomerExpression(undefined, this.root, path);
488
+ if (!this.value.isLoaded('customer')) {
489
+ return new CustomerExpression(undefined, this.root, path,
490
+ new TeaQLNotLoadedError(this.root, path, 'customer'));
491
+ }
492
+ const relation = this.value.customer;
493
+ const target = relation == null
494
+ ? undefined
495
+ : relation instanceof Customer
496
+ ? relation
497
+ : Customer.fromRecord({ id: relation });
498
+ return new CustomerExpression(target, this.root, path);
499
+ }
500
+
501
+ status(): OrderStatusExpression {
502
+ const path = expressionPath(this.path, 'status');
503
+ if (this.notLoaded) {
504
+ return new OrderStatusExpression(undefined, this.root, path, this.notLoaded);
505
+ }
506
+ if (!this.value) return new OrderStatusExpression(undefined, this.root, path);
507
+ if (!this.value.isLoaded('status')) {
508
+ return new OrderStatusExpression(undefined, this.root, path,
509
+ new TeaQLNotLoadedError(this.root, path, 'status'));
510
+ }
511
+ const relation = this.value.status;
512
+ const target = relation == null
513
+ ? undefined
514
+ : relation instanceof OrderStatus
515
+ ? relation
516
+ : OrderStatus.fromRecord({ id: relation });
517
+ return new OrderStatusExpression(target, this.root, path);
518
+ }
519
+
520
+ orderItemList(): OrderItemListExpression {
521
+ const path = expressionPath(this.path, 'orderItemList');
522
+ if (this.notLoaded) {
523
+ return new OrderItemListExpression([], this.root, path, false, this.notLoaded);
524
+ }
525
+ if (!this.value) return OrderItemListExpression.missing(this.root, path);
526
+ if (!this.value.isLoaded('orderItemList')) {
527
+ return new OrderItemListExpression([], this.root, path, false,
528
+ new TeaQLNotLoadedError(this.root, path, 'orderItemList'));
529
+ }
530
+ return new OrderItemListExpression(
531
+ this.value.orderItemList(), this.root, path,
532
+ );
533
+ }
534
+ }
535
+
536
+ export class OrderItemExpression {
537
+ constructor(
538
+ private readonly value: OrderItem | null | undefined,
539
+ private readonly root = 'OrderItem(null)',
540
+ private readonly path = '',
541
+ private readonly notLoaded?: TeaQLNotLoadedError,
542
+ ) {}
543
+
544
+ eval(): OrderItem | null | undefined {
545
+ if (this.notLoaded) throw this.notLoaded;
546
+ return this.value;
547
+ }
548
+
549
+ id(): ValueExpression<string> {
550
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
551
+ if (!this.value) return ValueExpression.missing<string>();
552
+ const path = expressionPath(this.path, 'id');
553
+ if (!this.value.isLoaded('id')) {
554
+ return ValueExpression.notLoaded<string>(
555
+ new TeaQLNotLoadedError(this.root, path, 'id'),
556
+ );
557
+ }
558
+ return new ValueExpression<string>(this.value.id);
559
+ }
560
+
561
+ productName(): ValueExpression<string> {
562
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded);
563
+ if (!this.value) return ValueExpression.missing<string>();
564
+ const path = expressionPath(this.path, 'productName');
565
+ if (!this.value.isLoaded('productName')) {
566
+ return ValueExpression.notLoaded<string>(
567
+ new TeaQLNotLoadedError(this.root, path, 'productName'),
568
+ );
569
+ }
570
+ return new ValueExpression<string>(this.value.productName);
571
+ }
572
+
573
+ quantity(): ValueExpression<number> {
574
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
575
+ if (!this.value) return ValueExpression.missing<number>();
576
+ const path = expressionPath(this.path, 'quantity');
577
+ if (!this.value.isLoaded('quantity')) {
578
+ return ValueExpression.notLoaded<number>(
579
+ new TeaQLNotLoadedError(this.root, path, 'quantity'),
580
+ );
581
+ }
582
+ return new ValueExpression<number>(this.value.quantity);
583
+ }
584
+
585
+ unitPrice(): ValueExpression<number> {
586
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
587
+ if (!this.value) return ValueExpression.missing<number>();
588
+ const path = expressionPath(this.path, 'unitPrice');
589
+ if (!this.value.isLoaded('unitPrice')) {
590
+ return ValueExpression.notLoaded<number>(
591
+ new TeaQLNotLoadedError(this.root, path, 'unitPrice'),
592
+ );
593
+ }
594
+ return new ValueExpression<number>(this.value.unitPrice);
595
+ }
596
+
597
+ version(): ValueExpression<number> {
598
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
599
+ if (!this.value) return ValueExpression.missing<number>();
600
+ const path = expressionPath(this.path, 'version');
601
+ if (!this.value.isLoaded('version')) {
602
+ return ValueExpression.notLoaded<number>(
603
+ new TeaQLNotLoadedError(this.root, path, 'version'),
604
+ );
605
+ }
606
+ return new ValueExpression<number>(this.value.version);
607
+ }
608
+
609
+ customerOrderId(): ValueExpression<string | number> {
610
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded);
611
+ if (!this.value) return ValueExpression.missing<string | number>();
612
+ const path = expressionPath(this.path, 'customerOrder');
613
+ if (!this.value.isLoaded('customerOrder')) {
614
+ return ValueExpression.notLoaded<string | number>(
615
+ new TeaQLNotLoadedError(this.root, path, 'customerOrder'),
616
+ );
617
+ }
618
+ return new ValueExpression<string | number>(
619
+ this.value.customerOrder as string | number | undefined,
620
+ );
621
+ }
622
+
623
+ customerOrder(): CustomerOrderExpression {
624
+ const path = expressionPath(this.path, 'customerOrder');
625
+ if (this.notLoaded) {
626
+ return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded);
627
+ }
628
+ if (!this.value) return new CustomerOrderExpression(undefined, this.root, path);
629
+ if (!this.value.isLoaded('customerOrder')) {
630
+ return new CustomerOrderExpression(undefined, this.root, path,
631
+ new TeaQLNotLoadedError(this.root, path, 'customerOrder'));
632
+ }
633
+ const relation = this.value.customerOrder;
634
+ const target = relation == null
635
+ ? undefined
636
+ : relation instanceof CustomerOrder
637
+ ? relation
638
+ : CustomerOrder.fromRecord({ id: relation });
639
+ return new CustomerOrderExpression(target, this.root, path);
640
+ }
641
+
642
+ }
643
+
644
+ export class PlatformListExpression {
645
+ constructor(
646
+ private readonly items: readonly Platform[],
647
+ private readonly root = 'Platform(null)',
648
+ private readonly path = '',
649
+ private readonly present = true,
650
+ private readonly notLoaded?: TeaQLNotLoadedError,
651
+ ) {}
652
+
653
+ static missing(root?: string, path = ''): PlatformListExpression {
654
+ return new PlatformListExpression([], root, path, false);
655
+ }
656
+
657
+ size(): ValueExpression<number> {
658
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
659
+ return this.present
660
+ ? new ValueExpression<number>(this.items.length)
661
+ : ValueExpression.missing<number>();
662
+ }
663
+
664
+ first(): PlatformExpression {
665
+ return this.get(0);
666
+ }
667
+
668
+ get(index: number): PlatformExpression {
669
+ const itemPath = expressionPath(this.path, `get(${index})`);
670
+ if (this.notLoaded) {
671
+ return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded);
672
+ }
673
+ return !this.present || index < 0 || index >= this.items.length
674
+ ? new PlatformExpression(undefined, this.root, itemPath)
675
+ : new PlatformExpression(this.items[index], this.root, itemPath);
676
+ }
677
+ }
678
+
679
+ export class OrderStatusListExpression {
680
+ constructor(
681
+ private readonly items: readonly OrderStatus[],
682
+ private readonly root = 'OrderStatus(null)',
683
+ private readonly path = '',
684
+ private readonly present = true,
685
+ private readonly notLoaded?: TeaQLNotLoadedError,
686
+ ) {}
687
+
688
+ static missing(root?: string, path = ''): OrderStatusListExpression {
689
+ return new OrderStatusListExpression([], root, path, false);
690
+ }
691
+
692
+ size(): ValueExpression<number> {
693
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
694
+ return this.present
695
+ ? new ValueExpression<number>(this.items.length)
696
+ : ValueExpression.missing<number>();
697
+ }
698
+
699
+ first(): OrderStatusExpression {
700
+ return this.get(0);
701
+ }
702
+
703
+ get(index: number): OrderStatusExpression {
704
+ const itemPath = expressionPath(this.path, `get(${index})`);
705
+ if (this.notLoaded) {
706
+ return new OrderStatusExpression(undefined, this.root, itemPath, this.notLoaded);
707
+ }
708
+ return !this.present || index < 0 || index >= this.items.length
709
+ ? new OrderStatusExpression(undefined, this.root, itemPath)
710
+ : new OrderStatusExpression(this.items[index], this.root, itemPath);
711
+ }
712
+ }
713
+
714
+ export class CustomerListExpression {
715
+ constructor(
716
+ private readonly items: readonly Customer[],
717
+ private readonly root = 'Customer(null)',
718
+ private readonly path = '',
719
+ private readonly present = true,
720
+ private readonly notLoaded?: TeaQLNotLoadedError,
721
+ ) {}
722
+
723
+ static missing(root?: string, path = ''): CustomerListExpression {
724
+ return new CustomerListExpression([], root, path, false);
725
+ }
726
+
727
+ size(): ValueExpression<number> {
728
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
729
+ return this.present
730
+ ? new ValueExpression<number>(this.items.length)
731
+ : ValueExpression.missing<number>();
732
+ }
733
+
734
+ first(): CustomerExpression {
735
+ return this.get(0);
736
+ }
737
+
738
+ get(index: number): CustomerExpression {
739
+ const itemPath = expressionPath(this.path, `get(${index})`);
740
+ if (this.notLoaded) {
741
+ return new CustomerExpression(undefined, this.root, itemPath, this.notLoaded);
742
+ }
743
+ return !this.present || index < 0 || index >= this.items.length
744
+ ? new CustomerExpression(undefined, this.root, itemPath)
745
+ : new CustomerExpression(this.items[index], this.root, itemPath);
746
+ }
747
+ }
748
+
749
+ export class CustomerOrderListExpression {
750
+ constructor(
751
+ private readonly items: readonly CustomerOrder[],
752
+ private readonly root = 'CustomerOrder(null)',
753
+ private readonly path = '',
754
+ private readonly present = true,
755
+ private readonly notLoaded?: TeaQLNotLoadedError,
756
+ ) {}
757
+
758
+ static missing(root?: string, path = ''): CustomerOrderListExpression {
759
+ return new CustomerOrderListExpression([], root, path, false);
760
+ }
761
+
762
+ size(): ValueExpression<number> {
763
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
764
+ return this.present
765
+ ? new ValueExpression<number>(this.items.length)
766
+ : ValueExpression.missing<number>();
767
+ }
768
+
769
+ first(): CustomerOrderExpression {
770
+ return this.get(0);
771
+ }
772
+
773
+ get(index: number): CustomerOrderExpression {
774
+ const itemPath = expressionPath(this.path, `get(${index})`);
775
+ if (this.notLoaded) {
776
+ return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded);
777
+ }
778
+ return !this.present || index < 0 || index >= this.items.length
779
+ ? new CustomerOrderExpression(undefined, this.root, itemPath)
780
+ : new CustomerOrderExpression(this.items[index], this.root, itemPath);
781
+ }
782
+ }
783
+
784
+ export class OrderItemListExpression {
785
+ constructor(
786
+ private readonly items: readonly OrderItem[],
787
+ private readonly root = 'OrderItem(null)',
788
+ private readonly path = '',
789
+ private readonly present = true,
790
+ private readonly notLoaded?: TeaQLNotLoadedError,
791
+ ) {}
792
+
793
+ static missing(root?: string, path = ''): OrderItemListExpression {
794
+ return new OrderItemListExpression([], root, path, false);
795
+ }
796
+
797
+ size(): ValueExpression<number> {
798
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded);
799
+ return this.present
800
+ ? new ValueExpression<number>(this.items.length)
801
+ : ValueExpression.missing<number>();
802
+ }
803
+
804
+ first(): OrderItemExpression {
805
+ return this.get(0);
806
+ }
807
+
808
+ get(index: number): OrderItemExpression {
809
+ const itemPath = expressionPath(this.path, `get(${index})`);
810
+ if (this.notLoaded) {
811
+ return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded);
812
+ }
813
+ return !this.present || index < 0 || index >= this.items.length
814
+ ? new OrderItemExpression(undefined, this.root, itemPath)
815
+ : new OrderItemExpression(this.items[index], this.root, itemPath);
816
+ }
817
+ }
818
+
819
+ export class E {
820
+ static platform(
821
+ value: Platform | null | undefined,
822
+ ): PlatformExpression {
823
+ return new PlatformExpression(
824
+ value, `Platform(id=${value?.id ?? 'null'})`,
825
+ );
826
+ }
827
+
828
+ static orderStatus(
829
+ value: OrderStatus | null | undefined,
830
+ ): OrderStatusExpression {
831
+ return new OrderStatusExpression(
832
+ value, `OrderStatus(id=${value?.id ?? 'null'})`,
833
+ );
834
+ }
835
+
836
+ static customer(
837
+ value: Customer | null | undefined,
838
+ ): CustomerExpression {
839
+ return new CustomerExpression(
840
+ value, `Customer(id=${value?.id ?? 'null'})`,
841
+ );
842
+ }
843
+
844
+ static customerOrder(
845
+ value: CustomerOrder | null | undefined,
846
+ ): CustomerOrderExpression {
847
+ return new CustomerOrderExpression(
848
+ value, `CustomerOrder(id=${value?.id ?? 'null'})`,
849
+ );
850
+ }
851
+
852
+ static orderItem(
853
+ value: OrderItem | null | undefined,
854
+ ): OrderItemExpression {
855
+ return new OrderItemExpression(
856
+ value, `OrderItem(id=${value?.id ?? 'null'})`,
857
+ );
858
+ }
859
+ }
source/browser-sqlite/orders-lib/src/generated/Q.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { TeaQLClient } from '../teaql-ts';
2
+ import { PlatformRequest } from './requests/PlatformRequest';
3
+ import { OrderStatusRequest } from './requests/OrderStatusRequest';
4
+ import { CustomerRequest } from './requests/CustomerRequest';
5
+ import { CustomerOrderRequest } from './requests/CustomerOrderRequest';
6
+ import { OrderItemRequest } from './requests/OrderItemRequest';
7
+
8
+ export class Q {
9
+ static platforms(): PlatformRequest {
10
+ return new PlatformRequest(false);
11
+ }
12
+
13
+ static platformsWithMinimalFields(): PlatformRequest {
14
+ return new PlatformRequest(true);
15
+ }
16
+ static orderStatuses(): OrderStatusRequest {
17
+ return new OrderStatusRequest(false);
18
+ }
19
+
20
+ static orderStatusesWithMinimalFields(): OrderStatusRequest {
21
+ return new OrderStatusRequest(true);
22
+ }
23
+ static customers(): CustomerRequest {
24
+ return new CustomerRequest(false);
25
+ }
26
+
27
+ static customersWithMinimalFields(): CustomerRequest {
28
+ return new CustomerRequest(true);
29
+ }
30
+ static customerOrders(): CustomerOrderRequest {
31
+ return new CustomerOrderRequest(false);
32
+ }
33
+
34
+ static customerOrdersWithMinimalFields(): CustomerOrderRequest {
35
+ return new CustomerOrderRequest(true);
36
+ }
37
+ static orderItems(): OrderItemRequest {
38
+ return new OrderItemRequest(false);
39
+ }
40
+
41
+ static orderItemsWithMinimalFields(): OrderItemRequest {
42
+ return new OrderItemRequest(true);
43
+ }
44
+ }
source/browser-sqlite/orders-lib/src/generated/models/Customer.ts ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, TeaQLDataService, UserContext } from '../../teaql-ts';
2
+ import { Platform } from './Platform';
3
+ import { CustomerOrder } from './CustomerOrder';
4
+
5
+ export class Customer {
6
+ private static teaqlTemporaryId = 0;
7
+ id?: string;
8
+ platform?: Platform | string;
9
+ name?: string;
10
+ version?: number;
11
+
12
+ constructor(init?: Partial<Customer>) {
13
+ Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
14
+ Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
15
+ Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
16
+ Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
17
+ Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
18
+ Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Customer.teaqlTemporaryId, writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false });
20
+ if (init) {
21
+ const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
22
+ delete fields["customerOrderList"];
23
+ Object.assign(this, fields);
24
+ if ((init as any).platform && typeof (init as any).platform === "object") {
25
+ this.platform = (init as any).platform instanceof Platform
26
+ ? (init as any).platform
27
+ : Platform.fromRecord((init as any).platform);
28
+ this.markLoaded("platform");
29
+ }
30
+ if (Array.isArray((init as any).customerOrderList)) {
31
+ (this as any)._customerOrderList = (init as any).customerOrderList.map(
32
+ (child: unknown) => child instanceof CustomerOrder
33
+ ? child
34
+ : CustomerOrder.fromRecord(child as Record<string, unknown>),
35
+ );
36
+ this.markLoaded("customerOrderList");
37
+ }
38
+ }
39
+ const key = this.teaqlEntityKey();
40
+ if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
41
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
42
+ }
43
+
44
+ private teaqlEntityKey(): EntityKey { return { entity: "Customer", id: (this as any)._ledgerId }; }
45
+ private teaqlAttachRoot(root: EntityRoot): this {
46
+ if ((this as any)._root !== root) { root.mergeFrom((this as any)._root); (this as any)._root = root; }
47
+ for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root);
48
+ return this;
49
+ }
50
+
51
+ static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Customer {
52
+ const entity = new Customer(record as Partial<Customer>);
53
+ return root ? entity.teaqlAttachRoot(root) : entity;
54
+ }
55
+
56
+ isLoaded(field: string): boolean {
57
+ return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field);
58
+ }
59
+
60
+ markLoaded(...fields: string[]): this {
61
+ for (const field of fields) (this as any)._loadedFields.add(field);
62
+ return this;
63
+ }
64
+
65
+ markLoadedOnly(...fields: string[]): this {
66
+ (this as any)._fullyLoaded = false;
67
+ (this as any)._loadedFields = new Set(fields);
68
+ return this;
69
+ }
70
+
71
+ static refer(id: string | number): Customer {
72
+ return new Customer({ id: String(id) } as Partial<Customer>);
73
+ }
74
+
75
+ /** @internal Generated Runtime Module fixed-ID construction capability. */
76
+ static teaqlBootstrapNew(id: string | number): Customer {
77
+ return new Customer().updateId(String(id));
78
+ }
79
+
80
+ markForDeletion(): this {
81
+ (this as any)._action = "Delete";
82
+ (this as any)._root.markAsDeleted(this.teaqlEntityKey());
83
+ return this;
84
+ }
85
+
86
+ auditAs(comment: string): this {
87
+ if (!comment?.trim()) {
88
+ throw new Error("Security audit failure: auditAs() requires a non-empty reason");
89
+ }
90
+ (this as any)._comment = comment;
91
+ return this;
92
+ }
93
+
94
+ async save(context: UserContext): Promise<Customer> {
95
+ const service = context.requireResource<TeaQLDataService>("dataService");
96
+ return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
97
+ this.teaqlPreflightGraph(context, service, graph);
98
+ return this.teaqlSaveWithinGraph(context, service, graph);
99
+ });
100
+ }
101
+
102
+ /** @internal Validates and fixes the complete graph before its first mutation. */
103
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
104
+ if (!parent && !(this as any)._comment?.trim()) {
105
+ throw new Error("Security audit failure: auditAs() must be called before save()");
106
+ }
107
+ const action = (this as any)._action;
108
+ if (action === "Update") {
109
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]
110
+ .find(field => !this.isLoaded(field.member));
111
+ if (notLoaded) {
112
+ throw new CheckException([{
113
+ ruleId: "invalid_type",
114
+ location: ObjectLocation.property(notLoaded.canonical),
115
+ message: "Mutation requires a fully loaded entity",
116
+ }]);
117
+ }
118
+ }
119
+ const request = graph.request({
120
+ entity: "Customer", action,
121
+ payload: action === "Update"
122
+ ? (this as any)._root.change(this.teaqlEntityKey())
123
+ : this.teaqlMutationPayload(),
124
+ id: (this as any).id, version: (this as any).version,
125
+ comment: (this as any)._comment,
126
+ ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
127
+ }, parent, (this as any)._comment).withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
128
+ service.preflightMutation(request);
129
+ const scope = request.scopeFor(this.teaqlEntityKey());
130
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
131
+ child.teaqlAttachRoot((this as any)._root);
132
+ child.updateCustomer(this);
133
+ try { child.teaqlPreflightGraph(context, service, graph, scope); }
134
+ catch (error) {
135
+ if (!(error instanceof CheckException)) throw error;
136
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
137
+ throw new CheckException(error.violations.map(violation => ({
138
+ ...violation, location: violation.location.prefixedBy(prefix),
139
+ })));
140
+ }
141
+ }
142
+ }
143
+
144
+ /** @internal Used by generated relation cascades inside the root graph transaction. */
145
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<Customer> {
146
+ if (!parent && !(this as any)._comment?.trim()) {
147
+ throw new Error("Security audit failure: auditAs() must be called before save()");
148
+ }
149
+ const action = (this as any)._action;
150
+ const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
151
+ const mutation = {
152
+ entity: "Customer",
153
+ action: (this as any)._action,
154
+ payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
155
+ id: (this as any).id,
156
+ version: (this as any).version,
157
+ comment: (this as any)._comment
158
+ ,ledgerKey: this.teaqlEntityKey()
159
+ ,ledgerRoot: (this as any)._root
160
+ };
161
+ const request = graph.request(mutation, parent, (this as any)._comment)
162
+ .withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
163
+ const result = await service.executeMutation(request);
164
+ for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
165
+ if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
166
+ }
167
+ if (!result.persistedRecord) {
168
+ throw new Error("Mutation did not return the authoritative persisted record");
169
+ }
170
+ const rollbackState = {
171
+ payload: this.teaqlMutationPayload(),
172
+ ledgerId: (this as any)._ledgerId,
173
+ action: (this as any)._action,
174
+ loadedFields: new Set((this as any)._loadedFields),
175
+ fullyLoaded: (this as any)._fullyLoaded,
176
+ };
177
+ const oldKey = this.teaqlEntityKey();
178
+ Object.assign(this, result.persistedRecord);
179
+ (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
180
+ const newKey = this.teaqlEntityKey();
181
+ (this as any)._root.rekey(oldKey, newKey);
182
+ service.afterGraphRollback(() => {
183
+ Object.assign(this, rollbackState.payload);
184
+ (this as any)._ledgerId = rollbackState.ledgerId;
185
+ (this as any)._action = rollbackState.action;
186
+ (this as any)._loadedFields = rollbackState.loadedFields;
187
+ (this as any)._fullyLoaded = rollbackState.fullyLoaded;
188
+ (this as any)._root.rekey(newKey, oldKey);
189
+ });
190
+ (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
191
+ (this as any)._fullyLoaded = false;
192
+ if (mutation.action !== "Delete") (this as any)._action = "Update";
193
+ const scope = request.scopeFor(newKey);
194
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
195
+ child.teaqlAttachRoot((this as any)._root);
196
+ child.updateCustomer(this);
197
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
198
+ catch (error) {
199
+ if (!(error instanceof CheckException)) throw error;
200
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
201
+ throw new CheckException(error.violations.map(violation => ({
202
+ ...violation, location: violation.location.prefixedBy(prefix),
203
+ })));
204
+ }
205
+ }
206
+ service.afterGraphCommit(() => {
207
+ (this as any)._root.clearEntity(newKey);
208
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
209
+ });
210
+ return this;
211
+ }
212
+
213
+ private teaqlMutationPayload(): Record<string, unknown> {
214
+ return {
215
+ "id": this.id,
216
+ "platform": this.platform,
217
+ "name": this.name,
218
+ "version": this.version
219
+ };
220
+ }
221
+
222
+ updateId(value: string): this {
223
+ this.id = value;
224
+ this.markLoaded("id");
225
+ (this as any)._root.set(this.teaqlEntityKey(), "id", value);
226
+ return this;
227
+ }
228
+
229
+ updateName(value: string): this {
230
+ this.name = value;
231
+ this.markLoaded("name");
232
+ (this as any)._root.set(this.teaqlEntityKey(), "name", value);
233
+ return this;
234
+ }
235
+
236
+ updateVersion(value: number): this {
237
+ this.version = value;
238
+ this.markLoaded("version");
239
+ (this as any)._root.set(this.teaqlEntityKey(), "version", value);
240
+ return this;
241
+ }
242
+ updatePlatform(value: any): this {
243
+ this.platform = value?.id ?? value;
244
+ this.markLoaded("platform");
245
+ (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform);
246
+ return this;
247
+ }
248
+
249
+ customerOrderList(): CustomerOrder[] {
250
+ return (this as any)._customerOrderList;
251
+ }
252
+ }
source/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, TeaQLDataService, UserContext } from '../../teaql-ts';
2
+ import { Customer } from './Customer';
3
+ import { OrderStatus } from './OrderStatus';
4
+ import { OrderItem } from './OrderItem';
5
+
6
+ export class CustomerOrder {
7
+ private static teaqlTemporaryId = 0;
8
+ id?: string;
9
+ customer?: Customer | string;
10
+ status?: OrderStatus | string;
11
+ orderNumber?: string;
12
+ orderDate?: string;
13
+ totalAmount?: number;
14
+ version?: number;
15
+
16
+ constructor(init?: Partial<CustomerOrder>) {
17
+ Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
18
+ Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
20
+ Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
21
+ Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
22
+ Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --CustomerOrder.teaqlTemporaryId, writable: true, enumerable: false });
23
+ Object.defineProperty(this, "_orderItemList", { value: [], writable: true, enumerable: false });
24
+ if (init) {
25
+ const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
26
+ delete fields["orderItemList"];
27
+ Object.assign(this, fields);
28
+ if ((init as any).customer && typeof (init as any).customer === "object") {
29
+ this.customer = (init as any).customer instanceof Customer
30
+ ? (init as any).customer
31
+ : Customer.fromRecord((init as any).customer);
32
+ this.markLoaded("customer");
33
+ }
34
+ if ((init as any).status && typeof (init as any).status === "object") {
35
+ this.status = (init as any).status instanceof OrderStatus
36
+ ? (init as any).status
37
+ : OrderStatus.fromRecord((init as any).status);
38
+ this.markLoaded("status");
39
+ }
40
+ if (Array.isArray((init as any).orderItemList)) {
41
+ (this as any)._orderItemList = (init as any).orderItemList.map(
42
+ (child: unknown) => child instanceof OrderItem
43
+ ? child
44
+ : OrderItem.fromRecord(child as Record<string, unknown>),
45
+ );
46
+ this.markLoaded("orderItemList");
47
+ }
48
+ }
49
+ const key = this.teaqlEntityKey();
50
+ if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
51
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
52
+ }
53
+
54
+ private teaqlEntityKey(): EntityKey { return { entity: "CustomerOrder", id: (this as any)._ledgerId }; }
55
+ private teaqlAttachRoot(root: EntityRoot): this {
56
+ if ((this as any)._root !== root) { root.mergeFrom((this as any)._root); (this as any)._root = root; }
57
+ for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root);
58
+ return this;
59
+ }
60
+
61
+ static fromRecord(record: Record<string, unknown>, root?: EntityRoot): CustomerOrder {
62
+ const entity = new CustomerOrder(record as Partial<CustomerOrder>);
63
+ return root ? entity.teaqlAttachRoot(root) : entity;
64
+ }
65
+
66
+ isLoaded(field: string): boolean {
67
+ return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field);
68
+ }
69
+
70
+ markLoaded(...fields: string[]): this {
71
+ for (const field of fields) (this as any)._loadedFields.add(field);
72
+ return this;
73
+ }
74
+
75
+ markLoadedOnly(...fields: string[]): this {
76
+ (this as any)._fullyLoaded = false;
77
+ (this as any)._loadedFields = new Set(fields);
78
+ return this;
79
+ }
80
+
81
+ static refer(id: string | number): CustomerOrder {
82
+ return new CustomerOrder({ id: String(id) } as Partial<CustomerOrder>);
83
+ }
84
+
85
+ /** @internal Generated Runtime Module fixed-ID construction capability. */
86
+ static teaqlBootstrapNew(id: string | number): CustomerOrder {
87
+ return new CustomerOrder().updateId(String(id));
88
+ }
89
+
90
+ markForDeletion(): this {
91
+ (this as any)._action = "Delete";
92
+ (this as any)._root.markAsDeleted(this.teaqlEntityKey());
93
+ return this;
94
+ }
95
+
96
+ auditAs(comment: string): this {
97
+ if (!comment?.trim()) {
98
+ throw new Error("Security audit failure: auditAs() requires a non-empty reason");
99
+ }
100
+ (this as any)._comment = comment;
101
+ return this;
102
+ }
103
+
104
+ async save(context: UserContext): Promise<CustomerOrder> {
105
+ const service = context.requireResource<TeaQLDataService>("dataService");
106
+ return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
107
+ this.teaqlPreflightGraph(context, service, graph);
108
+ return this.teaqlSaveWithinGraph(context, service, graph);
109
+ });
110
+ }
111
+
112
+ /** @internal Validates and fixes the complete graph before its first mutation. */
113
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
114
+ if (!parent && !(this as any)._comment?.trim()) {
115
+ throw new Error("Security audit failure: auditAs() must be called before save()");
116
+ }
117
+ const action = (this as any)._action;
118
+ if (action === "Update") {
119
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "customer", canonical: "customer" }, { member: "status", canonical: "status" }, { member: "orderNumber", canonical: "order_number" }, { member: "orderDate", canonical: "order_date" }, { member: "totalAmount", canonical: "total_amount" }, { member: "version", canonical: "version" }]
120
+ .find(field => !this.isLoaded(field.member));
121
+ if (notLoaded) {
122
+ throw new CheckException([{
123
+ ruleId: "invalid_type",
124
+ location: ObjectLocation.property(notLoaded.canonical),
125
+ message: "Mutation requires a fully loaded entity",
126
+ }]);
127
+ }
128
+ }
129
+ const request = graph.request({
130
+ entity: "CustomerOrder", action,
131
+ payload: action === "Update"
132
+ ? (this as any)._root.change(this.teaqlEntityKey())
133
+ : this.teaqlMutationPayload(),
134
+ id: (this as any).id, version: (this as any).version,
135
+ comment: (this as any)._comment,
136
+ ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
137
+ }, parent, (this as any)._comment).withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
138
+ service.preflightMutation(request);
139
+ const scope = request.scopeFor(this.teaqlEntityKey());
140
+ for (const [index, child] of (this as any)._orderItemList.entries()) {
141
+ child.teaqlAttachRoot((this as any)._root);
142
+ child.updateCustomerOrder(this);
143
+ try { child.teaqlPreflightGraph(context, service, graph, scope); }
144
+ catch (error) {
145
+ if (!(error instanceof CheckException)) throw error;
146
+ const prefix = ObjectLocation.property("order_item_list").index(index);
147
+ throw new CheckException(error.violations.map(violation => ({
148
+ ...violation, location: violation.location.prefixedBy(prefix),
149
+ })));
150
+ }
151
+ }
152
+ }
153
+
154
+ /** @internal Used by generated relation cascades inside the root graph transaction. */
155
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<CustomerOrder> {
156
+ if (!parent && !(this as any)._comment?.trim()) {
157
+ throw new Error("Security audit failure: auditAs() must be called before save()");
158
+ }
159
+ const action = (this as any)._action;
160
+ const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
161
+ const mutation = {
162
+ entity: "CustomerOrder",
163
+ action: (this as any)._action,
164
+ payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
165
+ id: (this as any).id,
166
+ version: (this as any).version,
167
+ comment: (this as any)._comment
168
+ ,ledgerKey: this.teaqlEntityKey()
169
+ ,ledgerRoot: (this as any)._root
170
+ };
171
+ const request = graph.request(mutation, parent, (this as any)._comment)
172
+ .withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
173
+ const result = await service.executeMutation(request);
174
+ for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
175
+ if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
176
+ }
177
+ if (!result.persistedRecord) {
178
+ throw new Error("Mutation did not return the authoritative persisted record");
179
+ }
180
+ const rollbackState = {
181
+ payload: this.teaqlMutationPayload(),
182
+ ledgerId: (this as any)._ledgerId,
183
+ action: (this as any)._action,
184
+ loadedFields: new Set((this as any)._loadedFields),
185
+ fullyLoaded: (this as any)._fullyLoaded,
186
+ };
187
+ const oldKey = this.teaqlEntityKey();
188
+ Object.assign(this, result.persistedRecord);
189
+ (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
190
+ const newKey = this.teaqlEntityKey();
191
+ (this as any)._root.rekey(oldKey, newKey);
192
+ service.afterGraphRollback(() => {
193
+ Object.assign(this, rollbackState.payload);
194
+ (this as any)._ledgerId = rollbackState.ledgerId;
195
+ (this as any)._action = rollbackState.action;
196
+ (this as any)._loadedFields = rollbackState.loadedFields;
197
+ (this as any)._fullyLoaded = rollbackState.fullyLoaded;
198
+ (this as any)._root.rekey(newKey, oldKey);
199
+ });
200
+ (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
201
+ (this as any)._fullyLoaded = false;
202
+ if (mutation.action !== "Delete") (this as any)._action = "Update";
203
+ const scope = request.scopeFor(newKey);
204
+ for (const [index, child] of (this as any)._orderItemList.entries()) {
205
+ child.teaqlAttachRoot((this as any)._root);
206
+ child.updateCustomerOrder(this);
207
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
208
+ catch (error) {
209
+ if (!(error instanceof CheckException)) throw error;
210
+ const prefix = ObjectLocation.property("order_item_list").index(index);
211
+ throw new CheckException(error.violations.map(violation => ({
212
+ ...violation, location: violation.location.prefixedBy(prefix),
213
+ })));
214
+ }
215
+ }
216
+ service.afterGraphCommit(() => {
217
+ (this as any)._root.clearEntity(newKey);
218
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
219
+ });
220
+ return this;
221
+ }
222
+
223
+ private teaqlMutationPayload(): Record<string, unknown> {
224
+ return {
225
+ "id": this.id,
226
+ "customer": this.customer,
227
+ "status": this.status,
228
+ "order_number": this.orderNumber,
229
+ "order_date": this.orderDate,
230
+ "total_amount": this.totalAmount,
231
+ "version": this.version
232
+ };
233
+ }
234
+
235
+ updateId(value: string): this {
236
+ this.id = value;
237
+ this.markLoaded("id");
238
+ (this as any)._root.set(this.teaqlEntityKey(), "id", value);
239
+ return this;
240
+ }
241
+
242
+ updateOrderNumber(value: string): this {
243
+ this.orderNumber = value;
244
+ this.markLoaded("orderNumber");
245
+ (this as any)._root.set(this.teaqlEntityKey(), "order_number", value);
246
+ return this;
247
+ }
248
+
249
+ updateOrderDate(value: string): this {
250
+ this.orderDate = value;
251
+ this.markLoaded("orderDate");
252
+ (this as any)._root.set(this.teaqlEntityKey(), "order_date", value);
253
+ return this;
254
+ }
255
+
256
+ updateTotalAmount(value: number): this {
257
+ this.totalAmount = value;
258
+ this.markLoaded("totalAmount");
259
+ (this as any)._root.set(this.teaqlEntityKey(), "total_amount", value);
260
+ return this;
261
+ }
262
+
263
+ updateVersion(value: number): this {
264
+ this.version = value;
265
+ this.markLoaded("version");
266
+ (this as any)._root.set(this.teaqlEntityKey(), "version", value);
267
+ return this;
268
+ }
269
+ updateCustomer(value: any): this {
270
+ this.customer = value?.id ?? value;
271
+ this.markLoaded("customer");
272
+ (this as any)._root.set(this.teaqlEntityKey(), "customer", this.customer);
273
+ return this;
274
+ }
275
+
276
+
277
+ updateStatus(value: any): this {
278
+ this.status = value?.id ?? value;
279
+ this.markLoaded("status");
280
+ (this as any)._root.set(this.teaqlEntityKey(), "status", this.status);
281
+ return this;
282
+ }
283
+ public updateStatusToNew(): CustomerOrder {
284
+ this.status = "1001";
285
+ this.markLoaded("status");
286
+ (this as any)._root.set(this.teaqlEntityKey(), "status", this.status);
287
+ return this;
288
+ }
289
+ public updateStatusToPaid(): CustomerOrder {
290
+ this.status = "1002";
291
+ this.markLoaded("status");
292
+ (this as any)._root.set(this.teaqlEntityKey(), "status", this.status);
293
+ return this;
294
+ }
295
+ public updateStatusToCancelled(): CustomerOrder {
296
+ this.status = "1003";
297
+ this.markLoaded("status");
298
+ (this as any)._root.set(this.teaqlEntityKey(), "status", this.status);
299
+ return this;
300
+ }
301
+
302
+ orderItemList(): OrderItem[] {
303
+ return (this as any)._orderItemList;
304
+ }
305
+ }
source/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, TeaQLDataService, UserContext } from '../../teaql-ts';
2
+ import { CustomerOrder } from './CustomerOrder';
3
+
4
+ export class OrderItem {
5
+ private static teaqlTemporaryId = 0;
6
+ id?: string;
7
+ customerOrder?: CustomerOrder | string;
8
+ productName?: string;
9
+ quantity?: number;
10
+ unitPrice?: number;
11
+ version?: number;
12
+
13
+ constructor(init?: Partial<OrderItem>) {
14
+ Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
15
+ Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
16
+ Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
17
+ Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
18
+ Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderItem.teaqlTemporaryId, writable: true, enumerable: false });
20
+ if (init) {
21
+ const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
22
+ Object.assign(this, fields);
23
+ if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") {
24
+ this.customerOrder = (init as any).customerOrder instanceof CustomerOrder
25
+ ? (init as any).customerOrder
26
+ : CustomerOrder.fromRecord((init as any).customerOrder);
27
+ this.markLoaded("customerOrder");
28
+ }
29
+ }
30
+ const key = this.teaqlEntityKey();
31
+ if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
32
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
33
+ }
34
+
35
+ private teaqlEntityKey(): EntityKey { return { entity: "OrderItem", id: (this as any)._ledgerId }; }
36
+ private teaqlAttachRoot(root: EntityRoot): this {
37
+ if ((this as any)._root !== root) { root.mergeFrom((this as any)._root); (this as any)._root = root; }
38
+ return this;
39
+ }
40
+
41
+ static fromRecord(record: Record<string, unknown>, root?: EntityRoot): OrderItem {
42
+ const entity = new OrderItem(record as Partial<OrderItem>);
43
+ return root ? entity.teaqlAttachRoot(root) : entity;
44
+ }
45
+
46
+ isLoaded(field: string): boolean {
47
+ return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field);
48
+ }
49
+
50
+ markLoaded(...fields: string[]): this {
51
+ for (const field of fields) (this as any)._loadedFields.add(field);
52
+ return this;
53
+ }
54
+
55
+ markLoadedOnly(...fields: string[]): this {
56
+ (this as any)._fullyLoaded = false;
57
+ (this as any)._loadedFields = new Set(fields);
58
+ return this;
59
+ }
60
+
61
+ static refer(id: string | number): OrderItem {
62
+ return new OrderItem({ id: String(id) } as Partial<OrderItem>);
63
+ }
64
+
65
+ /** @internal Generated Runtime Module fixed-ID construction capability. */
66
+ static teaqlBootstrapNew(id: string | number): OrderItem {
67
+ return new OrderItem().updateId(String(id));
68
+ }
69
+
70
+ markForDeletion(): this {
71
+ (this as any)._action = "Delete";
72
+ (this as any)._root.markAsDeleted(this.teaqlEntityKey());
73
+ return this;
74
+ }
75
+
76
+ auditAs(comment: string): this {
77
+ if (!comment?.trim()) {
78
+ throw new Error("Security audit failure: auditAs() requires a non-empty reason");
79
+ }
80
+ (this as any)._comment = comment;
81
+ return this;
82
+ }
83
+
84
+ async save(context: UserContext): Promise<OrderItem> {
85
+ const service = context.requireResource<TeaQLDataService>("dataService");
86
+ return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
87
+ this.teaqlPreflightGraph(context, service, graph);
88
+ return this.teaqlSaveWithinGraph(context, service, graph);
89
+ });
90
+ }
91
+
92
+ /** @internal Validates and fixes the complete graph before its first mutation. */
93
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
94
+ if (!parent && !(this as any)._comment?.trim()) {
95
+ throw new Error("Security audit failure: auditAs() must be called before save()");
96
+ }
97
+ const action = (this as any)._action;
98
+ if (action === "Update") {
99
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "productName", canonical: "product_name" }, { member: "quantity", canonical: "quantity" }, { member: "unitPrice", canonical: "unit_price" }, { member: "version", canonical: "version" }]
100
+ .find(field => !this.isLoaded(field.member));
101
+ if (notLoaded) {
102
+ throw new CheckException([{
103
+ ruleId: "invalid_type",
104
+ location: ObjectLocation.property(notLoaded.canonical),
105
+ message: "Mutation requires a fully loaded entity",
106
+ }]);
107
+ }
108
+ }
109
+ const request = graph.request({
110
+ entity: "OrderItem", action,
111
+ payload: action === "Update"
112
+ ? (this as any)._root.change(this.teaqlEntityKey())
113
+ : this.teaqlMutationPayload(),
114
+ id: (this as any).id, version: (this as any).version,
115
+ comment: (this as any)._comment,
116
+ ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
117
+ }, parent, (this as any)._comment).withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
118
+ service.preflightMutation(request);
119
+ const scope = request.scopeFor(this.teaqlEntityKey());
120
+ }
121
+
122
+ /** @internal Used by generated relation cascades inside the root graph transaction. */
123
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<OrderItem> {
124
+ if (!parent && !(this as any)._comment?.trim()) {
125
+ throw new Error("Security audit failure: auditAs() must be called before save()");
126
+ }
127
+ const action = (this as any)._action;
128
+ const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
129
+ const mutation = {
130
+ entity: "OrderItem",
131
+ action: (this as any)._action,
132
+ payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
133
+ id: (this as any).id,
134
+ version: (this as any).version,
135
+ comment: (this as any)._comment
136
+ ,ledgerKey: this.teaqlEntityKey()
137
+ ,ledgerRoot: (this as any)._root
138
+ };
139
+ const request = graph.request(mutation, parent, (this as any)._comment)
140
+ .withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
141
+ const result = await service.executeMutation(request);
142
+ for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
143
+ if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
144
+ }
145
+ if (!result.persistedRecord) {
146
+ throw new Error("Mutation did not return the authoritative persisted record");
147
+ }
148
+ const rollbackState = {
149
+ payload: this.teaqlMutationPayload(),
150
+ ledgerId: (this as any)._ledgerId,
151
+ action: (this as any)._action,
152
+ loadedFields: new Set((this as any)._loadedFields),
153
+ fullyLoaded: (this as any)._fullyLoaded,
154
+ };
155
+ const oldKey = this.teaqlEntityKey();
156
+ Object.assign(this, result.persistedRecord);
157
+ (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
158
+ const newKey = this.teaqlEntityKey();
159
+ (this as any)._root.rekey(oldKey, newKey);
160
+ service.afterGraphRollback(() => {
161
+ Object.assign(this, rollbackState.payload);
162
+ (this as any)._ledgerId = rollbackState.ledgerId;
163
+ (this as any)._action = rollbackState.action;
164
+ (this as any)._loadedFields = rollbackState.loadedFields;
165
+ (this as any)._fullyLoaded = rollbackState.fullyLoaded;
166
+ (this as any)._root.rekey(newKey, oldKey);
167
+ });
168
+ (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
169
+ (this as any)._fullyLoaded = false;
170
+ if (mutation.action !== "Delete") (this as any)._action = "Update";
171
+ const scope = request.scopeFor(newKey);
172
+ service.afterGraphCommit(() => {
173
+ (this as any)._root.clearEntity(newKey);
174
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
175
+ });
176
+ return this;
177
+ }
178
+
179
+ private teaqlMutationPayload(): Record<string, unknown> {
180
+ return {
181
+ "id": this.id,
182
+ "customer_order": this.customerOrder,
183
+ "product_name": this.productName,
184
+ "quantity": this.quantity,
185
+ "unit_price": this.unitPrice,
186
+ "version": this.version
187
+ };
188
+ }
189
+
190
+ updateId(value: string): this {
191
+ this.id = value;
192
+ this.markLoaded("id");
193
+ (this as any)._root.set(this.teaqlEntityKey(), "id", value);
194
+ return this;
195
+ }
196
+
197
+ updateProductName(value: string): this {
198
+ this.productName = value;
199
+ this.markLoaded("productName");
200
+ (this as any)._root.set(this.teaqlEntityKey(), "product_name", value);
201
+ return this;
202
+ }
203
+
204
+ updateQuantity(value: number): this {
205
+ this.quantity = value;
206
+ this.markLoaded("quantity");
207
+ (this as any)._root.set(this.teaqlEntityKey(), "quantity", value);
208
+ return this;
209
+ }
210
+
211
+ updateUnitPrice(value: number): this {
212
+ this.unitPrice = value;
213
+ this.markLoaded("unitPrice");
214
+ (this as any)._root.set(this.teaqlEntityKey(), "unit_price", value);
215
+ return this;
216
+ }
217
+
218
+ updateVersion(value: number): this {
219
+ this.version = value;
220
+ this.markLoaded("version");
221
+ (this as any)._root.set(this.teaqlEntityKey(), "version", value);
222
+ return this;
223
+ }
224
+ updateCustomerOrder(value: any): this {
225
+ this.customerOrder = value?.id ?? value;
226
+ this.markLoaded("customerOrder");
227
+ (this as any)._root.set(this.teaqlEntityKey(), "customer_order", this.customerOrder);
228
+ return this;
229
+ }
230
+
231
+ }
source/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, TeaQLDataService, UserContext } from '../../teaql-ts';
2
+ import { Platform } from './Platform';
3
+ import { CustomerOrder } from './CustomerOrder';
4
+
5
+ export class OrderStatus {
6
+ private static teaqlTemporaryId = 0;
7
+ platform?: Platform | string;
8
+ id?: string;
9
+ name?: string;
10
+ code?: string;
11
+ color?: string;
12
+ displayOrder?: number;
13
+ version?: number;
14
+
15
+ constructor(init?: Partial<OrderStatus>) {
16
+ Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
17
+ Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
18
+ Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
20
+ Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
21
+ Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderStatus.teaqlTemporaryId, writable: true, enumerable: false });
22
+ Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false });
23
+ if (init) {
24
+ const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
25
+ delete fields["customerOrderList"];
26
+ Object.assign(this, fields);
27
+ if ((init as any).platform && typeof (init as any).platform === "object") {
28
+ this.platform = (init as any).platform instanceof Platform
29
+ ? (init as any).platform
30
+ : Platform.fromRecord((init as any).platform);
31
+ this.markLoaded("platform");
32
+ }
33
+ if (Array.isArray((init as any).customerOrderList)) {
34
+ (this as any)._customerOrderList = (init as any).customerOrderList.map(
35
+ (child: unknown) => child instanceof CustomerOrder
36
+ ? child
37
+ : CustomerOrder.fromRecord(child as Record<string, unknown>),
38
+ );
39
+ this.markLoaded("customerOrderList");
40
+ }
41
+ }
42
+ const key = this.teaqlEntityKey();
43
+ if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
44
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
45
+ }
46
+
47
+ private teaqlEntityKey(): EntityKey { return { entity: "OrderStatus", id: (this as any)._ledgerId }; }
48
+ private teaqlAttachRoot(root: EntityRoot): this {
49
+ if ((this as any)._root !== root) { root.mergeFrom((this as any)._root); (this as any)._root = root; }
50
+ for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root);
51
+ return this;
52
+ }
53
+
54
+ static fromRecord(record: Record<string, unknown>, root?: EntityRoot): OrderStatus {
55
+ const entity = new OrderStatus(record as Partial<OrderStatus>);
56
+ return root ? entity.teaqlAttachRoot(root) : entity;
57
+ }
58
+
59
+ isLoaded(field: string): boolean {
60
+ return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field);
61
+ }
62
+
63
+ markLoaded(...fields: string[]): this {
64
+ for (const field of fields) (this as any)._loadedFields.add(field);
65
+ return this;
66
+ }
67
+
68
+ markLoadedOnly(...fields: string[]): this {
69
+ (this as any)._fullyLoaded = false;
70
+ (this as any)._loadedFields = new Set(fields);
71
+ return this;
72
+ }
73
+
74
+ static refer(id: string | number): OrderStatus {
75
+ return new OrderStatus({ id: String(id) } as Partial<OrderStatus>);
76
+ }
77
+
78
+ /** @internal Generated Runtime Module fixed-ID construction capability. */
79
+ static teaqlBootstrapNew(id: string | number): OrderStatus {
80
+ return new OrderStatus().updateId(String(id));
81
+ }
82
+
83
+ markForDeletion(): this {
84
+ (this as any)._action = "Delete";
85
+ (this as any)._root.markAsDeleted(this.teaqlEntityKey());
86
+ return this;
87
+ }
88
+
89
+ auditAs(comment: string): this {
90
+ if (!comment?.trim()) {
91
+ throw new Error("Security audit failure: auditAs() requires a non-empty reason");
92
+ }
93
+ (this as any)._comment = comment;
94
+ return this;
95
+ }
96
+
97
+ async save(context: UserContext): Promise<OrderStatus> {
98
+ const service = context.requireResource<TeaQLDataService>("dataService");
99
+ return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
100
+ this.teaqlPreflightGraph(context, service, graph);
101
+ return this.teaqlSaveWithinGraph(context, service, graph);
102
+ });
103
+ }
104
+
105
+ /** @internal Validates and fixes the complete graph before its first mutation. */
106
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
107
+ if (!parent && !(this as any)._comment?.trim()) {
108
+ throw new Error("Security audit failure: auditAs() must be called before save()");
109
+ }
110
+ const action = (this as any)._action;
111
+ if (action === "Update") {
112
+ const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "color", canonical: "color" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }]
113
+ .find(field => !this.isLoaded(field.member));
114
+ if (notLoaded) {
115
+ throw new CheckException([{
116
+ ruleId: "invalid_type",
117
+ location: ObjectLocation.property(notLoaded.canonical),
118
+ message: "Mutation requires a fully loaded entity",
119
+ }]);
120
+ }
121
+ }
122
+ const request = graph.request({
123
+ entity: "OrderStatus", action,
124
+ payload: action === "Update"
125
+ ? (this as any)._root.change(this.teaqlEntityKey())
126
+ : this.teaqlMutationPayload(),
127
+ id: (this as any).id, version: (this as any).version,
128
+ comment: (this as any)._comment,
129
+ ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
130
+ }, parent, (this as any)._comment).withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
131
+ service.preflightMutation(request);
132
+ const scope = request.scopeFor(this.teaqlEntityKey());
133
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
134
+ child.teaqlAttachRoot((this as any)._root);
135
+ child.updateStatus(this);
136
+ try { child.teaqlPreflightGraph(context, service, graph, scope); }
137
+ catch (error) {
138
+ if (!(error instanceof CheckException)) throw error;
139
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
140
+ throw new CheckException(error.violations.map(violation => ({
141
+ ...violation, location: violation.location.prefixedBy(prefix),
142
+ })));
143
+ }
144
+ }
145
+ }
146
+
147
+ /** @internal Used by generated relation cascades inside the root graph transaction. */
148
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<OrderStatus> {
149
+ if (!parent && !(this as any)._comment?.trim()) {
150
+ throw new Error("Security audit failure: auditAs() must be called before save()");
151
+ }
152
+ const action = (this as any)._action;
153
+ const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
154
+ const mutation = {
155
+ entity: "OrderStatus",
156
+ action: (this as any)._action,
157
+ payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
158
+ id: (this as any).id,
159
+ version: (this as any).version,
160
+ comment: (this as any)._comment
161
+ ,ledgerKey: this.teaqlEntityKey()
162
+ ,ledgerRoot: (this as any)._root
163
+ };
164
+ const request = graph.request(mutation, parent, (this as any)._comment)
165
+ .withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
166
+ const result = await service.executeMutation(request);
167
+ for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
168
+ if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
169
+ }
170
+ if (!result.persistedRecord) {
171
+ throw new Error("Mutation did not return the authoritative persisted record");
172
+ }
173
+ const rollbackState = {
174
+ payload: this.teaqlMutationPayload(),
175
+ ledgerId: (this as any)._ledgerId,
176
+ action: (this as any)._action,
177
+ loadedFields: new Set((this as any)._loadedFields),
178
+ fullyLoaded: (this as any)._fullyLoaded,
179
+ };
180
+ const oldKey = this.teaqlEntityKey();
181
+ Object.assign(this, result.persistedRecord);
182
+ (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
183
+ const newKey = this.teaqlEntityKey();
184
+ (this as any)._root.rekey(oldKey, newKey);
185
+ service.afterGraphRollback(() => {
186
+ Object.assign(this, rollbackState.payload);
187
+ (this as any)._ledgerId = rollbackState.ledgerId;
188
+ (this as any)._action = rollbackState.action;
189
+ (this as any)._loadedFields = rollbackState.loadedFields;
190
+ (this as any)._fullyLoaded = rollbackState.fullyLoaded;
191
+ (this as any)._root.rekey(newKey, oldKey);
192
+ });
193
+ (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
194
+ (this as any)._fullyLoaded = false;
195
+ if (mutation.action !== "Delete") (this as any)._action = "Update";
196
+ const scope = request.scopeFor(newKey);
197
+ for (const [index, child] of (this as any)._customerOrderList.entries()) {
198
+ child.teaqlAttachRoot((this as any)._root);
199
+ child.updateStatus(this);
200
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
201
+ catch (error) {
202
+ if (!(error instanceof CheckException)) throw error;
203
+ const prefix = ObjectLocation.property("customer_order_list").index(index);
204
+ throw new CheckException(error.violations.map(violation => ({
205
+ ...violation, location: violation.location.prefixedBy(prefix),
206
+ })));
207
+ }
208
+ }
209
+ service.afterGraphCommit(() => {
210
+ (this as any)._root.clearEntity(newKey);
211
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
212
+ });
213
+ return this;
214
+ }
215
+
216
+ private teaqlMutationPayload(): Record<string, unknown> {
217
+ return {
218
+ "platform": this.platform,
219
+ "id": this.id,
220
+ "name": this.name,
221
+ "code": this.code,
222
+ "color": this.color,
223
+ "display_order": this.displayOrder,
224
+ "version": this.version
225
+ };
226
+ }
227
+
228
+ updateId(value: string): this {
229
+ this.id = value;
230
+ this.markLoaded("id");
231
+ (this as any)._root.set(this.teaqlEntityKey(), "id", value);
232
+ return this;
233
+ }
234
+
235
+ updateName(value: string): this {
236
+ this.name = value;
237
+ this.markLoaded("name");
238
+ (this as any)._root.set(this.teaqlEntityKey(), "name", value);
239
+ return this;
240
+ }
241
+
242
+ updateCode(value: string): this {
243
+ this.code = value;
244
+ this.markLoaded("code");
245
+ (this as any)._root.set(this.teaqlEntityKey(), "code", value);
246
+ return this;
247
+ }
248
+
249
+ updateColor(value: string): this {
250
+ this.color = value;
251
+ this.markLoaded("color");
252
+ (this as any)._root.set(this.teaqlEntityKey(), "color", value);
253
+ return this;
254
+ }
255
+
256
+ updateDisplayOrder(value: number): this {
257
+ this.displayOrder = value;
258
+ this.markLoaded("displayOrder");
259
+ (this as any)._root.set(this.teaqlEntityKey(), "display_order", value);
260
+ return this;
261
+ }
262
+
263
+ updateVersion(value: number): this {
264
+ this.version = value;
265
+ this.markLoaded("version");
266
+ (this as any)._root.set(this.teaqlEntityKey(), "version", value);
267
+ return this;
268
+ }
269
+ updatePlatform(value: any): this {
270
+ this.platform = value?.id ?? value;
271
+ this.markLoaded("platform");
272
+ (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform);
273
+ return this;
274
+ }
275
+
276
+ customerOrderList(): CustomerOrder[] {
277
+ return (this as any)._customerOrderList;
278
+ }
279
+ }
source/browser-sqlite/orders-lib/src/generated/models/Platform.ts ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, TeaQLDataService, UserContext } from '../../teaql-ts';
2
+ import { OrderStatus } from './OrderStatus';
3
+ import { Customer } from './Customer';
4
+
5
+ export class Platform {
6
+ private static teaqlTemporaryId = 0;
7
+ id?: string;
8
+ name?: string;
9
+ version?: number;
10
+
11
+ constructor(init?: Partial<Platform>) {
12
+ Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
13
+ Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
14
+ Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
15
+ Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
16
+ Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
17
+ Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false });
18
+ Object.defineProperty(this, "_orderStatusList", { value: [], writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_customerList", { value: [], writable: true, enumerable: false });
20
+ if (init) {
21
+ const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
22
+ delete fields["orderStatusList"];
23
+ delete fields["customerList"];
24
+ Object.assign(this, fields);
25
+ if (Array.isArray((init as any).orderStatusList)) {
26
+ (this as any)._orderStatusList = (init as any).orderStatusList.map(
27
+ (child: unknown) => child instanceof OrderStatus
28
+ ? child
29
+ : OrderStatus.fromRecord(child as Record<string, unknown>),
30
+ );
31
+ this.markLoaded("orderStatusList");
32
+ }
33
+ if (Array.isArray((init as any).customerList)) {
34
+ (this as any)._customerList = (init as any).customerList.map(
35
+ (child: unknown) => child instanceof Customer
36
+ ? child
37
+ : Customer.fromRecord(child as Record<string, unknown>),
38
+ );
39
+ this.markLoaded("customerList");
40
+ }
41
+ }
42
+ const key = this.teaqlEntityKey();
43
+ if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
44
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version));
45
+ }
46
+
47
+ private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; }
48
+ private teaqlAttachRoot(root: EntityRoot): this {
49
+ if ((this as any)._root !== root) { root.mergeFrom((this as any)._root); (this as any)._root = root; }
50
+ for (const child of (this as any)._orderStatusList) child.teaqlAttachRoot(root);
51
+ for (const child of (this as any)._customerList) child.teaqlAttachRoot(root);
52
+ return this;
53
+ }
54
+
55
+ static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Platform {
56
+ const entity = new Platform(record as Partial<Platform>);
57
+ return root ? entity.teaqlAttachRoot(root) : entity;
58
+ }
59
+
60
+ isLoaded(field: string): boolean {
61
+ return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field);
62
+ }
63
+
64
+ markLoaded(...fields: string[]): this {
65
+ for (const field of fields) (this as any)._loadedFields.add(field);
66
+ return this;
67
+ }
68
+
69
+ markLoadedOnly(...fields: string[]): this {
70
+ (this as any)._fullyLoaded = false;
71
+ (this as any)._loadedFields = new Set(fields);
72
+ return this;
73
+ }
74
+
75
+ static refer(id: string | number): Platform {
76
+ return new Platform({ id: String(id) } as Partial<Platform>);
77
+ }
78
+
79
+ /** @internal Generated Runtime Module fixed-ID construction capability. */
80
+ static teaqlBootstrapNew(id: string | number): Platform {
81
+ return new Platform().updateId(String(id));
82
+ }
83
+
84
+ markForDeletion(): this {
85
+ (this as any)._action = "Delete";
86
+ (this as any)._root.markAsDeleted(this.teaqlEntityKey());
87
+ return this;
88
+ }
89
+
90
+ auditAs(comment: string): this {
91
+ if (!comment?.trim()) {
92
+ throw new Error("Security audit failure: auditAs() requires a non-empty reason");
93
+ }
94
+ (this as any)._comment = comment;
95
+ return this;
96
+ }
97
+
98
+ async save(context: UserContext): Promise<Platform> {
99
+ const service = context.requireResource<TeaQLDataService>("dataService");
100
+ return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
101
+ this.teaqlPreflightGraph(context, service, graph);
102
+ return this.teaqlSaveWithinGraph(context, service, graph);
103
+ });
104
+ }
105
+
106
+ /** @internal Validates and fixes the complete graph before its first mutation. */
107
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
108
+ if (!parent && !(this as any)._comment?.trim()) {
109
+ throw new Error("Security audit failure: auditAs() must be called before save()");
110
+ }
111
+ const action = (this as any)._action;
112
+ if (action === "Update") {
113
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]
114
+ .find(field => !this.isLoaded(field.member));
115
+ if (notLoaded) {
116
+ throw new CheckException([{
117
+ ruleId: "invalid_type",
118
+ location: ObjectLocation.property(notLoaded.canonical),
119
+ message: "Mutation requires a fully loaded entity",
120
+ }]);
121
+ }
122
+ }
123
+ const request = graph.request({
124
+ entity: "Platform", action,
125
+ payload: action === "Update"
126
+ ? (this as any)._root.change(this.teaqlEntityKey())
127
+ : this.teaqlMutationPayload(),
128
+ id: (this as any).id, version: (this as any).version,
129
+ comment: (this as any)._comment,
130
+ ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
131
+ }, parent, (this as any)._comment).withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
132
+ service.preflightMutation(request);
133
+ const scope = request.scopeFor(this.teaqlEntityKey());
134
+ for (const [index, child] of (this as any)._orderStatusList.entries()) {
135
+ child.teaqlAttachRoot((this as any)._root);
136
+ child.updatePlatform(this);
137
+ try { child.teaqlPreflightGraph(context, service, graph, scope); }
138
+ catch (error) {
139
+ if (!(error instanceof CheckException)) throw error;
140
+ const prefix = ObjectLocation.property("order_status_list").index(index);
141
+ throw new CheckException(error.violations.map(violation => ({
142
+ ...violation, location: violation.location.prefixedBy(prefix),
143
+ })));
144
+ }
145
+ }
146
+ for (const [index, child] of (this as any)._customerList.entries()) {
147
+ child.teaqlAttachRoot((this as any)._root);
148
+ child.updatePlatform(this);
149
+ try { child.teaqlPreflightGraph(context, service, graph, scope); }
150
+ catch (error) {
151
+ if (!(error instanceof CheckException)) throw error;
152
+ const prefix = ObjectLocation.property("customer_list").index(index);
153
+ throw new CheckException(error.violations.map(violation => ({
154
+ ...violation, location: violation.location.prefixedBy(prefix),
155
+ })));
156
+ }
157
+ }
158
+ }
159
+
160
+ /** @internal Used by generated relation cascades inside the root graph transaction. */
161
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<Platform> {
162
+ if (!parent && !(this as any)._comment?.trim()) {
163
+ throw new Error("Security audit failure: auditAs() must be called before save()");
164
+ }
165
+ const action = (this as any)._action;
166
+ const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
167
+ const mutation = {
168
+ entity: "Platform",
169
+ action: (this as any)._action,
170
+ payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
171
+ id: (this as any).id,
172
+ version: (this as any).version,
173
+ comment: (this as any)._comment
174
+ ,ledgerKey: this.teaqlEntityKey()
175
+ ,ledgerRoot: (this as any)._root
176
+ };
177
+ const request = graph.request(mutation, parent, (this as any)._comment)
178
+ .withLoadedSnapshot(new LoadedScalarSnapshot(this.teaqlMutationPayload()));
179
+ const result = await service.executeMutation(request);
180
+ for (const [field, value] of Object.entries(mutation.payload as Record<string, unknown>)) {
181
+ if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value);
182
+ }
183
+ if (!result.persistedRecord) {
184
+ throw new Error("Mutation did not return the authoritative persisted record");
185
+ }
186
+ const rollbackState = {
187
+ payload: this.teaqlMutationPayload(),
188
+ ledgerId: (this as any)._ledgerId,
189
+ action: (this as any)._action,
190
+ loadedFields: new Set((this as any)._loadedFields),
191
+ fullyLoaded: (this as any)._fullyLoaded,
192
+ };
193
+ const oldKey = this.teaqlEntityKey();
194
+ Object.assign(this, result.persistedRecord);
195
+ (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
196
+ const newKey = this.teaqlEntityKey();
197
+ (this as any)._root.rekey(oldKey, newKey);
198
+ service.afterGraphRollback(() => {
199
+ Object.assign(this, rollbackState.payload);
200
+ (this as any)._ledgerId = rollbackState.ledgerId;
201
+ (this as any)._action = rollbackState.action;
202
+ (this as any)._loadedFields = rollbackState.loadedFields;
203
+ (this as any)._fullyLoaded = rollbackState.fullyLoaded;
204
+ (this as any)._root.rekey(newKey, oldKey);
205
+ });
206
+ (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
207
+ (this as any)._fullyLoaded = false;
208
+ if (mutation.action !== "Delete") (this as any)._action = "Update";
209
+ const scope = request.scopeFor(newKey);
210
+ for (const [index, child] of (this as any)._orderStatusList.entries()) {
211
+ child.teaqlAttachRoot((this as any)._root);
212
+ child.updatePlatform(this);
213
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
214
+ catch (error) {
215
+ if (!(error instanceof CheckException)) throw error;
216
+ const prefix = ObjectLocation.property("order_status_list").index(index);
217
+ throw new CheckException(error.violations.map(violation => ({
218
+ ...violation, location: violation.location.prefixedBy(prefix),
219
+ })));
220
+ }
221
+ }
222
+ for (const [index, child] of (this as any)._customerList.entries()) {
223
+ child.teaqlAttachRoot((this as any)._root);
224
+ child.updatePlatform(this);
225
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
226
+ catch (error) {
227
+ if (!(error instanceof CheckException)) throw error;
228
+ const prefix = ObjectLocation.property("customer_list").index(index);
229
+ throw new CheckException(error.violations.map(violation => ({
230
+ ...violation, location: violation.location.prefixedBy(prefix),
231
+ })));
232
+ }
233
+ }
234
+ service.afterGraphCommit(() => {
235
+ (this as any)._root.clearEntity(newKey);
236
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version));
237
+ });
238
+ return this;
239
+ }
240
+
241
+ private teaqlMutationPayload(): Record<string, unknown> {
242
+ return {
243
+ "id": this.id,
244
+ "name": this.name,
245
+ "version": this.version
246
+ };
247
+ }
248
+
249
+ updateId(value: string): this {
250
+ this.id = value;
251
+ this.markLoaded("id");
252
+ (this as any)._root.set(this.teaqlEntityKey(), "id", value);
253
+ return this;
254
+ }
255
+
256
+ updateName(value: string): this {
257
+ this.name = value;
258
+ this.markLoaded("name");
259
+ (this as any)._root.set(this.teaqlEntityKey(), "name", value);
260
+ return this;
261
+ }
262
+
263
+ updateVersion(value: number): this {
264
+ this.version = value;
265
+ this.markLoaded("version");
266
+ (this as any)._root.set(this.teaqlEntityKey(), "version", value);
267
+ return this;
268
+ }
269
+ orderStatusList(): OrderStatus[] {
270
+ return (this as any)._orderStatusList;
271
+ }
272
+
273
+ customerList(): Customer[] {
274
+ return (this as any)._customerList;
275
+ }
276
+ }
source/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts ADDED
@@ -0,0 +1,1206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, TeaQLPage, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { CustomerOrder } from '../models/CustomerOrder';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning } from 'teaql-ts';
4
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
+
6
+
7
+
8
+ export class CustomerOrderRequest {
9
+ private query: SelectQuery;
10
+ private filters: any[] = [];
11
+ private _purpose: string | undefined;
12
+ private _comment: string | undefined;
13
+ private _pageCountAlias: string | undefined;
14
+ private _pageCountMethod: "count" | "countAs" | undefined;
15
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
16
+
17
+ constructor(minimal = false) {
18
+ this.query = new SelectQuery("CustomerOrder");
19
+ this.filters.push({ version: { "$gte": 1 } });
20
+ if (minimal) {
21
+ this.selectId();
22
+ this.selectVersion();
23
+ }
24
+ else this.selectSelfFields();
25
+ }
26
+
27
+ comment(c: string): this {
28
+ this.query.comment(c);
29
+ this._comment = c;
30
+ return this;
31
+ }
32
+
33
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
34
+ const base = this.query.clone();
35
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
36
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
37
+ this.query = merged.query as SelectQuery;
38
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
39
+ this._dynamicSearchWarnings.push(...merged.warnings);
40
+ return this;
41
+ }
42
+
43
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
44
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
45
+ }
46
+
47
+ purpose(p: string): ExecutableCustomerOrderRequest {
48
+ this.query.purpose(p);
49
+ this._purpose = p;
50
+ return new ExecutableCustomerOrderRequest(
51
+ (context) => this.executeForListInternal(context),
52
+ (context) => this.executeForRowsInternal(context),
53
+ (context, offset, limit) => this.executeForPageInternal(context, offset, limit),
54
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
55
+ () => this.limit(1),
56
+ (c) => this.comment(c),
57
+ () => this.ensureIntent());
58
+ }
59
+
60
+ optimizeForContinuousPageFetch(): this {
61
+ this.query.optimizeForContinuousPageFetch();
62
+ return this;
63
+ }
64
+
65
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
66
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
67
+ return this;
68
+ }
69
+
70
+ optimizePaginationWithIdSet(): this {
71
+ this.query.optimizePaginationWithIdSet();
72
+ return this;
73
+ }
74
+
75
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
76
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
77
+ return this;
78
+ }
79
+
80
+ topNProbeParentThreshold(threshold: number): this {
81
+ this.query.topNProbeParentThreshold(threshold);
82
+ return this;
83
+ }
84
+
85
+ limit(n: number): this {
86
+ this.query.limit(n);
87
+ return this;
88
+ }
89
+
90
+ offset(n: number): this {
91
+ this.query.offset(n);
92
+ return this;
93
+ }
94
+
95
+ toQuery(): SelectQuery {
96
+ if (this.filters.length > 0) {
97
+ this.query.filter({ "$and": this.filters });
98
+ }
99
+ return this.query;
100
+ }
101
+
102
+ withDeletedRows(): this {
103
+ this.filters = this.filters.filter(filter => !("version" in filter));
104
+ return this;
105
+ }
106
+
107
+ deletedRowsOnly(): this {
108
+ this.withDeletedRows();
109
+ this.filters.push({ version: { "$lte": -1 } });
110
+ return this;
111
+ }
112
+
113
+ selectSelfFields(): this {
114
+ this.query.select(["id", "customer", "status", "orderNumber", "orderDate", "totalAmount", "version"]);
115
+ return this;
116
+ }
117
+
118
+ selectId(): this {
119
+ this.query.select(["id"]);
120
+ return this;
121
+ }
122
+
123
+
124
+
125
+ selectOrderNumber(): this {
126
+ this.query.select(["orderNumber"]);
127
+ return this;
128
+ }
129
+
130
+ selectOrderDate(): this {
131
+ this.query.select(["orderDate"]);
132
+ return this;
133
+ }
134
+
135
+ selectTotalAmount(): this {
136
+ this.query.select(["totalAmount"]);
137
+ return this;
138
+ }
139
+
140
+ selectVersion(): this {
141
+ this.query.select(["version"]);
142
+ return this;
143
+ }
144
+
145
+
146
+ selectCustomerWith(request: { toQuery(): SelectQuery }): this {
147
+ this.query.select(["customer"]);
148
+ this.query.relationQuery(
149
+ "customer", request.toQuery(), "customer", "id", false,
150
+ { kind: "relation-select", method: "selectCustomerWith", relation: "customer" });
151
+ return this;
152
+ }
153
+ selectStatusWith(request: { toQuery(): SelectQuery }): this {
154
+ this.query.select(["status"]);
155
+ this.query.relationQuery(
156
+ "status", request.toQuery(), "status", "id", false,
157
+ { kind: "relation-select", method: "selectStatusWith", relation: "status" });
158
+ return this;
159
+ }
160
+
161
+ withCustomerMatching(request: { toQuery(): SelectQuery }): this {
162
+ this.filters.push({
163
+ "customer": {
164
+ "$inSubquery": { query: request.toQuery(), field: "id" },
165
+ },
166
+ });
167
+ return this;
168
+ }
169
+
170
+ withoutCustomerMatching(request: { toQuery(): SelectQuery }): this {
171
+ this.filters.push({
172
+ "customer": {
173
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
174
+ },
175
+ });
176
+ return this;
177
+ }
178
+ withStatusMatching(request: { toQuery(): SelectQuery }): this {
179
+ this.filters.push({
180
+ "status": {
181
+ "$inSubquery": { query: request.toQuery(), field: "id" },
182
+ },
183
+ });
184
+ return this;
185
+ }
186
+
187
+ withoutStatusMatching(request: { toQuery(): SelectQuery }): this {
188
+ this.filters.push({
189
+ "status": {
190
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
191
+ },
192
+ });
193
+ return this;
194
+ }
195
+
196
+ selectOrderItemListWith(request: { toQuery(): SelectQuery }): this {
197
+ this.query.relationQuery(
198
+ "orderItemList", request.toQuery(), "id", "customerOrder", true,
199
+ { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" });
200
+ return this;
201
+ }
202
+
203
+ haveOrderItems(): this {
204
+ return this.withOrderItemListMatching({
205
+ toQuery: () => new SelectQuery("OrderItem"),
206
+ });
207
+ }
208
+
209
+ haveNoOrderItems(): this {
210
+ return this.withoutOrderItemListMatching({
211
+ toQuery: () => new SelectQuery("OrderItem"),
212
+ });
213
+ }
214
+
215
+ withOrderItemListMatching(request: { toQuery(): SelectQuery }): this {
216
+ this.filters.push({
217
+ "id": {
218
+ "$inSubquery": {
219
+ query: request.toQuery(), field: "customerOrder",
220
+ },
221
+ },
222
+ });
223
+ return this;
224
+ }
225
+
226
+ withoutOrderItemListMatching(request: { toQuery(): SelectQuery }): this {
227
+ this.filters.push({
228
+ "id": {
229
+ "$notInSubquery": {
230
+ query: request.toQuery(), field: "customerOrder",
231
+ },
232
+ },
233
+ });
234
+ return this;
235
+ }
236
+
237
+ countOrderItems(): this {
238
+ return this.countOrderItemsAs("countOrderItems");
239
+ }
240
+
241
+ countOrderItemsAs(alias: string): this {
242
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
243
+ this.countOrderItemsWith(alias, { toQuery: () => query });
244
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
245
+ kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias };
246
+ return this;
247
+ }
248
+
249
+ countOrderItemsWith(alias: string, child: { toQuery(): SelectQuery }): this {
250
+ const query = child.toQuery().clone();
251
+ query.aggregateItems = [];
252
+ query.aggregate("Count", "id", alias);
253
+ this.query.relationAggregate("orderItemList", alias, query, true,
254
+ { kind: "relation-count", method: "countOrderItemsWith", relation: "orderItemList", alias });
255
+ return this;
256
+ }
257
+
258
+ minQuantityOfOrderItems(): this {
259
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
260
+ return this.minQuantityOfOrderItemsAs(
261
+ "minOfQuantityOfOrderItems", { toQuery: () => query });
262
+ }
263
+
264
+ minQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
265
+ const query = child.toQuery().clone();
266
+ query.aggregateItems = [];
267
+ query.aggregate("min", "quantity", alias);
268
+ this.query.relationAggregate("orderItemList", alias, query, true,
269
+ { kind: "aggregate", method: "minQuantityOfOrderItemsAs", relation: "orderItemList", alias });
270
+ return this;
271
+ }
272
+ maxQuantityOfOrderItems(): this {
273
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
274
+ return this.maxQuantityOfOrderItemsAs(
275
+ "maxOfQuantityOfOrderItems", { toQuery: () => query });
276
+ }
277
+
278
+ maxQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
279
+ const query = child.toQuery().clone();
280
+ query.aggregateItems = [];
281
+ query.aggregate("max", "quantity", alias);
282
+ this.query.relationAggregate("orderItemList", alias, query, true,
283
+ { kind: "aggregate", method: "maxQuantityOfOrderItemsAs", relation: "orderItemList", alias });
284
+ return this;
285
+ }
286
+ sumQuantityOfOrderItems(): this {
287
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
288
+ return this.sumQuantityOfOrderItemsAs(
289
+ "sumOfQuantityOfOrderItems", { toQuery: () => query });
290
+ }
291
+
292
+ sumQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
293
+ const query = child.toQuery().clone();
294
+ query.aggregateItems = [];
295
+ query.aggregate("sum", "quantity", alias);
296
+ this.query.relationAggregate("orderItemList", alias, query, true,
297
+ { kind: "aggregate", method: "sumQuantityOfOrderItemsAs", relation: "orderItemList", alias });
298
+ return this;
299
+ }
300
+ avgQuantityOfOrderItems(): this {
301
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
302
+ return this.avgQuantityOfOrderItemsAs(
303
+ "avgOfQuantityOfOrderItems", { toQuery: () => query });
304
+ }
305
+
306
+ avgQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
307
+ const query = child.toQuery().clone();
308
+ query.aggregateItems = [];
309
+ query.aggregate("avg", "quantity", alias);
310
+ this.query.relationAggregate("orderItemList", alias, query, true,
311
+ { kind: "aggregate", method: "avgQuantityOfOrderItemsAs", relation: "orderItemList", alias });
312
+ return this;
313
+ }
314
+ standardDeviationQuantityOfOrderItems(): this {
315
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
316
+ return this.standardDeviationQuantityOfOrderItemsAs(
317
+ "standardDeviationOfQuantityOfOrderItems", { toQuery: () => query });
318
+ }
319
+
320
+ standardDeviationQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
321
+ const query = child.toQuery().clone();
322
+ query.aggregateItems = [];
323
+ query.aggregate("stddev", "quantity", alias);
324
+ this.query.relationAggregate("orderItemList", alias, query, true,
325
+ { kind: "aggregate", method: "standardDeviationQuantityOfOrderItemsAs", relation: "orderItemList", alias });
326
+ return this;
327
+ }
328
+ squareRootOfPopulationStandardDeviationQuantityOfOrderItems(): this {
329
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
330
+ return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(
331
+ "squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems", { toQuery: () => query });
332
+ }
333
+
334
+ squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
335
+ const query = child.toQuery().clone();
336
+ query.aggregateItems = [];
337
+ query.aggregate("stddev_pop", "quantity", alias);
338
+ this.query.relationAggregate("orderItemList", alias, query, true,
339
+ { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs", relation: "orderItemList", alias });
340
+ return this;
341
+ }
342
+ sampleVarianceQuantityOfOrderItems(): this {
343
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
344
+ return this.sampleVarianceQuantityOfOrderItemsAs(
345
+ "sampleVarianceOfQuantityOfOrderItems", { toQuery: () => query });
346
+ }
347
+
348
+ sampleVarianceQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
349
+ const query = child.toQuery().clone();
350
+ query.aggregateItems = [];
351
+ query.aggregate("var_samp", "quantity", alias);
352
+ this.query.relationAggregate("orderItemList", alias, query, true,
353
+ { kind: "aggregate", method: "sampleVarianceQuantityOfOrderItemsAs", relation: "orderItemList", alias });
354
+ return this;
355
+ }
356
+ samplePopulationVarianceQuantityOfOrderItems(): this {
357
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
358
+ return this.samplePopulationVarianceQuantityOfOrderItemsAs(
359
+ "samplePopulationVarianceOfQuantityOfOrderItems", { toQuery: () => query });
360
+ }
361
+
362
+ samplePopulationVarianceQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
363
+ const query = child.toQuery().clone();
364
+ query.aggregateItems = [];
365
+ query.aggregate("var_pop", "quantity", alias);
366
+ this.query.relationAggregate("orderItemList", alias, query, true,
367
+ { kind: "aggregate", method: "samplePopulationVarianceQuantityOfOrderItemsAs", relation: "orderItemList", alias });
368
+ return this;
369
+ }
370
+ minUnitPriceOfOrderItems(): this {
371
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
372
+ return this.minUnitPriceOfOrderItemsAs(
373
+ "minOfUnitPriceOfOrderItems", { toQuery: () => query });
374
+ }
375
+
376
+ minUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
377
+ const query = child.toQuery().clone();
378
+ query.aggregateItems = [];
379
+ query.aggregate("min", "unitPrice", alias);
380
+ this.query.relationAggregate("orderItemList", alias, query, true,
381
+ { kind: "aggregate", method: "minUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
382
+ return this;
383
+ }
384
+ maxUnitPriceOfOrderItems(): this {
385
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
386
+ return this.maxUnitPriceOfOrderItemsAs(
387
+ "maxOfUnitPriceOfOrderItems", { toQuery: () => query });
388
+ }
389
+
390
+ maxUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
391
+ const query = child.toQuery().clone();
392
+ query.aggregateItems = [];
393
+ query.aggregate("max", "unitPrice", alias);
394
+ this.query.relationAggregate("orderItemList", alias, query, true,
395
+ { kind: "aggregate", method: "maxUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
396
+ return this;
397
+ }
398
+ sumUnitPriceOfOrderItems(): this {
399
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
400
+ return this.sumUnitPriceOfOrderItemsAs(
401
+ "sumOfUnitPriceOfOrderItems", { toQuery: () => query });
402
+ }
403
+
404
+ sumUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
405
+ const query = child.toQuery().clone();
406
+ query.aggregateItems = [];
407
+ query.aggregate("sum", "unitPrice", alias);
408
+ this.query.relationAggregate("orderItemList", alias, query, true,
409
+ { kind: "aggregate", method: "sumUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
410
+ return this;
411
+ }
412
+ avgUnitPriceOfOrderItems(): this {
413
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
414
+ return this.avgUnitPriceOfOrderItemsAs(
415
+ "avgOfUnitPriceOfOrderItems", { toQuery: () => query });
416
+ }
417
+
418
+ avgUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
419
+ const query = child.toQuery().clone();
420
+ query.aggregateItems = [];
421
+ query.aggregate("avg", "unitPrice", alias);
422
+ this.query.relationAggregate("orderItemList", alias, query, true,
423
+ { kind: "aggregate", method: "avgUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
424
+ return this;
425
+ }
426
+ standardDeviationUnitPriceOfOrderItems(): this {
427
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
428
+ return this.standardDeviationUnitPriceOfOrderItemsAs(
429
+ "standardDeviationOfUnitPriceOfOrderItems", { toQuery: () => query });
430
+ }
431
+
432
+ standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
433
+ const query = child.toQuery().clone();
434
+ query.aggregateItems = [];
435
+ query.aggregate("stddev", "unitPrice", alias);
436
+ this.query.relationAggregate("orderItemList", alias, query, true,
437
+ { kind: "aggregate", method: "standardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
438
+ return this;
439
+ }
440
+ squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this {
441
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
442
+ return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(
443
+ "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { toQuery: () => query });
444
+ }
445
+
446
+ squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
447
+ const query = child.toQuery().clone();
448
+ query.aggregateItems = [];
449
+ query.aggregate("stddev_pop", "unitPrice", alias);
450
+ this.query.relationAggregate("orderItemList", alias, query, true,
451
+ { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
452
+ return this;
453
+ }
454
+ sampleVarianceUnitPriceOfOrderItems(): this {
455
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
456
+ return this.sampleVarianceUnitPriceOfOrderItemsAs(
457
+ "sampleVarianceOfUnitPriceOfOrderItems", { toQuery: () => query });
458
+ }
459
+
460
+ sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
461
+ const query = child.toQuery().clone();
462
+ query.aggregateItems = [];
463
+ query.aggregate("var_samp", "unitPrice", alias);
464
+ this.query.relationAggregate("orderItemList", alias, query, true,
465
+ { kind: "aggregate", method: "sampleVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
466
+ return this;
467
+ }
468
+ samplePopulationVarianceUnitPriceOfOrderItems(): this {
469
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
470
+ return this.samplePopulationVarianceUnitPriceOfOrderItemsAs(
471
+ "samplePopulationVarianceOfUnitPriceOfOrderItems", { toQuery: () => query });
472
+ }
473
+
474
+ samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this {
475
+ const query = child.toQuery().clone();
476
+ query.aggregateItems = [];
477
+ query.aggregate("var_pop", "unitPrice", alias);
478
+ this.query.relationAggregate("orderItemList", alias, query, true,
479
+ { kind: "aggregate", method: "samplePopulationVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
480
+ return this;
481
+ }
482
+
483
+ withIdIs(val: any): this {
484
+ this.filters.push({ "id": { "$eq": val } });
485
+ return this;
486
+ }
487
+
488
+ withIdIsNot(val: any): this {
489
+ this.filters.push({ "id": { "$ne": val } });
490
+ return this;
491
+ }
492
+
493
+ withIdIn(...vals: any[]): this {
494
+ this.filters.push({ "id": { "$in": vals } });
495
+ return this;
496
+ }
497
+
498
+ withIdNotIn(...vals: any[]): this {
499
+ this.filters.push({ "id": { "$notIn": vals } });
500
+ return this;
501
+ }
502
+
503
+ withIdGreaterThan(val: any): this {
504
+ this.filters.push({ "id": { "$gt": val } });
505
+ return this;
506
+ }
507
+
508
+ withIdGreaterThanOrEqualTo(val: any): this {
509
+ this.filters.push({ "id": { "$gte": val } });
510
+ return this;
511
+ }
512
+
513
+ withIdLessThan(val: any): this {
514
+ this.filters.push({ "id": { "$lt": val } });
515
+ return this;
516
+ }
517
+
518
+ withIdLessThanOrEqualTo(val: any): this {
519
+ this.filters.push({ "id": { "$lte": val } });
520
+ return this;
521
+ }
522
+
523
+ withIdBetween(lower: any, upper: any): this {
524
+ this.filters.push({ "id": { "$between": [lower, upper] } });
525
+ return this;
526
+ }
527
+
528
+ withIdIsKnown(): this {
529
+ this.filters.push({ "id": { "$isNull": false } });
530
+ return this;
531
+ }
532
+
533
+ withIdIsUnknown(): this {
534
+ this.filters.push({ "id": { "$isNull": true } });
535
+ return this;
536
+ }
537
+
538
+ filterByCustomer(val: any): this {
539
+ this.filters.push({ "customer": { "$eq": val } });
540
+ return this;
541
+ }
542
+
543
+ filterByCustomerIn(...vals: any[]): this {
544
+ this.filters.push({ "customer": { "$in": vals } });
545
+ return this;
546
+ }
547
+
548
+ withCustomerIsKnown(): this {
549
+ this.filters.push({ "customer": { "$isNull": false } });
550
+ return this;
551
+ }
552
+
553
+ withCustomerIsUnknown(): this {
554
+ this.filters.push({ "customer": { "$isNull": true } });
555
+ return this;
556
+ }
557
+
558
+ filterByStatus(val: any): this {
559
+ this.filters.push({ "status": { "$eq": val } });
560
+ return this;
561
+ }
562
+
563
+ filterByStatusIn(...vals: any[]): this {
564
+ this.filters.push({ "status": { "$in": vals } });
565
+ return this;
566
+ }
567
+
568
+ withStatusIsKnown(): this {
569
+ this.filters.push({ "status": { "$isNull": false } });
570
+ return this;
571
+ }
572
+
573
+ withStatusIsUnknown(): this {
574
+ this.filters.push({ "status": { "$isNull": true } });
575
+ return this;
576
+ }
577
+ withStatusIsNew(): this {
578
+ this.filters.push({ "status": { "$eq": "1001" } });
579
+ return this;
580
+ }
581
+ withStatusIsPaid(): this {
582
+ this.filters.push({ "status": { "$eq": "1002" } });
583
+ return this;
584
+ }
585
+ withStatusIsCancelled(): this {
586
+ this.filters.push({ "status": { "$eq": "1003" } });
587
+ return this;
588
+ }
589
+
590
+ withOrderNumberContaining(val: string): this {
591
+ this.filters.push({ "orderNumber": { "$contains": val } });
592
+ return this;
593
+ }
594
+
595
+ withOrderNumberIs(val: string): this {
596
+ this.filters.push({ "orderNumber": { "$eq": val } });
597
+ return this;
598
+ }
599
+
600
+ withOrderNumberIsNot(val: any): this {
601
+ this.filters.push({ "orderNumber": { "$ne": val } });
602
+ return this;
603
+ }
604
+
605
+ withOrderNumberIn(...vals: any[]): this {
606
+ this.filters.push({ "orderNumber": { "$in": vals } });
607
+ return this;
608
+ }
609
+
610
+ withOrderNumberNotIn(...vals: any[]): this {
611
+ this.filters.push({ "orderNumber": { "$notIn": vals } });
612
+ return this;
613
+ }
614
+
615
+ withOrderNumberGreaterThan(val: any): this {
616
+ this.filters.push({ "orderNumber": { "$gt": val } });
617
+ return this;
618
+ }
619
+
620
+ withOrderNumberGreaterThanOrEqualTo(val: any): this {
621
+ this.filters.push({ "orderNumber": { "$gte": val } });
622
+ return this;
623
+ }
624
+
625
+ withOrderNumberLessThan(val: any): this {
626
+ this.filters.push({ "orderNumber": { "$lt": val } });
627
+ return this;
628
+ }
629
+
630
+ withOrderNumberLessThanOrEqualTo(val: any): this {
631
+ this.filters.push({ "orderNumber": { "$lte": val } });
632
+ return this;
633
+ }
634
+
635
+ withOrderNumberBetween(lower: any, upper: any): this {
636
+ this.filters.push({ "orderNumber": { "$between": [lower, upper] } });
637
+ return this;
638
+ }
639
+
640
+ withOrderNumberIsKnown(): this {
641
+ this.filters.push({ "orderNumber": { "$isNull": false } });
642
+ return this;
643
+ }
644
+
645
+ withOrderNumberIsUnknown(): this {
646
+ this.filters.push({ "orderNumber": { "$isNull": true } });
647
+ return this;
648
+ }
649
+ withOrderNumberNotContaining(val: string): this {
650
+ this.filters.push({ "orderNumber": { "$notContains": val } });
651
+ return this;
652
+ }
653
+
654
+ withOrderNumberStartingWith(val: string): this {
655
+ this.filters.push({ "orderNumber": { "$startsWith": val } });
656
+ return this;
657
+ }
658
+
659
+ withOrderNumberNotStartingWith(val: string): this {
660
+ this.filters.push({ "orderNumber": { "$notStartsWith": val } });
661
+ return this;
662
+ }
663
+
664
+ withOrderNumberEndingWith(val: string): this {
665
+ this.filters.push({ "orderNumber": { "$endsWith": val } });
666
+ return this;
667
+ }
668
+
669
+ withOrderNumberNotEndingWith(val: string): this {
670
+ this.filters.push({ "orderNumber": { "$notEndsWith": val } });
671
+ return this;
672
+ }
673
+
674
+ withOrderNumberSoundingLike(val: string): this {
675
+ this.filters.push({ "orderNumber": { "$soundLike": val } });
676
+ return this;
677
+ }
678
+
679
+ withOrderDateIs(val: any): this {
680
+ this.filters.push({ "orderDate": { "$eq": val } });
681
+ return this;
682
+ }
683
+
684
+ withOrderDateIsNot(val: any): this {
685
+ this.filters.push({ "orderDate": { "$ne": val } });
686
+ return this;
687
+ }
688
+
689
+ withOrderDateIn(...vals: any[]): this {
690
+ this.filters.push({ "orderDate": { "$in": vals } });
691
+ return this;
692
+ }
693
+
694
+ withOrderDateNotIn(...vals: any[]): this {
695
+ this.filters.push({ "orderDate": { "$notIn": vals } });
696
+ return this;
697
+ }
698
+
699
+ withOrderDateGreaterThan(val: any): this {
700
+ this.filters.push({ "orderDate": { "$gt": val } });
701
+ return this;
702
+ }
703
+
704
+ withOrderDateGreaterThanOrEqualTo(val: any): this {
705
+ this.filters.push({ "orderDate": { "$gte": val } });
706
+ return this;
707
+ }
708
+
709
+ withOrderDateLessThan(val: any): this {
710
+ this.filters.push({ "orderDate": { "$lt": val } });
711
+ return this;
712
+ }
713
+
714
+ withOrderDateLessThanOrEqualTo(val: any): this {
715
+ this.filters.push({ "orderDate": { "$lte": val } });
716
+ return this;
717
+ }
718
+
719
+ withOrderDateBetween(lower: any, upper: any): this {
720
+ this.filters.push({ "orderDate": { "$between": [lower, upper] } });
721
+ return this;
722
+ }
723
+
724
+ withOrderDateIsKnown(): this {
725
+ this.filters.push({ "orderDate": { "$isNull": false } });
726
+ return this;
727
+ }
728
+
729
+ withOrderDateIsUnknown(): this {
730
+ this.filters.push({ "orderDate": { "$isNull": true } });
731
+ return this;
732
+ }
733
+
734
+ withTotalAmountIs(val: any): this {
735
+ this.filters.push({ "totalAmount": { "$eq": val } });
736
+ return this;
737
+ }
738
+
739
+ withTotalAmountIsNot(val: any): this {
740
+ this.filters.push({ "totalAmount": { "$ne": val } });
741
+ return this;
742
+ }
743
+
744
+ withTotalAmountIn(...vals: any[]): this {
745
+ this.filters.push({ "totalAmount": { "$in": vals } });
746
+ return this;
747
+ }
748
+
749
+ withTotalAmountNotIn(...vals: any[]): this {
750
+ this.filters.push({ "totalAmount": { "$notIn": vals } });
751
+ return this;
752
+ }
753
+
754
+ withTotalAmountGreaterThan(val: any): this {
755
+ this.filters.push({ "totalAmount": { "$gt": val } });
756
+ return this;
757
+ }
758
+
759
+ withTotalAmountGreaterThanOrEqualTo(val: any): this {
760
+ this.filters.push({ "totalAmount": { "$gte": val } });
761
+ return this;
762
+ }
763
+
764
+ withTotalAmountLessThan(val: any): this {
765
+ this.filters.push({ "totalAmount": { "$lt": val } });
766
+ return this;
767
+ }
768
+
769
+ withTotalAmountLessThanOrEqualTo(val: any): this {
770
+ this.filters.push({ "totalAmount": { "$lte": val } });
771
+ return this;
772
+ }
773
+
774
+ withTotalAmountBetween(lower: any, upper: any): this {
775
+ this.filters.push({ "totalAmount": { "$between": [lower, upper] } });
776
+ return this;
777
+ }
778
+
779
+ withTotalAmountIsKnown(): this {
780
+ this.filters.push({ "totalAmount": { "$isNull": false } });
781
+ return this;
782
+ }
783
+
784
+ withTotalAmountIsUnknown(): this {
785
+ this.filters.push({ "totalAmount": { "$isNull": true } });
786
+ return this;
787
+ }
788
+
789
+ withVersionIs(val: any): this {
790
+ this.filters.push({ "version": { "$eq": val } });
791
+ return this;
792
+ }
793
+
794
+ withVersionIsNot(val: any): this {
795
+ this.filters.push({ "version": { "$ne": val } });
796
+ return this;
797
+ }
798
+
799
+ withVersionIn(...vals: any[]): this {
800
+ this.filters.push({ "version": { "$in": vals } });
801
+ return this;
802
+ }
803
+
804
+ withVersionNotIn(...vals: any[]): this {
805
+ this.filters.push({ "version": { "$notIn": vals } });
806
+ return this;
807
+ }
808
+
809
+ withVersionGreaterThan(val: any): this {
810
+ this.filters.push({ "version": { "$gt": val } });
811
+ return this;
812
+ }
813
+
814
+ withVersionGreaterThanOrEqualTo(val: any): this {
815
+ this.filters.push({ "version": { "$gte": val } });
816
+ return this;
817
+ }
818
+
819
+ withVersionLessThan(val: any): this {
820
+ this.filters.push({ "version": { "$lt": val } });
821
+ return this;
822
+ }
823
+
824
+ withVersionLessThanOrEqualTo(val: any): this {
825
+ this.filters.push({ "version": { "$lte": val } });
826
+ return this;
827
+ }
828
+
829
+ withVersionBetween(lower: any, upper: any): this {
830
+ this.filters.push({ "version": { "$between": [lower, upper] } });
831
+ return this;
832
+ }
833
+
834
+ withVersionIsKnown(): this {
835
+ this.filters.push({ "version": { "$isNull": false } });
836
+ return this;
837
+ }
838
+
839
+ withVersionIsUnknown(): this {
840
+ this.filters.push({ "version": { "$isNull": true } });
841
+ return this;
842
+ }
843
+
844
+ orderByIdAscending(): this {
845
+ this.query.orderBy("id", "asc");
846
+ return this;
847
+ }
848
+
849
+ orderByIdDescending(): this {
850
+ this.query.orderBy("id", "desc");
851
+ return this;
852
+ }
853
+
854
+
855
+
856
+ orderByOrderNumberAscending(): this {
857
+ this.query.orderBy("orderNumber", "asc");
858
+ return this;
859
+ }
860
+
861
+ orderByOrderNumberDescending(): this {
862
+ this.query.orderBy("orderNumber", "desc");
863
+ return this;
864
+ }
865
+
866
+ orderByOrderDateAscending(): this {
867
+ this.query.orderBy("orderDate", "asc");
868
+ return this;
869
+ }
870
+
871
+ orderByOrderDateDescending(): this {
872
+ this.query.orderBy("orderDate", "desc");
873
+ return this;
874
+ }
875
+
876
+ orderByTotalAmountAscending(): this {
877
+ this.query.orderBy("totalAmount", "asc");
878
+ return this;
879
+ }
880
+
881
+ orderByTotalAmountDescending(): this {
882
+ this.query.orderBy("totalAmount", "desc");
883
+ return this;
884
+ }
885
+
886
+ orderByVersionAscending(): this {
887
+ this.query.orderBy("version", "asc");
888
+ return this;
889
+ }
890
+
891
+ orderByVersionDescending(): this {
892
+ this.query.orderBy("version", "desc");
893
+ return this;
894
+ }
895
+
896
+
897
+ // --- Aggregations ---
898
+ count(): this {
899
+ this.query.aggregate("Count", "id", "count");
900
+ this._pageCountAlias = "count";
901
+ this._pageCountMethod = "count";
902
+ return this;
903
+ }
904
+
905
+ countAs(retName: string): this {
906
+ this.query.aggregate("Count", "id", retName);
907
+ this._pageCountAlias = retName;
908
+ this._pageCountMethod = "countAs";
909
+ return this;
910
+ }
911
+
912
+ minTotalAmount(): this {
913
+ return this.minTotalAmountAs("minOfTotalAmount");
914
+ }
915
+
916
+ minTotalAmountAs(retName: string): this {
917
+ this.query.aggregate("min", "totalAmount", retName);
918
+ return this;
919
+ }
920
+ maxTotalAmount(): this {
921
+ return this.maxTotalAmountAs("maxOfTotalAmount");
922
+ }
923
+
924
+ maxTotalAmountAs(retName: string): this {
925
+ this.query.aggregate("max", "totalAmount", retName);
926
+ return this;
927
+ }
928
+ sumTotalAmount(): this {
929
+ return this.sumTotalAmountAs("sumOfTotalAmount");
930
+ }
931
+
932
+ sumTotalAmountAs(retName: string): this {
933
+ this.query.aggregate("sum", "totalAmount", retName);
934
+ return this;
935
+ }
936
+ avgTotalAmount(): this {
937
+ return this.avgTotalAmountAs("avgOfTotalAmount");
938
+ }
939
+
940
+ avgTotalAmountAs(retName: string): this {
941
+ this.query.aggregate("avg", "totalAmount", retName);
942
+ return this;
943
+ }
944
+ standardDeviationTotalAmount(): this {
945
+ return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount");
946
+ }
947
+
948
+ standardDeviationTotalAmountAs(retName: string): this {
949
+ this.query.aggregate("stddev", "totalAmount", retName);
950
+ return this;
951
+ }
952
+ squareRootOfPopulationStandardDeviationTotalAmount(): this {
953
+ return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount");
954
+ }
955
+
956
+ squareRootOfPopulationStandardDeviationTotalAmountAs(retName: string): this {
957
+ this.query.aggregate("stddev_pop", "totalAmount", retName);
958
+ return this;
959
+ }
960
+ sampleVarianceTotalAmount(): this {
961
+ return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount");
962
+ }
963
+
964
+ sampleVarianceTotalAmountAs(retName: string): this {
965
+ this.query.aggregate("var_samp", "totalAmount", retName);
966
+ return this;
967
+ }
968
+ samplePopulationVarianceTotalAmount(): this {
969
+ return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount");
970
+ }
971
+
972
+ samplePopulationVarianceTotalAmountAs(retName: string): this {
973
+ this.query.aggregate("var_pop", "totalAmount", retName);
974
+ return this;
975
+ }
976
+
977
+ // --- Group By ---
978
+ groupById(): this {
979
+ this.query.groupBy("id");
980
+ return this;
981
+ }
982
+
983
+ groupByIdAs(retName: string): this {
984
+ this.query.groupBy("id"); // In TS we don't alias group by yet natively
985
+ return this;
986
+ }
987
+ groupByCustomer(): this {
988
+ this.query.groupBy("customer");
989
+ return this;
990
+ }
991
+
992
+ groupByCustomerAs(retName: string): this {
993
+ this.query.groupBy("customer"); // In TS we don't alias group by yet natively
994
+ return this;
995
+ }
996
+ groupByStatus(): this {
997
+ this.query.groupBy("status");
998
+ return this;
999
+ }
1000
+
1001
+ groupByStatusAs(retName: string): this {
1002
+ this.query.groupBy("status"); // In TS we don't alias group by yet natively
1003
+ return this;
1004
+ }
1005
+ groupByOrderNumber(): this {
1006
+ this.query.groupBy("orderNumber");
1007
+ return this;
1008
+ }
1009
+
1010
+ groupByOrderNumberAs(retName: string): this {
1011
+ this.query.groupBy("orderNumber"); // In TS we don't alias group by yet natively
1012
+ return this;
1013
+ }
1014
+ groupByOrderDate(): this {
1015
+ this.query.groupBy("orderDate");
1016
+ return this;
1017
+ }
1018
+
1019
+ groupByOrderDateAs(retName: string): this {
1020
+ this.query.groupBy("orderDate"); // In TS we don't alias group by yet natively
1021
+ return this;
1022
+ }
1023
+ groupByTotalAmount(): this {
1024
+ this.query.groupBy("totalAmount");
1025
+ return this;
1026
+ }
1027
+
1028
+ groupByTotalAmountAs(retName: string): this {
1029
+ this.query.groupBy("totalAmount"); // In TS we don't alias group by yet natively
1030
+ return this;
1031
+ }
1032
+ groupByVersion(): this {
1033
+ this.query.groupBy("version");
1034
+ return this;
1035
+ }
1036
+
1037
+ groupByVersionAs(retName: string): this {
1038
+ this.query.groupBy("version"); // In TS we don't alias group by yet natively
1039
+ return this;
1040
+ }
1041
+
1042
+ // --- Facets ---
1043
+ facetByCustomerAs(
1044
+ facetName: string,
1045
+ request: { toQuery(): SelectQuery },
1046
+ includeAllFacets = true,
1047
+ ): this {
1048
+ this.query.facetBy(facetName, "customer", request, includeAllFacets,
1049
+ { kind: "facet", method: "facetByCustomerAs", relation: "customer", alias: facetName });
1050
+ return this;
1051
+ }
1052
+
1053
+ facetByStatusAs(
1054
+ facetName: string,
1055
+ request: { toQuery(): SelectQuery },
1056
+ includeAllFacets = true,
1057
+ ): this {
1058
+ this.query.facetBy(facetName, "status", request, includeAllFacets,
1059
+ { kind: "facet", method: "facetByStatusAs", relation: "status", alias: facetName });
1060
+ return this;
1061
+ }
1062
+
1063
+
1064
+ private async executeForListInternal(context: UserContext): Promise<SmartList<CustomerOrder>> {
1065
+ this.ensureIntent();
1066
+ if (this.filters.length > 0) {
1067
+ this.query.filter({ "$and": this.filters });
1068
+ }
1069
+
1070
+ const service = context.requireResource<TeaQLDataService>("dataService");
1071
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
1072
+ const queryRoot = new EntityRoot();
1073
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
1074
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
1075
+ row instanceof CustomerOrder
1076
+ ? row
1077
+ : CustomerOrder.fromRecord(row as Record<string, unknown>, queryRoot));
1078
+ const result = new SmartList<CustomerOrder>(data);
1079
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
1080
+
1081
+ if (this.query.facets.length > 0) {
1082
+ result.facets = await executeRelationFacets(
1083
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
1084
+ }
1085
+
1086
+ return result;
1087
+ }
1088
+
1089
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
1090
+ this.ensureIntent();
1091
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
1092
+ const service = context.requireResource<TeaQLDataService>("dataService");
1093
+ return new SmartList<Record<string, unknown>>(
1094
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
1095
+ }
1096
+
1097
+ private async executeForPageInternal(
1098
+ context: UserContext, offset: number, limit: number,
1099
+ ): Promise<TeaQLPage<CustomerOrder>> {
1100
+ this.ensureIntent();
1101
+ this.query.offset(offset).limit(limit);
1102
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
1103
+ const service = context.requireResource<TeaQLDataService>("dataService");
1104
+ const useIdSet = this.query.localIdSetPaginationOptions() !== undefined;
1105
+ const countOperation = { kind: "named-count" as const,
1106
+ method: this._pageCountMethod ?? "count",
1107
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
1108
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
1109
+ this.query, this._pageCountAlias, countOperation);
1110
+ const pageQuery = this.query.clone();
1111
+ // A page count describes the full filtered set, not an aggregate-only page row.
1112
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
1113
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
1114
+ const rows = await service.executeQuery(context.prepareQuery(pageQuery));
1115
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
1116
+ ? context.idSetPaginationCount!
1117
+ : (totalCountBeforeRows ?? await service.executeCount(this.query, this._pageCountAlias, countOperation));
1118
+ const queryRoot = new EntityRoot();
1119
+ const data = new SmartList(rows.map((row: unknown) =>
1120
+ row instanceof CustomerOrder
1121
+ ? row
1122
+ : CustomerOrder.fromRecord(row as Record<string, unknown>, queryRoot)));
1123
+ data.totalCount = totalCount;
1124
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
1125
+ if (this.query.facets.length > 0) {
1126
+ data.facets = await executeRelationFacets(
1127
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
1128
+ }
1129
+ return { data, totalCount, offset, limit };
1130
+ }
1131
+
1132
+ private async *executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<CustomerOrder> {
1133
+ this.ensureIntent();
1134
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
1135
+ const service = context.requireResource<TeaQLDataService>("dataService");
1136
+ const queryRoot = new EntityRoot();
1137
+ for await (const chunk of service.executeForStream(this.query, chunkSize)) {
1138
+ for (const entity of chunk) {
1139
+ yield entity instanceof CustomerOrder
1140
+ ? entity
1141
+ : CustomerOrder.fromRecord(entity as Record<string, unknown>, queryRoot);
1142
+ }
1143
+ }
1144
+ }
1145
+
1146
+ private ensureIntent(): void {
1147
+ if (!this._comment?.trim()) {
1148
+ throw new Error("Security audit failure: non-empty comment() is required before execution");
1149
+ }
1150
+ if (!this._purpose?.trim()) {
1151
+ throw new Error("Security audit failure: non-empty purpose() is required before execution");
1152
+ }
1153
+ }
1154
+
1155
+ }
1156
+
1157
+ export class ExecutableCustomerOrderRequest {
1158
+ constructor(
1159
+ private readonly execute: (context: UserContext) => Promise<SmartList<CustomerOrder>>,
1160
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
1161
+ private readonly page: (
1162
+ context: UserContext, offset: number, limit: number,
1163
+ ) => Promise<TeaQLPage<CustomerOrder>>,
1164
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<CustomerOrder>,
1165
+ private readonly limitOne: () => void,
1166
+ private readonly addComment: (comment: string) => void,
1167
+ private readonly ensureIntent: () => void,
1168
+ ) {}
1169
+
1170
+ comment(c: string): this {
1171
+ this.addComment(c);
1172
+ return this;
1173
+ }
1174
+
1175
+ newEntity(context: UserContext): CustomerOrder {
1176
+ this.ensureIntent();
1177
+ return new CustomerOrder();
1178
+ }
1179
+
1180
+ executeForList(context: UserContext): Promise<SmartList<CustomerOrder>> {
1181
+ this.ensureIntent();
1182
+ return this.execute(context);
1183
+ }
1184
+
1185
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
1186
+ this.ensureIntent();
1187
+ return this.executeRows(context);
1188
+ }
1189
+
1190
+ executeForPage(
1191
+ context: UserContext, offset: number, limit: number,
1192
+ ): Promise<TeaQLPage<CustomerOrder>> {
1193
+ this.ensureIntent();
1194
+ return this.page(context, offset, limit);
1195
+ }
1196
+
1197
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<CustomerOrder> {
1198
+ this.ensureIntent();
1199
+ return this.stream(context, chunkSize);
1200
+ }
1201
+
1202
+ async executeForOne(context: UserContext): Promise<CustomerOrder | undefined> {
1203
+ this.limitOne();
1204
+ return (await this.executeForList(context))[0];
1205
+ }
1206
+ }
source/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts ADDED
@@ -0,0 +1,795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, TeaQLPage, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { Customer } from '../models/Customer';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning } from 'teaql-ts';
4
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
+
6
+
7
+
8
+ export class CustomerRequest {
9
+ private query: SelectQuery;
10
+ private filters: any[] = [];
11
+ private _purpose: string | undefined;
12
+ private _comment: string | undefined;
13
+ private _pageCountAlias: string | undefined;
14
+ private _pageCountMethod: "count" | "countAs" | undefined;
15
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
16
+
17
+ constructor(minimal = false) {
18
+ this.query = new SelectQuery("Customer");
19
+ this.filters.push({ version: { "$gte": 1 } });
20
+ if (minimal) {
21
+ this.selectId();
22
+ this.selectVersion();
23
+ }
24
+ else this.selectSelfFields();
25
+ }
26
+
27
+ comment(c: string): this {
28
+ this.query.comment(c);
29
+ this._comment = c;
30
+ return this;
31
+ }
32
+
33
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
34
+ const base = this.query.clone();
35
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
36
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
37
+ this.query = merged.query as SelectQuery;
38
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
39
+ this._dynamicSearchWarnings.push(...merged.warnings);
40
+ return this;
41
+ }
42
+
43
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
44
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
45
+ }
46
+
47
+ purpose(p: string): ExecutableCustomerRequest {
48
+ this.query.purpose(p);
49
+ this._purpose = p;
50
+ return new ExecutableCustomerRequest(
51
+ (context) => this.executeForListInternal(context),
52
+ (context) => this.executeForRowsInternal(context),
53
+ (context, offset, limit) => this.executeForPageInternal(context, offset, limit),
54
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
55
+ () => this.limit(1),
56
+ (c) => this.comment(c),
57
+ () => this.ensureIntent());
58
+ }
59
+
60
+ optimizeForContinuousPageFetch(): this {
61
+ this.query.optimizeForContinuousPageFetch();
62
+ return this;
63
+ }
64
+
65
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
66
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
67
+ return this;
68
+ }
69
+
70
+ optimizePaginationWithIdSet(): this {
71
+ this.query.optimizePaginationWithIdSet();
72
+ return this;
73
+ }
74
+
75
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
76
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
77
+ return this;
78
+ }
79
+
80
+ topNProbeParentThreshold(threshold: number): this {
81
+ this.query.topNProbeParentThreshold(threshold);
82
+ return this;
83
+ }
84
+
85
+ limit(n: number): this {
86
+ this.query.limit(n);
87
+ return this;
88
+ }
89
+
90
+ offset(n: number): this {
91
+ this.query.offset(n);
92
+ return this;
93
+ }
94
+
95
+ toQuery(): SelectQuery {
96
+ if (this.filters.length > 0) {
97
+ this.query.filter({ "$and": this.filters });
98
+ }
99
+ return this.query;
100
+ }
101
+
102
+ withDeletedRows(): this {
103
+ this.filters = this.filters.filter(filter => !("version" in filter));
104
+ return this;
105
+ }
106
+
107
+ deletedRowsOnly(): this {
108
+ this.withDeletedRows();
109
+ this.filters.push({ version: { "$lte": -1 } });
110
+ return this;
111
+ }
112
+
113
+ selectSelfFields(): this {
114
+ this.query.select(["id", "platform", "name", "version"]);
115
+ return this;
116
+ }
117
+
118
+ selectId(): this {
119
+ this.query.select(["id"]);
120
+ return this;
121
+ }
122
+
123
+
124
+ selectName(): this {
125
+ this.query.select(["name"]);
126
+ return this;
127
+ }
128
+
129
+ selectVersion(): this {
130
+ this.query.select(["version"]);
131
+ return this;
132
+ }
133
+
134
+
135
+ selectPlatformWith(request: { toQuery(): SelectQuery }): this {
136
+ this.query.select(["platform"]);
137
+ this.query.relationQuery(
138
+ "platform", request.toQuery(), "platform", "id", false,
139
+ { kind: "relation-select", method: "selectPlatformWith", relation: "platform" });
140
+ return this;
141
+ }
142
+
143
+ withPlatformMatching(request: { toQuery(): SelectQuery }): this {
144
+ this.filters.push({
145
+ "platform": {
146
+ "$inSubquery": { query: request.toQuery(), field: "id" },
147
+ },
148
+ });
149
+ return this;
150
+ }
151
+
152
+ withoutPlatformMatching(request: { toQuery(): SelectQuery }): this {
153
+ this.filters.push({
154
+ "platform": {
155
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
156
+ },
157
+ });
158
+ return this;
159
+ }
160
+
161
+ selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this {
162
+ this.query.relationQuery(
163
+ "customerOrderList", request.toQuery(), "id", "customer", true,
164
+ { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" });
165
+ return this;
166
+ }
167
+
168
+ haveCustomerOrders(): this {
169
+ return this.withCustomerOrderListMatching({
170
+ toQuery: () => new SelectQuery("CustomerOrder"),
171
+ });
172
+ }
173
+
174
+ haveNoCustomerOrders(): this {
175
+ return this.withoutCustomerOrderListMatching({
176
+ toQuery: () => new SelectQuery("CustomerOrder"),
177
+ });
178
+ }
179
+
180
+ withCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
181
+ this.filters.push({
182
+ "id": {
183
+ "$inSubquery": {
184
+ query: request.toQuery(), field: "customer",
185
+ },
186
+ },
187
+ });
188
+ return this;
189
+ }
190
+
191
+ withoutCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
192
+ this.filters.push({
193
+ "id": {
194
+ "$notInSubquery": {
195
+ query: request.toQuery(), field: "customer",
196
+ },
197
+ },
198
+ });
199
+ return this;
200
+ }
201
+
202
+ countCustomerOrders(): this {
203
+ return this.countCustomerOrdersAs("countCustomerOrders");
204
+ }
205
+
206
+ countCustomerOrdersAs(alias: string): this {
207
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
208
+ this.countCustomerOrdersWith(alias, { toQuery: () => query });
209
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
210
+ kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias };
211
+ return this;
212
+ }
213
+
214
+ countCustomerOrdersWith(alias: string, child: { toQuery(): SelectQuery }): this {
215
+ const query = child.toQuery().clone();
216
+ query.aggregateItems = [];
217
+ query.aggregate("Count", "id", alias);
218
+ this.query.relationAggregate("customerOrderList", alias, query, true,
219
+ { kind: "relation-count", method: "countCustomerOrdersWith", relation: "customerOrderList", alias });
220
+ return this;
221
+ }
222
+
223
+ minTotalAmountOfCustomerOrders(): this {
224
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
225
+ return this.minTotalAmountOfCustomerOrdersAs(
226
+ "minOfTotalAmountOfCustomerOrders", { toQuery: () => query });
227
+ }
228
+
229
+ minTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
230
+ const query = child.toQuery().clone();
231
+ query.aggregateItems = [];
232
+ query.aggregate("min", "totalAmount", alias);
233
+ this.query.relationAggregate("customerOrderList", alias, query, true,
234
+ { kind: "aggregate", method: "minTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
235
+ return this;
236
+ }
237
+ maxTotalAmountOfCustomerOrders(): this {
238
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
239
+ return this.maxTotalAmountOfCustomerOrdersAs(
240
+ "maxOfTotalAmountOfCustomerOrders", { toQuery: () => query });
241
+ }
242
+
243
+ maxTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
244
+ const query = child.toQuery().clone();
245
+ query.aggregateItems = [];
246
+ query.aggregate("max", "totalAmount", alias);
247
+ this.query.relationAggregate("customerOrderList", alias, query, true,
248
+ { kind: "aggregate", method: "maxTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
249
+ return this;
250
+ }
251
+ sumTotalAmountOfCustomerOrders(): this {
252
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
253
+ return this.sumTotalAmountOfCustomerOrdersAs(
254
+ "sumOfTotalAmountOfCustomerOrders", { toQuery: () => query });
255
+ }
256
+
257
+ sumTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
258
+ const query = child.toQuery().clone();
259
+ query.aggregateItems = [];
260
+ query.aggregate("sum", "totalAmount", alias);
261
+ this.query.relationAggregate("customerOrderList", alias, query, true,
262
+ { kind: "aggregate", method: "sumTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
263
+ return this;
264
+ }
265
+ avgTotalAmountOfCustomerOrders(): this {
266
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
267
+ return this.avgTotalAmountOfCustomerOrdersAs(
268
+ "avgOfTotalAmountOfCustomerOrders", { toQuery: () => query });
269
+ }
270
+
271
+ avgTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
272
+ const query = child.toQuery().clone();
273
+ query.aggregateItems = [];
274
+ query.aggregate("avg", "totalAmount", alias);
275
+ this.query.relationAggregate("customerOrderList", alias, query, true,
276
+ { kind: "aggregate", method: "avgTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
277
+ return this;
278
+ }
279
+ standardDeviationTotalAmountOfCustomerOrders(): this {
280
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
281
+ return this.standardDeviationTotalAmountOfCustomerOrdersAs(
282
+ "standardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
283
+ }
284
+
285
+ standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
286
+ const query = child.toQuery().clone();
287
+ query.aggregateItems = [];
288
+ query.aggregate("stddev", "totalAmount", alias);
289
+ this.query.relationAggregate("customerOrderList", alias, query, true,
290
+ { kind: "aggregate", method: "standardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
291
+ return this;
292
+ }
293
+ squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this {
294
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
295
+ return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(
296
+ "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
297
+ }
298
+
299
+ squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
300
+ const query = child.toQuery().clone();
301
+ query.aggregateItems = [];
302
+ query.aggregate("stddev_pop", "totalAmount", alias);
303
+ this.query.relationAggregate("customerOrderList", alias, query, true,
304
+ { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
305
+ return this;
306
+ }
307
+ sampleVarianceTotalAmountOfCustomerOrders(): this {
308
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
309
+ return this.sampleVarianceTotalAmountOfCustomerOrdersAs(
310
+ "sampleVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
311
+ }
312
+
313
+ sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
314
+ const query = child.toQuery().clone();
315
+ query.aggregateItems = [];
316
+ query.aggregate("var_samp", "totalAmount", alias);
317
+ this.query.relationAggregate("customerOrderList", alias, query, true,
318
+ { kind: "aggregate", method: "sampleVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
319
+ return this;
320
+ }
321
+ samplePopulationVarianceTotalAmountOfCustomerOrders(): this {
322
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
323
+ return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs(
324
+ "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
325
+ }
326
+
327
+ samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
328
+ const query = child.toQuery().clone();
329
+ query.aggregateItems = [];
330
+ query.aggregate("var_pop", "totalAmount", alias);
331
+ this.query.relationAggregate("customerOrderList", alias, query, true,
332
+ { kind: "aggregate", method: "samplePopulationVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
333
+ return this;
334
+ }
335
+
336
+ withIdIs(val: any): this {
337
+ this.filters.push({ "id": { "$eq": val } });
338
+ return this;
339
+ }
340
+
341
+ withIdIsNot(val: any): this {
342
+ this.filters.push({ "id": { "$ne": val } });
343
+ return this;
344
+ }
345
+
346
+ withIdIn(...vals: any[]): this {
347
+ this.filters.push({ "id": { "$in": vals } });
348
+ return this;
349
+ }
350
+
351
+ withIdNotIn(...vals: any[]): this {
352
+ this.filters.push({ "id": { "$notIn": vals } });
353
+ return this;
354
+ }
355
+
356
+ withIdGreaterThan(val: any): this {
357
+ this.filters.push({ "id": { "$gt": val } });
358
+ return this;
359
+ }
360
+
361
+ withIdGreaterThanOrEqualTo(val: any): this {
362
+ this.filters.push({ "id": { "$gte": val } });
363
+ return this;
364
+ }
365
+
366
+ withIdLessThan(val: any): this {
367
+ this.filters.push({ "id": { "$lt": val } });
368
+ return this;
369
+ }
370
+
371
+ withIdLessThanOrEqualTo(val: any): this {
372
+ this.filters.push({ "id": { "$lte": val } });
373
+ return this;
374
+ }
375
+
376
+ withIdBetween(lower: any, upper: any): this {
377
+ this.filters.push({ "id": { "$between": [lower, upper] } });
378
+ return this;
379
+ }
380
+
381
+ withIdIsKnown(): this {
382
+ this.filters.push({ "id": { "$isNull": false } });
383
+ return this;
384
+ }
385
+
386
+ withIdIsUnknown(): this {
387
+ this.filters.push({ "id": { "$isNull": true } });
388
+ return this;
389
+ }
390
+
391
+ filterByPlatform(val: any): this {
392
+ this.filters.push({ "platform": { "$eq": val } });
393
+ return this;
394
+ }
395
+
396
+ filterByPlatformIn(...vals: any[]): this {
397
+ this.filters.push({ "platform": { "$in": vals } });
398
+ return this;
399
+ }
400
+
401
+ withPlatformIsKnown(): this {
402
+ this.filters.push({ "platform": { "$isNull": false } });
403
+ return this;
404
+ }
405
+
406
+ withPlatformIsUnknown(): this {
407
+ this.filters.push({ "platform": { "$isNull": true } });
408
+ return this;
409
+ }
410
+
411
+ withNameContaining(val: string): this {
412
+ this.filters.push({ "name": { "$contains": val } });
413
+ return this;
414
+ }
415
+
416
+ withNameIs(val: string): this {
417
+ this.filters.push({ "name": { "$eq": val } });
418
+ return this;
419
+ }
420
+
421
+ withNameIsNot(val: any): this {
422
+ this.filters.push({ "name": { "$ne": val } });
423
+ return this;
424
+ }
425
+
426
+ withNameIn(...vals: any[]): this {
427
+ this.filters.push({ "name": { "$in": vals } });
428
+ return this;
429
+ }
430
+
431
+ withNameNotIn(...vals: any[]): this {
432
+ this.filters.push({ "name": { "$notIn": vals } });
433
+ return this;
434
+ }
435
+
436
+ withNameGreaterThan(val: any): this {
437
+ this.filters.push({ "name": { "$gt": val } });
438
+ return this;
439
+ }
440
+
441
+ withNameGreaterThanOrEqualTo(val: any): this {
442
+ this.filters.push({ "name": { "$gte": val } });
443
+ return this;
444
+ }
445
+
446
+ withNameLessThan(val: any): this {
447
+ this.filters.push({ "name": { "$lt": val } });
448
+ return this;
449
+ }
450
+
451
+ withNameLessThanOrEqualTo(val: any): this {
452
+ this.filters.push({ "name": { "$lte": val } });
453
+ return this;
454
+ }
455
+
456
+ withNameBetween(lower: any, upper: any): this {
457
+ this.filters.push({ "name": { "$between": [lower, upper] } });
458
+ return this;
459
+ }
460
+
461
+ withNameIsKnown(): this {
462
+ this.filters.push({ "name": { "$isNull": false } });
463
+ return this;
464
+ }
465
+
466
+ withNameIsUnknown(): this {
467
+ this.filters.push({ "name": { "$isNull": true } });
468
+ return this;
469
+ }
470
+ withNameNotContaining(val: string): this {
471
+ this.filters.push({ "name": { "$notContains": val } });
472
+ return this;
473
+ }
474
+
475
+ withNameStartingWith(val: string): this {
476
+ this.filters.push({ "name": { "$startsWith": val } });
477
+ return this;
478
+ }
479
+
480
+ withNameNotStartingWith(val: string): this {
481
+ this.filters.push({ "name": { "$notStartsWith": val } });
482
+ return this;
483
+ }
484
+
485
+ withNameEndingWith(val: string): this {
486
+ this.filters.push({ "name": { "$endsWith": val } });
487
+ return this;
488
+ }
489
+
490
+ withNameNotEndingWith(val: string): this {
491
+ this.filters.push({ "name": { "$notEndsWith": val } });
492
+ return this;
493
+ }
494
+
495
+ withNameSoundingLike(val: string): this {
496
+ this.filters.push({ "name": { "$soundLike": val } });
497
+ return this;
498
+ }
499
+
500
+ withVersionIs(val: any): this {
501
+ this.filters.push({ "version": { "$eq": val } });
502
+ return this;
503
+ }
504
+
505
+ withVersionIsNot(val: any): this {
506
+ this.filters.push({ "version": { "$ne": val } });
507
+ return this;
508
+ }
509
+
510
+ withVersionIn(...vals: any[]): this {
511
+ this.filters.push({ "version": { "$in": vals } });
512
+ return this;
513
+ }
514
+
515
+ withVersionNotIn(...vals: any[]): this {
516
+ this.filters.push({ "version": { "$notIn": vals } });
517
+ return this;
518
+ }
519
+
520
+ withVersionGreaterThan(val: any): this {
521
+ this.filters.push({ "version": { "$gt": val } });
522
+ return this;
523
+ }
524
+
525
+ withVersionGreaterThanOrEqualTo(val: any): this {
526
+ this.filters.push({ "version": { "$gte": val } });
527
+ return this;
528
+ }
529
+
530
+ withVersionLessThan(val: any): this {
531
+ this.filters.push({ "version": { "$lt": val } });
532
+ return this;
533
+ }
534
+
535
+ withVersionLessThanOrEqualTo(val: any): this {
536
+ this.filters.push({ "version": { "$lte": val } });
537
+ return this;
538
+ }
539
+
540
+ withVersionBetween(lower: any, upper: any): this {
541
+ this.filters.push({ "version": { "$between": [lower, upper] } });
542
+ return this;
543
+ }
544
+
545
+ withVersionIsKnown(): this {
546
+ this.filters.push({ "version": { "$isNull": false } });
547
+ return this;
548
+ }
549
+
550
+ withVersionIsUnknown(): this {
551
+ this.filters.push({ "version": { "$isNull": true } });
552
+ return this;
553
+ }
554
+
555
+ orderByIdAscending(): this {
556
+ this.query.orderBy("id", "asc");
557
+ return this;
558
+ }
559
+
560
+ orderByIdDescending(): this {
561
+ this.query.orderBy("id", "desc");
562
+ return this;
563
+ }
564
+
565
+
566
+ orderByNameAscending(): this {
567
+ this.query.orderBy("name", "asc");
568
+ return this;
569
+ }
570
+
571
+ orderByNameDescending(): this {
572
+ this.query.orderBy("name", "desc");
573
+ return this;
574
+ }
575
+
576
+ orderByVersionAscending(): this {
577
+ this.query.orderBy("version", "asc");
578
+ return this;
579
+ }
580
+
581
+ orderByVersionDescending(): this {
582
+ this.query.orderBy("version", "desc");
583
+ return this;
584
+ }
585
+
586
+
587
+ // --- Aggregations ---
588
+ count(): this {
589
+ this.query.aggregate("Count", "id", "count");
590
+ this._pageCountAlias = "count";
591
+ this._pageCountMethod = "count";
592
+ return this;
593
+ }
594
+
595
+ countAs(retName: string): this {
596
+ this.query.aggregate("Count", "id", retName);
597
+ this._pageCountAlias = retName;
598
+ this._pageCountMethod = "countAs";
599
+ return this;
600
+ }
601
+
602
+
603
+ // --- Group By ---
604
+ groupById(): this {
605
+ this.query.groupBy("id");
606
+ return this;
607
+ }
608
+
609
+ groupByIdAs(retName: string): this {
610
+ this.query.groupBy("id"); // In TS we don't alias group by yet natively
611
+ return this;
612
+ }
613
+ groupByPlatform(): this {
614
+ this.query.groupBy("platform");
615
+ return this;
616
+ }
617
+
618
+ groupByPlatformAs(retName: string): this {
619
+ this.query.groupBy("platform"); // In TS we don't alias group by yet natively
620
+ return this;
621
+ }
622
+ groupByName(): this {
623
+ this.query.groupBy("name");
624
+ return this;
625
+ }
626
+
627
+ groupByNameAs(retName: string): this {
628
+ this.query.groupBy("name"); // In TS we don't alias group by yet natively
629
+ return this;
630
+ }
631
+ groupByVersion(): this {
632
+ this.query.groupBy("version");
633
+ return this;
634
+ }
635
+
636
+ groupByVersionAs(retName: string): this {
637
+ this.query.groupBy("version"); // In TS we don't alias group by yet natively
638
+ return this;
639
+ }
640
+
641
+ // --- Facets ---
642
+ facetByPlatformAs(
643
+ facetName: string,
644
+ request: { toQuery(): SelectQuery },
645
+ includeAllFacets = true,
646
+ ): this {
647
+ this.query.facetBy(facetName, "platform", request, includeAllFacets,
648
+ { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName });
649
+ return this;
650
+ }
651
+
652
+
653
+ private async executeForListInternal(context: UserContext): Promise<SmartList<Customer>> {
654
+ this.ensureIntent();
655
+ if (this.filters.length > 0) {
656
+ this.query.filter({ "$and": this.filters });
657
+ }
658
+
659
+ const service = context.requireResource<TeaQLDataService>("dataService");
660
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
661
+ const queryRoot = new EntityRoot();
662
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
663
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
664
+ row instanceof Customer
665
+ ? row
666
+ : Customer.fromRecord(row as Record<string, unknown>, queryRoot));
667
+ const result = new SmartList<Customer>(data);
668
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
669
+
670
+ if (this.query.facets.length > 0) {
671
+ result.facets = await executeRelationFacets(
672
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
673
+ }
674
+
675
+ return result;
676
+ }
677
+
678
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
679
+ this.ensureIntent();
680
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
681
+ const service = context.requireResource<TeaQLDataService>("dataService");
682
+ return new SmartList<Record<string, unknown>>(
683
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
684
+ }
685
+
686
+ private async executeForPageInternal(
687
+ context: UserContext, offset: number, limit: number,
688
+ ): Promise<TeaQLPage<Customer>> {
689
+ this.ensureIntent();
690
+ this.query.offset(offset).limit(limit);
691
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
692
+ const service = context.requireResource<TeaQLDataService>("dataService");
693
+ const useIdSet = this.query.localIdSetPaginationOptions() !== undefined;
694
+ const countOperation = { kind: "named-count" as const,
695
+ method: this._pageCountMethod ?? "count",
696
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
697
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
698
+ this.query, this._pageCountAlias, countOperation);
699
+ const pageQuery = this.query.clone();
700
+ // A page count describes the full filtered set, not an aggregate-only page row.
701
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
702
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
703
+ const rows = await service.executeQuery(context.prepareQuery(pageQuery));
704
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
705
+ ? context.idSetPaginationCount!
706
+ : (totalCountBeforeRows ?? await service.executeCount(this.query, this._pageCountAlias, countOperation));
707
+ const queryRoot = new EntityRoot();
708
+ const data = new SmartList(rows.map((row: unknown) =>
709
+ row instanceof Customer
710
+ ? row
711
+ : Customer.fromRecord(row as Record<string, unknown>, queryRoot)));
712
+ data.totalCount = totalCount;
713
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
714
+ if (this.query.facets.length > 0) {
715
+ data.facets = await executeRelationFacets(
716
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
717
+ }
718
+ return { data, totalCount, offset, limit };
719
+ }
720
+
721
+ private async *executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<Customer> {
722
+ this.ensureIntent();
723
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
724
+ const service = context.requireResource<TeaQLDataService>("dataService");
725
+ const queryRoot = new EntityRoot();
726
+ for await (const chunk of service.executeForStream(this.query, chunkSize)) {
727
+ for (const entity of chunk) {
728
+ yield entity instanceof Customer
729
+ ? entity
730
+ : Customer.fromRecord(entity as Record<string, unknown>, queryRoot);
731
+ }
732
+ }
733
+ }
734
+
735
+ private ensureIntent(): void {
736
+ if (!this._comment?.trim()) {
737
+ throw new Error("Security audit failure: non-empty comment() is required before execution");
738
+ }
739
+ if (!this._purpose?.trim()) {
740
+ throw new Error("Security audit failure: non-empty purpose() is required before execution");
741
+ }
742
+ }
743
+
744
+ }
745
+
746
+ export class ExecutableCustomerRequest {
747
+ constructor(
748
+ private readonly execute: (context: UserContext) => Promise<SmartList<Customer>>,
749
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
750
+ private readonly page: (
751
+ context: UserContext, offset: number, limit: number,
752
+ ) => Promise<TeaQLPage<Customer>>,
753
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<Customer>,
754
+ private readonly limitOne: () => void,
755
+ private readonly addComment: (comment: string) => void,
756
+ private readonly ensureIntent: () => void,
757
+ ) {}
758
+
759
+ comment(c: string): this {
760
+ this.addComment(c);
761
+ return this;
762
+ }
763
+
764
+ newEntity(context: UserContext): Customer {
765
+ this.ensureIntent();
766
+ return new Customer();
767
+ }
768
+
769
+ executeForList(context: UserContext): Promise<SmartList<Customer>> {
770
+ this.ensureIntent();
771
+ return this.execute(context);
772
+ }
773
+
774
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
775
+ this.ensureIntent();
776
+ return this.executeRows(context);
777
+ }
778
+
779
+ executeForPage(
780
+ context: UserContext, offset: number, limit: number,
781
+ ): Promise<TeaQLPage<Customer>> {
782
+ this.ensureIntent();
783
+ return this.page(context, offset, limit);
784
+ }
785
+
786
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<Customer> {
787
+ this.ensureIntent();
788
+ return this.stream(context, chunkSize);
789
+ }
790
+
791
+ async executeForOne(context: UserContext): Promise<Customer | undefined> {
792
+ this.limitOne();
793
+ return (await this.executeForList(context))[0];
794
+ }
795
+ }
source/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts ADDED
@@ -0,0 +1,909 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, TeaQLPage, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { OrderItem } from '../models/OrderItem';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning } from 'teaql-ts';
4
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
+
6
+
7
+
8
+ export class OrderItemRequest {
9
+ private query: SelectQuery;
10
+ private filters: any[] = [];
11
+ private _purpose: string | undefined;
12
+ private _comment: string | undefined;
13
+ private _pageCountAlias: string | undefined;
14
+ private _pageCountMethod: "count" | "countAs" | undefined;
15
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
16
+
17
+ constructor(minimal = false) {
18
+ this.query = new SelectQuery("OrderItem");
19
+ this.filters.push({ version: { "$gte": 1 } });
20
+ if (minimal) {
21
+ this.selectId();
22
+ this.selectVersion();
23
+ }
24
+ else this.selectSelfFields();
25
+ }
26
+
27
+ comment(c: string): this {
28
+ this.query.comment(c);
29
+ this._comment = c;
30
+ return this;
31
+ }
32
+
33
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
34
+ const base = this.query.clone();
35
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
36
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
37
+ this.query = merged.query as SelectQuery;
38
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
39
+ this._dynamicSearchWarnings.push(...merged.warnings);
40
+ return this;
41
+ }
42
+
43
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
44
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
45
+ }
46
+
47
+ purpose(p: string): ExecutableOrderItemRequest {
48
+ this.query.purpose(p);
49
+ this._purpose = p;
50
+ return new ExecutableOrderItemRequest(
51
+ (context) => this.executeForListInternal(context),
52
+ (context) => this.executeForRowsInternal(context),
53
+ (context, offset, limit) => this.executeForPageInternal(context, offset, limit),
54
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
55
+ () => this.limit(1),
56
+ (c) => this.comment(c),
57
+ () => this.ensureIntent());
58
+ }
59
+
60
+ optimizeForContinuousPageFetch(): this {
61
+ this.query.optimizeForContinuousPageFetch();
62
+ return this;
63
+ }
64
+
65
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
66
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
67
+ return this;
68
+ }
69
+
70
+ optimizePaginationWithIdSet(): this {
71
+ this.query.optimizePaginationWithIdSet();
72
+ return this;
73
+ }
74
+
75
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
76
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
77
+ return this;
78
+ }
79
+
80
+ topNProbeParentThreshold(threshold: number): this {
81
+ this.query.topNProbeParentThreshold(threshold);
82
+ return this;
83
+ }
84
+
85
+ limit(n: number): this {
86
+ this.query.limit(n);
87
+ return this;
88
+ }
89
+
90
+ offset(n: number): this {
91
+ this.query.offset(n);
92
+ return this;
93
+ }
94
+
95
+ toQuery(): SelectQuery {
96
+ if (this.filters.length > 0) {
97
+ this.query.filter({ "$and": this.filters });
98
+ }
99
+ return this.query;
100
+ }
101
+
102
+ withDeletedRows(): this {
103
+ this.filters = this.filters.filter(filter => !("version" in filter));
104
+ return this;
105
+ }
106
+
107
+ deletedRowsOnly(): this {
108
+ this.withDeletedRows();
109
+ this.filters.push({ version: { "$lte": -1 } });
110
+ return this;
111
+ }
112
+
113
+ selectSelfFields(): this {
114
+ this.query.select(["id", "customerOrder", "productName", "quantity", "unitPrice", "version"]);
115
+ return this;
116
+ }
117
+
118
+ selectId(): this {
119
+ this.query.select(["id"]);
120
+ return this;
121
+ }
122
+
123
+
124
+ selectProductName(): this {
125
+ this.query.select(["productName"]);
126
+ return this;
127
+ }
128
+
129
+ selectQuantity(): this {
130
+ this.query.select(["quantity"]);
131
+ return this;
132
+ }
133
+
134
+ selectUnitPrice(): this {
135
+ this.query.select(["unitPrice"]);
136
+ return this;
137
+ }
138
+
139
+ selectVersion(): this {
140
+ this.query.select(["version"]);
141
+ return this;
142
+ }
143
+
144
+
145
+ selectCustomerOrderWith(request: { toQuery(): SelectQuery }): this {
146
+ this.query.select(["customerOrder"]);
147
+ this.query.relationQuery(
148
+ "customerOrder", request.toQuery(), "customerOrder", "id", false,
149
+ { kind: "relation-select", method: "selectCustomerOrderWith", relation: "customerOrder" });
150
+ return this;
151
+ }
152
+
153
+ withCustomerOrderMatching(request: { toQuery(): SelectQuery }): this {
154
+ this.filters.push({
155
+ "customerOrder": {
156
+ "$inSubquery": { query: request.toQuery(), field: "id" },
157
+ },
158
+ });
159
+ return this;
160
+ }
161
+
162
+ withoutCustomerOrderMatching(request: { toQuery(): SelectQuery }): this {
163
+ this.filters.push({
164
+ "customerOrder": {
165
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
166
+ },
167
+ });
168
+ return this;
169
+ }
170
+
171
+
172
+
173
+
174
+ withIdIs(val: any): this {
175
+ this.filters.push({ "id": { "$eq": val } });
176
+ return this;
177
+ }
178
+
179
+ withIdIsNot(val: any): this {
180
+ this.filters.push({ "id": { "$ne": val } });
181
+ return this;
182
+ }
183
+
184
+ withIdIn(...vals: any[]): this {
185
+ this.filters.push({ "id": { "$in": vals } });
186
+ return this;
187
+ }
188
+
189
+ withIdNotIn(...vals: any[]): this {
190
+ this.filters.push({ "id": { "$notIn": vals } });
191
+ return this;
192
+ }
193
+
194
+ withIdGreaterThan(val: any): this {
195
+ this.filters.push({ "id": { "$gt": val } });
196
+ return this;
197
+ }
198
+
199
+ withIdGreaterThanOrEqualTo(val: any): this {
200
+ this.filters.push({ "id": { "$gte": val } });
201
+ return this;
202
+ }
203
+
204
+ withIdLessThan(val: any): this {
205
+ this.filters.push({ "id": { "$lt": val } });
206
+ return this;
207
+ }
208
+
209
+ withIdLessThanOrEqualTo(val: any): this {
210
+ this.filters.push({ "id": { "$lte": val } });
211
+ return this;
212
+ }
213
+
214
+ withIdBetween(lower: any, upper: any): this {
215
+ this.filters.push({ "id": { "$between": [lower, upper] } });
216
+ return this;
217
+ }
218
+
219
+ withIdIsKnown(): this {
220
+ this.filters.push({ "id": { "$isNull": false } });
221
+ return this;
222
+ }
223
+
224
+ withIdIsUnknown(): this {
225
+ this.filters.push({ "id": { "$isNull": true } });
226
+ return this;
227
+ }
228
+
229
+ filterByCustomerOrder(val: any): this {
230
+ this.filters.push({ "customerOrder": { "$eq": val } });
231
+ return this;
232
+ }
233
+
234
+ filterByCustomerOrderIn(...vals: any[]): this {
235
+ this.filters.push({ "customerOrder": { "$in": vals } });
236
+ return this;
237
+ }
238
+
239
+ withCustomerOrderIsKnown(): this {
240
+ this.filters.push({ "customerOrder": { "$isNull": false } });
241
+ return this;
242
+ }
243
+
244
+ withCustomerOrderIsUnknown(): this {
245
+ this.filters.push({ "customerOrder": { "$isNull": true } });
246
+ return this;
247
+ }
248
+
249
+ withProductNameContaining(val: string): this {
250
+ this.filters.push({ "productName": { "$contains": val } });
251
+ return this;
252
+ }
253
+
254
+ withProductNameIs(val: string): this {
255
+ this.filters.push({ "productName": { "$eq": val } });
256
+ return this;
257
+ }
258
+
259
+ withProductNameIsNot(val: any): this {
260
+ this.filters.push({ "productName": { "$ne": val } });
261
+ return this;
262
+ }
263
+
264
+ withProductNameIn(...vals: any[]): this {
265
+ this.filters.push({ "productName": { "$in": vals } });
266
+ return this;
267
+ }
268
+
269
+ withProductNameNotIn(...vals: any[]): this {
270
+ this.filters.push({ "productName": { "$notIn": vals } });
271
+ return this;
272
+ }
273
+
274
+ withProductNameGreaterThan(val: any): this {
275
+ this.filters.push({ "productName": { "$gt": val } });
276
+ return this;
277
+ }
278
+
279
+ withProductNameGreaterThanOrEqualTo(val: any): this {
280
+ this.filters.push({ "productName": { "$gte": val } });
281
+ return this;
282
+ }
283
+
284
+ withProductNameLessThan(val: any): this {
285
+ this.filters.push({ "productName": { "$lt": val } });
286
+ return this;
287
+ }
288
+
289
+ withProductNameLessThanOrEqualTo(val: any): this {
290
+ this.filters.push({ "productName": { "$lte": val } });
291
+ return this;
292
+ }
293
+
294
+ withProductNameBetween(lower: any, upper: any): this {
295
+ this.filters.push({ "productName": { "$between": [lower, upper] } });
296
+ return this;
297
+ }
298
+
299
+ withProductNameIsKnown(): this {
300
+ this.filters.push({ "productName": { "$isNull": false } });
301
+ return this;
302
+ }
303
+
304
+ withProductNameIsUnknown(): this {
305
+ this.filters.push({ "productName": { "$isNull": true } });
306
+ return this;
307
+ }
308
+ withProductNameNotContaining(val: string): this {
309
+ this.filters.push({ "productName": { "$notContains": val } });
310
+ return this;
311
+ }
312
+
313
+ withProductNameStartingWith(val: string): this {
314
+ this.filters.push({ "productName": { "$startsWith": val } });
315
+ return this;
316
+ }
317
+
318
+ withProductNameNotStartingWith(val: string): this {
319
+ this.filters.push({ "productName": { "$notStartsWith": val } });
320
+ return this;
321
+ }
322
+
323
+ withProductNameEndingWith(val: string): this {
324
+ this.filters.push({ "productName": { "$endsWith": val } });
325
+ return this;
326
+ }
327
+
328
+ withProductNameNotEndingWith(val: string): this {
329
+ this.filters.push({ "productName": { "$notEndsWith": val } });
330
+ return this;
331
+ }
332
+
333
+ withProductNameSoundingLike(val: string): this {
334
+ this.filters.push({ "productName": { "$soundLike": val } });
335
+ return this;
336
+ }
337
+
338
+ withQuantityIs(val: any): this {
339
+ this.filters.push({ "quantity": { "$eq": val } });
340
+ return this;
341
+ }
342
+
343
+ withQuantityIsNot(val: any): this {
344
+ this.filters.push({ "quantity": { "$ne": val } });
345
+ return this;
346
+ }
347
+
348
+ withQuantityIn(...vals: any[]): this {
349
+ this.filters.push({ "quantity": { "$in": vals } });
350
+ return this;
351
+ }
352
+
353
+ withQuantityNotIn(...vals: any[]): this {
354
+ this.filters.push({ "quantity": { "$notIn": vals } });
355
+ return this;
356
+ }
357
+
358
+ withQuantityGreaterThan(val: any): this {
359
+ this.filters.push({ "quantity": { "$gt": val } });
360
+ return this;
361
+ }
362
+
363
+ withQuantityGreaterThanOrEqualTo(val: any): this {
364
+ this.filters.push({ "quantity": { "$gte": val } });
365
+ return this;
366
+ }
367
+
368
+ withQuantityLessThan(val: any): this {
369
+ this.filters.push({ "quantity": { "$lt": val } });
370
+ return this;
371
+ }
372
+
373
+ withQuantityLessThanOrEqualTo(val: any): this {
374
+ this.filters.push({ "quantity": { "$lte": val } });
375
+ return this;
376
+ }
377
+
378
+ withQuantityBetween(lower: any, upper: any): this {
379
+ this.filters.push({ "quantity": { "$between": [lower, upper] } });
380
+ return this;
381
+ }
382
+
383
+ withQuantityIsKnown(): this {
384
+ this.filters.push({ "quantity": { "$isNull": false } });
385
+ return this;
386
+ }
387
+
388
+ withQuantityIsUnknown(): this {
389
+ this.filters.push({ "quantity": { "$isNull": true } });
390
+ return this;
391
+ }
392
+
393
+ withUnitPriceIs(val: any): this {
394
+ this.filters.push({ "unitPrice": { "$eq": val } });
395
+ return this;
396
+ }
397
+
398
+ withUnitPriceIsNot(val: any): this {
399
+ this.filters.push({ "unitPrice": { "$ne": val } });
400
+ return this;
401
+ }
402
+
403
+ withUnitPriceIn(...vals: any[]): this {
404
+ this.filters.push({ "unitPrice": { "$in": vals } });
405
+ return this;
406
+ }
407
+
408
+ withUnitPriceNotIn(...vals: any[]): this {
409
+ this.filters.push({ "unitPrice": { "$notIn": vals } });
410
+ return this;
411
+ }
412
+
413
+ withUnitPriceGreaterThan(val: any): this {
414
+ this.filters.push({ "unitPrice": { "$gt": val } });
415
+ return this;
416
+ }
417
+
418
+ withUnitPriceGreaterThanOrEqualTo(val: any): this {
419
+ this.filters.push({ "unitPrice": { "$gte": val } });
420
+ return this;
421
+ }
422
+
423
+ withUnitPriceLessThan(val: any): this {
424
+ this.filters.push({ "unitPrice": { "$lt": val } });
425
+ return this;
426
+ }
427
+
428
+ withUnitPriceLessThanOrEqualTo(val: any): this {
429
+ this.filters.push({ "unitPrice": { "$lte": val } });
430
+ return this;
431
+ }
432
+
433
+ withUnitPriceBetween(lower: any, upper: any): this {
434
+ this.filters.push({ "unitPrice": { "$between": [lower, upper] } });
435
+ return this;
436
+ }
437
+
438
+ withUnitPriceIsKnown(): this {
439
+ this.filters.push({ "unitPrice": { "$isNull": false } });
440
+ return this;
441
+ }
442
+
443
+ withUnitPriceIsUnknown(): this {
444
+ this.filters.push({ "unitPrice": { "$isNull": true } });
445
+ return this;
446
+ }
447
+
448
+ withVersionIs(val: any): this {
449
+ this.filters.push({ "version": { "$eq": val } });
450
+ return this;
451
+ }
452
+
453
+ withVersionIsNot(val: any): this {
454
+ this.filters.push({ "version": { "$ne": val } });
455
+ return this;
456
+ }
457
+
458
+ withVersionIn(...vals: any[]): this {
459
+ this.filters.push({ "version": { "$in": vals } });
460
+ return this;
461
+ }
462
+
463
+ withVersionNotIn(...vals: any[]): this {
464
+ this.filters.push({ "version": { "$notIn": vals } });
465
+ return this;
466
+ }
467
+
468
+ withVersionGreaterThan(val: any): this {
469
+ this.filters.push({ "version": { "$gt": val } });
470
+ return this;
471
+ }
472
+
473
+ withVersionGreaterThanOrEqualTo(val: any): this {
474
+ this.filters.push({ "version": { "$gte": val } });
475
+ return this;
476
+ }
477
+
478
+ withVersionLessThan(val: any): this {
479
+ this.filters.push({ "version": { "$lt": val } });
480
+ return this;
481
+ }
482
+
483
+ withVersionLessThanOrEqualTo(val: any): this {
484
+ this.filters.push({ "version": { "$lte": val } });
485
+ return this;
486
+ }
487
+
488
+ withVersionBetween(lower: any, upper: any): this {
489
+ this.filters.push({ "version": { "$between": [lower, upper] } });
490
+ return this;
491
+ }
492
+
493
+ withVersionIsKnown(): this {
494
+ this.filters.push({ "version": { "$isNull": false } });
495
+ return this;
496
+ }
497
+
498
+ withVersionIsUnknown(): this {
499
+ this.filters.push({ "version": { "$isNull": true } });
500
+ return this;
501
+ }
502
+
503
+ orderByIdAscending(): this {
504
+ this.query.orderBy("id", "asc");
505
+ return this;
506
+ }
507
+
508
+ orderByIdDescending(): this {
509
+ this.query.orderBy("id", "desc");
510
+ return this;
511
+ }
512
+
513
+
514
+ orderByProductNameAscending(): this {
515
+ this.query.orderBy("productName", "asc");
516
+ return this;
517
+ }
518
+
519
+ orderByProductNameDescending(): this {
520
+ this.query.orderBy("productName", "desc");
521
+ return this;
522
+ }
523
+
524
+ orderByQuantityAscending(): this {
525
+ this.query.orderBy("quantity", "asc");
526
+ return this;
527
+ }
528
+
529
+ orderByQuantityDescending(): this {
530
+ this.query.orderBy("quantity", "desc");
531
+ return this;
532
+ }
533
+
534
+ orderByUnitPriceAscending(): this {
535
+ this.query.orderBy("unitPrice", "asc");
536
+ return this;
537
+ }
538
+
539
+ orderByUnitPriceDescending(): this {
540
+ this.query.orderBy("unitPrice", "desc");
541
+ return this;
542
+ }
543
+
544
+ orderByVersionAscending(): this {
545
+ this.query.orderBy("version", "asc");
546
+ return this;
547
+ }
548
+
549
+ orderByVersionDescending(): this {
550
+ this.query.orderBy("version", "desc");
551
+ return this;
552
+ }
553
+
554
+
555
+ // --- Aggregations ---
556
+ count(): this {
557
+ this.query.aggregate("Count", "id", "count");
558
+ this._pageCountAlias = "count";
559
+ this._pageCountMethod = "count";
560
+ return this;
561
+ }
562
+
563
+ countAs(retName: string): this {
564
+ this.query.aggregate("Count", "id", retName);
565
+ this._pageCountAlias = retName;
566
+ this._pageCountMethod = "countAs";
567
+ return this;
568
+ }
569
+
570
+ minQuantity(): this {
571
+ return this.minQuantityAs("minOfQuantity");
572
+ }
573
+
574
+ minQuantityAs(retName: string): this {
575
+ this.query.aggregate("min", "quantity", retName);
576
+ return this;
577
+ }
578
+ maxQuantity(): this {
579
+ return this.maxQuantityAs("maxOfQuantity");
580
+ }
581
+
582
+ maxQuantityAs(retName: string): this {
583
+ this.query.aggregate("max", "quantity", retName);
584
+ return this;
585
+ }
586
+ sumQuantity(): this {
587
+ return this.sumQuantityAs("sumOfQuantity");
588
+ }
589
+
590
+ sumQuantityAs(retName: string): this {
591
+ this.query.aggregate("sum", "quantity", retName);
592
+ return this;
593
+ }
594
+ avgQuantity(): this {
595
+ return this.avgQuantityAs("avgOfQuantity");
596
+ }
597
+
598
+ avgQuantityAs(retName: string): this {
599
+ this.query.aggregate("avg", "quantity", retName);
600
+ return this;
601
+ }
602
+ standardDeviationQuantity(): this {
603
+ return this.standardDeviationQuantityAs("standardDeviationOfQuantity");
604
+ }
605
+
606
+ standardDeviationQuantityAs(retName: string): this {
607
+ this.query.aggregate("stddev", "quantity", retName);
608
+ return this;
609
+ }
610
+ squareRootOfPopulationStandardDeviationQuantity(): this {
611
+ return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity");
612
+ }
613
+
614
+ squareRootOfPopulationStandardDeviationQuantityAs(retName: string): this {
615
+ this.query.aggregate("stddev_pop", "quantity", retName);
616
+ return this;
617
+ }
618
+ sampleVarianceQuantity(): this {
619
+ return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity");
620
+ }
621
+
622
+ sampleVarianceQuantityAs(retName: string): this {
623
+ this.query.aggregate("var_samp", "quantity", retName);
624
+ return this;
625
+ }
626
+ samplePopulationVarianceQuantity(): this {
627
+ return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity");
628
+ }
629
+
630
+ samplePopulationVarianceQuantityAs(retName: string): this {
631
+ this.query.aggregate("var_pop", "quantity", retName);
632
+ return this;
633
+ }
634
+ minUnitPrice(): this {
635
+ return this.minUnitPriceAs("minOfUnitPrice");
636
+ }
637
+
638
+ minUnitPriceAs(retName: string): this {
639
+ this.query.aggregate("min", "unitPrice", retName);
640
+ return this;
641
+ }
642
+ maxUnitPrice(): this {
643
+ return this.maxUnitPriceAs("maxOfUnitPrice");
644
+ }
645
+
646
+ maxUnitPriceAs(retName: string): this {
647
+ this.query.aggregate("max", "unitPrice", retName);
648
+ return this;
649
+ }
650
+ sumUnitPrice(): this {
651
+ return this.sumUnitPriceAs("sumOfUnitPrice");
652
+ }
653
+
654
+ sumUnitPriceAs(retName: string): this {
655
+ this.query.aggregate("sum", "unitPrice", retName);
656
+ return this;
657
+ }
658
+ avgUnitPrice(): this {
659
+ return this.avgUnitPriceAs("avgOfUnitPrice");
660
+ }
661
+
662
+ avgUnitPriceAs(retName: string): this {
663
+ this.query.aggregate("avg", "unitPrice", retName);
664
+ return this;
665
+ }
666
+ standardDeviationUnitPrice(): this {
667
+ return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice");
668
+ }
669
+
670
+ standardDeviationUnitPriceAs(retName: string): this {
671
+ this.query.aggregate("stddev", "unitPrice", retName);
672
+ return this;
673
+ }
674
+ squareRootOfPopulationStandardDeviationUnitPrice(): this {
675
+ return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice");
676
+ }
677
+
678
+ squareRootOfPopulationStandardDeviationUnitPriceAs(retName: string): this {
679
+ this.query.aggregate("stddev_pop", "unitPrice", retName);
680
+ return this;
681
+ }
682
+ sampleVarianceUnitPrice(): this {
683
+ return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice");
684
+ }
685
+
686
+ sampleVarianceUnitPriceAs(retName: string): this {
687
+ this.query.aggregate("var_samp", "unitPrice", retName);
688
+ return this;
689
+ }
690
+ samplePopulationVarianceUnitPrice(): this {
691
+ return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice");
692
+ }
693
+
694
+ samplePopulationVarianceUnitPriceAs(retName: string): this {
695
+ this.query.aggregate("var_pop", "unitPrice", retName);
696
+ return this;
697
+ }
698
+
699
+ // --- Group By ---
700
+ groupById(): this {
701
+ this.query.groupBy("id");
702
+ return this;
703
+ }
704
+
705
+ groupByIdAs(retName: string): this {
706
+ this.query.groupBy("id"); // In TS we don't alias group by yet natively
707
+ return this;
708
+ }
709
+ groupByCustomerOrder(): this {
710
+ this.query.groupBy("customerOrder");
711
+ return this;
712
+ }
713
+
714
+ groupByCustomerOrderAs(retName: string): this {
715
+ this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively
716
+ return this;
717
+ }
718
+ groupByProductName(): this {
719
+ this.query.groupBy("productName");
720
+ return this;
721
+ }
722
+
723
+ groupByProductNameAs(retName: string): this {
724
+ this.query.groupBy("productName"); // In TS we don't alias group by yet natively
725
+ return this;
726
+ }
727
+ groupByQuantity(): this {
728
+ this.query.groupBy("quantity");
729
+ return this;
730
+ }
731
+
732
+ groupByQuantityAs(retName: string): this {
733
+ this.query.groupBy("quantity"); // In TS we don't alias group by yet natively
734
+ return this;
735
+ }
736
+ groupByUnitPrice(): this {
737
+ this.query.groupBy("unitPrice");
738
+ return this;
739
+ }
740
+
741
+ groupByUnitPriceAs(retName: string): this {
742
+ this.query.groupBy("unitPrice"); // In TS we don't alias group by yet natively
743
+ return this;
744
+ }
745
+ groupByVersion(): this {
746
+ this.query.groupBy("version");
747
+ return this;
748
+ }
749
+
750
+ groupByVersionAs(retName: string): this {
751
+ this.query.groupBy("version"); // In TS we don't alias group by yet natively
752
+ return this;
753
+ }
754
+
755
+ // --- Facets ---
756
+ facetByCustomerOrderAs(
757
+ facetName: string,
758
+ request: { toQuery(): SelectQuery },
759
+ includeAllFacets = true,
760
+ ): this {
761
+ this.query.facetBy(facetName, "customerOrder", request, includeAllFacets,
762
+ { kind: "facet", method: "facetByCustomerOrderAs", relation: "customerOrder", alias: facetName });
763
+ return this;
764
+ }
765
+
766
+
767
+ private async executeForListInternal(context: UserContext): Promise<SmartList<OrderItem>> {
768
+ this.ensureIntent();
769
+ if (this.filters.length > 0) {
770
+ this.query.filter({ "$and": this.filters });
771
+ }
772
+
773
+ const service = context.requireResource<TeaQLDataService>("dataService");
774
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
775
+ const queryRoot = new EntityRoot();
776
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
777
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
778
+ row instanceof OrderItem
779
+ ? row
780
+ : OrderItem.fromRecord(row as Record<string, unknown>, queryRoot));
781
+ const result = new SmartList<OrderItem>(data);
782
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
783
+
784
+ if (this.query.facets.length > 0) {
785
+ result.facets = await executeRelationFacets(
786
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
787
+ }
788
+
789
+ return result;
790
+ }
791
+
792
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
793
+ this.ensureIntent();
794
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
795
+ const service = context.requireResource<TeaQLDataService>("dataService");
796
+ return new SmartList<Record<string, unknown>>(
797
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
798
+ }
799
+
800
+ private async executeForPageInternal(
801
+ context: UserContext, offset: number, limit: number,
802
+ ): Promise<TeaQLPage<OrderItem>> {
803
+ this.ensureIntent();
804
+ this.query.offset(offset).limit(limit);
805
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
806
+ const service = context.requireResource<TeaQLDataService>("dataService");
807
+ const useIdSet = this.query.localIdSetPaginationOptions() !== undefined;
808
+ const countOperation = { kind: "named-count" as const,
809
+ method: this._pageCountMethod ?? "count",
810
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
811
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
812
+ this.query, this._pageCountAlias, countOperation);
813
+ const pageQuery = this.query.clone();
814
+ // A page count describes the full filtered set, not an aggregate-only page row.
815
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
816
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
817
+ const rows = await service.executeQuery(context.prepareQuery(pageQuery));
818
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
819
+ ? context.idSetPaginationCount!
820
+ : (totalCountBeforeRows ?? await service.executeCount(this.query, this._pageCountAlias, countOperation));
821
+ const queryRoot = new EntityRoot();
822
+ const data = new SmartList(rows.map((row: unknown) =>
823
+ row instanceof OrderItem
824
+ ? row
825
+ : OrderItem.fromRecord(row as Record<string, unknown>, queryRoot)));
826
+ data.totalCount = totalCount;
827
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
828
+ if (this.query.facets.length > 0) {
829
+ data.facets = await executeRelationFacets(
830
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
831
+ }
832
+ return { data, totalCount, offset, limit };
833
+ }
834
+
835
+ private async *executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<OrderItem> {
836
+ this.ensureIntent();
837
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
838
+ const service = context.requireResource<TeaQLDataService>("dataService");
839
+ const queryRoot = new EntityRoot();
840
+ for await (const chunk of service.executeForStream(this.query, chunkSize)) {
841
+ for (const entity of chunk) {
842
+ yield entity instanceof OrderItem
843
+ ? entity
844
+ : OrderItem.fromRecord(entity as Record<string, unknown>, queryRoot);
845
+ }
846
+ }
847
+ }
848
+
849
+ private ensureIntent(): void {
850
+ if (!this._comment?.trim()) {
851
+ throw new Error("Security audit failure: non-empty comment() is required before execution");
852
+ }
853
+ if (!this._purpose?.trim()) {
854
+ throw new Error("Security audit failure: non-empty purpose() is required before execution");
855
+ }
856
+ }
857
+
858
+ }
859
+
860
+ export class ExecutableOrderItemRequest {
861
+ constructor(
862
+ private readonly execute: (context: UserContext) => Promise<SmartList<OrderItem>>,
863
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
864
+ private readonly page: (
865
+ context: UserContext, offset: number, limit: number,
866
+ ) => Promise<TeaQLPage<OrderItem>>,
867
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<OrderItem>,
868
+ private readonly limitOne: () => void,
869
+ private readonly addComment: (comment: string) => void,
870
+ private readonly ensureIntent: () => void,
871
+ ) {}
872
+
873
+ comment(c: string): this {
874
+ this.addComment(c);
875
+ return this;
876
+ }
877
+
878
+ newEntity(context: UserContext): OrderItem {
879
+ this.ensureIntent();
880
+ return new OrderItem();
881
+ }
882
+
883
+ executeForList(context: UserContext): Promise<SmartList<OrderItem>> {
884
+ this.ensureIntent();
885
+ return this.execute(context);
886
+ }
887
+
888
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
889
+ this.ensureIntent();
890
+ return this.executeRows(context);
891
+ }
892
+
893
+ executeForPage(
894
+ context: UserContext, offset: number, limit: number,
895
+ ): Promise<TeaQLPage<OrderItem>> {
896
+ this.ensureIntent();
897
+ return this.page(context, offset, limit);
898
+ }
899
+
900
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<OrderItem> {
901
+ this.ensureIntent();
902
+ return this.stream(context, chunkSize);
903
+ }
904
+
905
+ async executeForOne(context: UserContext): Promise<OrderItem | undefined> {
906
+ this.limitOne();
907
+ return (await this.executeForList(context))[0];
908
+ }
909
+ }
source/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts ADDED
@@ -0,0 +1,1162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, TeaQLPage, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { OrderStatus } from '../models/OrderStatus';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning } from 'teaql-ts';
4
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
+
6
+
7
+
8
+ export class OrderStatusRequest {
9
+ private query: SelectQuery;
10
+ private filters: any[] = [];
11
+ private _purpose: string | undefined;
12
+ private _comment: string | undefined;
13
+ private _pageCountAlias: string | undefined;
14
+ private _pageCountMethod: "count" | "countAs" | undefined;
15
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
16
+
17
+ constructor(minimal = false) {
18
+ this.query = new SelectQuery("OrderStatus");
19
+ this.filters.push({ version: { "$gte": 1 } });
20
+ if (minimal) {
21
+ this.selectId();
22
+ this.selectVersion();
23
+ }
24
+ else this.selectSelfFields();
25
+ }
26
+
27
+ comment(c: string): this {
28
+ this.query.comment(c);
29
+ this._comment = c;
30
+ return this;
31
+ }
32
+
33
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
34
+ const base = this.query.clone();
35
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
36
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
37
+ this.query = merged.query as SelectQuery;
38
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
39
+ this._dynamicSearchWarnings.push(...merged.warnings);
40
+ return this;
41
+ }
42
+
43
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
44
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
45
+ }
46
+
47
+ purpose(p: string): ExecutableOrderStatusRequest {
48
+ this.query.purpose(p);
49
+ this._purpose = p;
50
+ return new ExecutableOrderStatusRequest(
51
+ (context) => this.executeForListInternal(context),
52
+ (context) => this.executeForRowsInternal(context),
53
+ (context, offset, limit) => this.executeForPageInternal(context, offset, limit),
54
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
55
+ () => this.limit(1),
56
+ (c) => this.comment(c),
57
+ () => this.ensureIntent());
58
+ }
59
+
60
+ optimizeForContinuousPageFetch(): this {
61
+ this.query.optimizeForContinuousPageFetch();
62
+ return this;
63
+ }
64
+
65
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
66
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
67
+ return this;
68
+ }
69
+
70
+ optimizePaginationWithIdSet(): this {
71
+ this.query.optimizePaginationWithIdSet();
72
+ return this;
73
+ }
74
+
75
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
76
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
77
+ return this;
78
+ }
79
+
80
+ topNProbeParentThreshold(threshold: number): this {
81
+ this.query.topNProbeParentThreshold(threshold);
82
+ return this;
83
+ }
84
+
85
+ limit(n: number): this {
86
+ this.query.limit(n);
87
+ return this;
88
+ }
89
+
90
+ offset(n: number): this {
91
+ this.query.offset(n);
92
+ return this;
93
+ }
94
+
95
+ toQuery(): SelectQuery {
96
+ if (this.filters.length > 0) {
97
+ this.query.filter({ "$and": this.filters });
98
+ }
99
+ return this.query;
100
+ }
101
+
102
+ withDeletedRows(): this {
103
+ this.filters = this.filters.filter(filter => !("version" in filter));
104
+ return this;
105
+ }
106
+
107
+ deletedRowsOnly(): this {
108
+ this.withDeletedRows();
109
+ this.filters.push({ version: { "$lte": -1 } });
110
+ return this;
111
+ }
112
+
113
+ selectSelfFields(): this {
114
+ this.query.select(["platform", "id", "name", "code", "color", "displayOrder", "version"]);
115
+ return this;
116
+ }
117
+
118
+ selectId(): this {
119
+ this.query.select(["id"]);
120
+ return this;
121
+ }
122
+
123
+ selectName(): this {
124
+ this.query.select(["name"]);
125
+ return this;
126
+ }
127
+
128
+ selectCode(): this {
129
+ this.query.select(["code"]);
130
+ return this;
131
+ }
132
+
133
+ selectColor(): this {
134
+ this.query.select(["color"]);
135
+ return this;
136
+ }
137
+
138
+ selectDisplayOrder(): this {
139
+ this.query.select(["displayOrder"]);
140
+ return this;
141
+ }
142
+
143
+ selectVersion(): this {
144
+ this.query.select(["version"]);
145
+ return this;
146
+ }
147
+
148
+
149
+ selectPlatformWith(request: { toQuery(): SelectQuery }): this {
150
+ this.query.select(["platform"]);
151
+ this.query.relationQuery(
152
+ "platform", request.toQuery(), "platform", "id", false,
153
+ { kind: "relation-select", method: "selectPlatformWith", relation: "platform" });
154
+ return this;
155
+ }
156
+
157
+ withPlatformMatching(request: { toQuery(): SelectQuery }): this {
158
+ this.filters.push({
159
+ "platform": {
160
+ "$inSubquery": { query: request.toQuery(), field: "id" },
161
+ },
162
+ });
163
+ return this;
164
+ }
165
+
166
+ withoutPlatformMatching(request: { toQuery(): SelectQuery }): this {
167
+ this.filters.push({
168
+ "platform": {
169
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
170
+ },
171
+ });
172
+ return this;
173
+ }
174
+
175
+ selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this {
176
+ this.query.relationQuery(
177
+ "customerOrderList", request.toQuery(), "id", "status", true,
178
+ { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" });
179
+ return this;
180
+ }
181
+
182
+ haveCustomerOrders(): this {
183
+ return this.withCustomerOrderListMatching({
184
+ toQuery: () => new SelectQuery("CustomerOrder"),
185
+ });
186
+ }
187
+
188
+ haveNoCustomerOrders(): this {
189
+ return this.withoutCustomerOrderListMatching({
190
+ toQuery: () => new SelectQuery("CustomerOrder"),
191
+ });
192
+ }
193
+
194
+ withCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
195
+ this.filters.push({
196
+ "id": {
197
+ "$inSubquery": {
198
+ query: request.toQuery(), field: "status",
199
+ },
200
+ },
201
+ });
202
+ return this;
203
+ }
204
+
205
+ withoutCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this {
206
+ this.filters.push({
207
+ "id": {
208
+ "$notInSubquery": {
209
+ query: request.toQuery(), field: "status",
210
+ },
211
+ },
212
+ });
213
+ return this;
214
+ }
215
+
216
+ countCustomerOrders(): this {
217
+ return this.countCustomerOrdersAs("countCustomerOrders");
218
+ }
219
+
220
+ countCustomerOrdersAs(alias: string): this {
221
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
222
+ this.countCustomerOrdersWith(alias, { toQuery: () => query });
223
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
224
+ kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias };
225
+ return this;
226
+ }
227
+
228
+ countCustomerOrdersWith(alias: string, child: { toQuery(): SelectQuery }): this {
229
+ const query = child.toQuery().clone();
230
+ query.aggregateItems = [];
231
+ query.aggregate("Count", "id", alias);
232
+ this.query.relationAggregate("customerOrderList", alias, query, true,
233
+ { kind: "relation-count", method: "countCustomerOrdersWith", relation: "customerOrderList", alias });
234
+ return this;
235
+ }
236
+
237
+ minTotalAmountOfCustomerOrders(): this {
238
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
239
+ return this.minTotalAmountOfCustomerOrdersAs(
240
+ "minOfTotalAmountOfCustomerOrders", { toQuery: () => query });
241
+ }
242
+
243
+ minTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
244
+ const query = child.toQuery().clone();
245
+ query.aggregateItems = [];
246
+ query.aggregate("min", "totalAmount", alias);
247
+ this.query.relationAggregate("customerOrderList", alias, query, true,
248
+ { kind: "aggregate", method: "minTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
249
+ return this;
250
+ }
251
+ maxTotalAmountOfCustomerOrders(): this {
252
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
253
+ return this.maxTotalAmountOfCustomerOrdersAs(
254
+ "maxOfTotalAmountOfCustomerOrders", { toQuery: () => query });
255
+ }
256
+
257
+ maxTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
258
+ const query = child.toQuery().clone();
259
+ query.aggregateItems = [];
260
+ query.aggregate("max", "totalAmount", alias);
261
+ this.query.relationAggregate("customerOrderList", alias, query, true,
262
+ { kind: "aggregate", method: "maxTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
263
+ return this;
264
+ }
265
+ sumTotalAmountOfCustomerOrders(): this {
266
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
267
+ return this.sumTotalAmountOfCustomerOrdersAs(
268
+ "sumOfTotalAmountOfCustomerOrders", { toQuery: () => query });
269
+ }
270
+
271
+ sumTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
272
+ const query = child.toQuery().clone();
273
+ query.aggregateItems = [];
274
+ query.aggregate("sum", "totalAmount", alias);
275
+ this.query.relationAggregate("customerOrderList", alias, query, true,
276
+ { kind: "aggregate", method: "sumTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
277
+ return this;
278
+ }
279
+ avgTotalAmountOfCustomerOrders(): this {
280
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
281
+ return this.avgTotalAmountOfCustomerOrdersAs(
282
+ "avgOfTotalAmountOfCustomerOrders", { toQuery: () => query });
283
+ }
284
+
285
+ avgTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
286
+ const query = child.toQuery().clone();
287
+ query.aggregateItems = [];
288
+ query.aggregate("avg", "totalAmount", alias);
289
+ this.query.relationAggregate("customerOrderList", alias, query, true,
290
+ { kind: "aggregate", method: "avgTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
291
+ return this;
292
+ }
293
+ standardDeviationTotalAmountOfCustomerOrders(): this {
294
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
295
+ return this.standardDeviationTotalAmountOfCustomerOrdersAs(
296
+ "standardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
297
+ }
298
+
299
+ standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
300
+ const query = child.toQuery().clone();
301
+ query.aggregateItems = [];
302
+ query.aggregate("stddev", "totalAmount", alias);
303
+ this.query.relationAggregate("customerOrderList", alias, query, true,
304
+ { kind: "aggregate", method: "standardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
305
+ return this;
306
+ }
307
+ squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this {
308
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
309
+ return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(
310
+ "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query });
311
+ }
312
+
313
+ squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
314
+ const query = child.toQuery().clone();
315
+ query.aggregateItems = [];
316
+ query.aggregate("stddev_pop", "totalAmount", alias);
317
+ this.query.relationAggregate("customerOrderList", alias, query, true,
318
+ { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
319
+ return this;
320
+ }
321
+ sampleVarianceTotalAmountOfCustomerOrders(): this {
322
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
323
+ return this.sampleVarianceTotalAmountOfCustomerOrdersAs(
324
+ "sampleVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
325
+ }
326
+
327
+ sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
328
+ const query = child.toQuery().clone();
329
+ query.aggregateItems = [];
330
+ query.aggregate("var_samp", "totalAmount", alias);
331
+ this.query.relationAggregate("customerOrderList", alias, query, true,
332
+ { kind: "aggregate", method: "sampleVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
333
+ return this;
334
+ }
335
+ samplePopulationVarianceTotalAmountOfCustomerOrders(): this {
336
+ const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } });
337
+ return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs(
338
+ "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query });
339
+ }
340
+
341
+ samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this {
342
+ const query = child.toQuery().clone();
343
+ query.aggregateItems = [];
344
+ query.aggregate("var_pop", "totalAmount", alias);
345
+ this.query.relationAggregate("customerOrderList", alias, query, true,
346
+ { kind: "aggregate", method: "samplePopulationVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias });
347
+ return this;
348
+ }
349
+
350
+ filterByPlatform(val: any): this {
351
+ this.filters.push({ "platform": { "$eq": val } });
352
+ return this;
353
+ }
354
+
355
+ filterByPlatformIn(...vals: any[]): this {
356
+ this.filters.push({ "platform": { "$in": vals } });
357
+ return this;
358
+ }
359
+
360
+ withPlatformIsKnown(): this {
361
+ this.filters.push({ "platform": { "$isNull": false } });
362
+ return this;
363
+ }
364
+
365
+ withPlatformIsUnknown(): this {
366
+ this.filters.push({ "platform": { "$isNull": true } });
367
+ return this;
368
+ }
369
+
370
+ withIdIs(val: any): this {
371
+ this.filters.push({ "id": { "$eq": val } });
372
+ return this;
373
+ }
374
+
375
+ withIdIsNot(val: any): this {
376
+ this.filters.push({ "id": { "$ne": val } });
377
+ return this;
378
+ }
379
+
380
+ withIdIn(...vals: any[]): this {
381
+ this.filters.push({ "id": { "$in": vals } });
382
+ return this;
383
+ }
384
+
385
+ withIdNotIn(...vals: any[]): this {
386
+ this.filters.push({ "id": { "$notIn": vals } });
387
+ return this;
388
+ }
389
+
390
+ withIdGreaterThan(val: any): this {
391
+ this.filters.push({ "id": { "$gt": val } });
392
+ return this;
393
+ }
394
+
395
+ withIdGreaterThanOrEqualTo(val: any): this {
396
+ this.filters.push({ "id": { "$gte": val } });
397
+ return this;
398
+ }
399
+
400
+ withIdLessThan(val: any): this {
401
+ this.filters.push({ "id": { "$lt": val } });
402
+ return this;
403
+ }
404
+
405
+ withIdLessThanOrEqualTo(val: any): this {
406
+ this.filters.push({ "id": { "$lte": val } });
407
+ return this;
408
+ }
409
+
410
+ withIdBetween(lower: any, upper: any): this {
411
+ this.filters.push({ "id": { "$between": [lower, upper] } });
412
+ return this;
413
+ }
414
+
415
+ withIdIsKnown(): this {
416
+ this.filters.push({ "id": { "$isNull": false } });
417
+ return this;
418
+ }
419
+
420
+ withIdIsUnknown(): this {
421
+ this.filters.push({ "id": { "$isNull": true } });
422
+ return this;
423
+ }
424
+
425
+ withNameContaining(val: string): this {
426
+ this.filters.push({ "name": { "$contains": val } });
427
+ return this;
428
+ }
429
+
430
+ withNameIs(val: string): this {
431
+ this.filters.push({ "name": { "$eq": val } });
432
+ return this;
433
+ }
434
+
435
+ withNameIsNot(val: any): this {
436
+ this.filters.push({ "name": { "$ne": val } });
437
+ return this;
438
+ }
439
+
440
+ withNameIn(...vals: any[]): this {
441
+ this.filters.push({ "name": { "$in": vals } });
442
+ return this;
443
+ }
444
+
445
+ withNameNotIn(...vals: any[]): this {
446
+ this.filters.push({ "name": { "$notIn": vals } });
447
+ return this;
448
+ }
449
+
450
+ withNameGreaterThan(val: any): this {
451
+ this.filters.push({ "name": { "$gt": val } });
452
+ return this;
453
+ }
454
+
455
+ withNameGreaterThanOrEqualTo(val: any): this {
456
+ this.filters.push({ "name": { "$gte": val } });
457
+ return this;
458
+ }
459
+
460
+ withNameLessThan(val: any): this {
461
+ this.filters.push({ "name": { "$lt": val } });
462
+ return this;
463
+ }
464
+
465
+ withNameLessThanOrEqualTo(val: any): this {
466
+ this.filters.push({ "name": { "$lte": val } });
467
+ return this;
468
+ }
469
+
470
+ withNameBetween(lower: any, upper: any): this {
471
+ this.filters.push({ "name": { "$between": [lower, upper] } });
472
+ return this;
473
+ }
474
+
475
+ withNameIsKnown(): this {
476
+ this.filters.push({ "name": { "$isNull": false } });
477
+ return this;
478
+ }
479
+
480
+ withNameIsUnknown(): this {
481
+ this.filters.push({ "name": { "$isNull": true } });
482
+ return this;
483
+ }
484
+ withNameNotContaining(val: string): this {
485
+ this.filters.push({ "name": { "$notContains": val } });
486
+ return this;
487
+ }
488
+
489
+ withNameStartingWith(val: string): this {
490
+ this.filters.push({ "name": { "$startsWith": val } });
491
+ return this;
492
+ }
493
+
494
+ withNameNotStartingWith(val: string): this {
495
+ this.filters.push({ "name": { "$notStartsWith": val } });
496
+ return this;
497
+ }
498
+
499
+ withNameEndingWith(val: string): this {
500
+ this.filters.push({ "name": { "$endsWith": val } });
501
+ return this;
502
+ }
503
+
504
+ withNameNotEndingWith(val: string): this {
505
+ this.filters.push({ "name": { "$notEndsWith": val } });
506
+ return this;
507
+ }
508
+
509
+ withNameSoundingLike(val: string): this {
510
+ this.filters.push({ "name": { "$soundLike": val } });
511
+ return this;
512
+ }
513
+
514
+ withCodeContaining(val: string): this {
515
+ this.filters.push({ "code": { "$contains": val } });
516
+ return this;
517
+ }
518
+
519
+ withCodeIs(val: string): this {
520
+ this.filters.push({ "code": { "$eq": val } });
521
+ return this;
522
+ }
523
+
524
+ withCodeIsNot(val: any): this {
525
+ this.filters.push({ "code": { "$ne": val } });
526
+ return this;
527
+ }
528
+
529
+ withCodeIn(...vals: any[]): this {
530
+ this.filters.push({ "code": { "$in": vals } });
531
+ return this;
532
+ }
533
+
534
+ withCodeNotIn(...vals: any[]): this {
535
+ this.filters.push({ "code": { "$notIn": vals } });
536
+ return this;
537
+ }
538
+
539
+ withCodeGreaterThan(val: any): this {
540
+ this.filters.push({ "code": { "$gt": val } });
541
+ return this;
542
+ }
543
+
544
+ withCodeGreaterThanOrEqualTo(val: any): this {
545
+ this.filters.push({ "code": { "$gte": val } });
546
+ return this;
547
+ }
548
+
549
+ withCodeLessThan(val: any): this {
550
+ this.filters.push({ "code": { "$lt": val } });
551
+ return this;
552
+ }
553
+
554
+ withCodeLessThanOrEqualTo(val: any): this {
555
+ this.filters.push({ "code": { "$lte": val } });
556
+ return this;
557
+ }
558
+
559
+ withCodeBetween(lower: any, upper: any): this {
560
+ this.filters.push({ "code": { "$between": [lower, upper] } });
561
+ return this;
562
+ }
563
+
564
+ withCodeIsKnown(): this {
565
+ this.filters.push({ "code": { "$isNull": false } });
566
+ return this;
567
+ }
568
+
569
+ withCodeIsUnknown(): this {
570
+ this.filters.push({ "code": { "$isNull": true } });
571
+ return this;
572
+ }
573
+ withCodeNotContaining(val: string): this {
574
+ this.filters.push({ "code": { "$notContains": val } });
575
+ return this;
576
+ }
577
+
578
+ withCodeStartingWith(val: string): this {
579
+ this.filters.push({ "code": { "$startsWith": val } });
580
+ return this;
581
+ }
582
+
583
+ withCodeNotStartingWith(val: string): this {
584
+ this.filters.push({ "code": { "$notStartsWith": val } });
585
+ return this;
586
+ }
587
+
588
+ withCodeEndingWith(val: string): this {
589
+ this.filters.push({ "code": { "$endsWith": val } });
590
+ return this;
591
+ }
592
+
593
+ withCodeNotEndingWith(val: string): this {
594
+ this.filters.push({ "code": { "$notEndsWith": val } });
595
+ return this;
596
+ }
597
+
598
+ withCodeSoundingLike(val: string): this {
599
+ this.filters.push({ "code": { "$soundLike": val } });
600
+ return this;
601
+ }
602
+
603
+ withColorContaining(val: string): this {
604
+ this.filters.push({ "color": { "$contains": val } });
605
+ return this;
606
+ }
607
+
608
+ withColorIs(val: string): this {
609
+ this.filters.push({ "color": { "$eq": val } });
610
+ return this;
611
+ }
612
+
613
+ withColorIsNot(val: any): this {
614
+ this.filters.push({ "color": { "$ne": val } });
615
+ return this;
616
+ }
617
+
618
+ withColorIn(...vals: any[]): this {
619
+ this.filters.push({ "color": { "$in": vals } });
620
+ return this;
621
+ }
622
+
623
+ withColorNotIn(...vals: any[]): this {
624
+ this.filters.push({ "color": { "$notIn": vals } });
625
+ return this;
626
+ }
627
+
628
+ withColorGreaterThan(val: any): this {
629
+ this.filters.push({ "color": { "$gt": val } });
630
+ return this;
631
+ }
632
+
633
+ withColorGreaterThanOrEqualTo(val: any): this {
634
+ this.filters.push({ "color": { "$gte": val } });
635
+ return this;
636
+ }
637
+
638
+ withColorLessThan(val: any): this {
639
+ this.filters.push({ "color": { "$lt": val } });
640
+ return this;
641
+ }
642
+
643
+ withColorLessThanOrEqualTo(val: any): this {
644
+ this.filters.push({ "color": { "$lte": val } });
645
+ return this;
646
+ }
647
+
648
+ withColorBetween(lower: any, upper: any): this {
649
+ this.filters.push({ "color": { "$between": [lower, upper] } });
650
+ return this;
651
+ }
652
+
653
+ withColorIsKnown(): this {
654
+ this.filters.push({ "color": { "$isNull": false } });
655
+ return this;
656
+ }
657
+
658
+ withColorIsUnknown(): this {
659
+ this.filters.push({ "color": { "$isNull": true } });
660
+ return this;
661
+ }
662
+ withColorNotContaining(val: string): this {
663
+ this.filters.push({ "color": { "$notContains": val } });
664
+ return this;
665
+ }
666
+
667
+ withColorStartingWith(val: string): this {
668
+ this.filters.push({ "color": { "$startsWith": val } });
669
+ return this;
670
+ }
671
+
672
+ withColorNotStartingWith(val: string): this {
673
+ this.filters.push({ "color": { "$notStartsWith": val } });
674
+ return this;
675
+ }
676
+
677
+ withColorEndingWith(val: string): this {
678
+ this.filters.push({ "color": { "$endsWith": val } });
679
+ return this;
680
+ }
681
+
682
+ withColorNotEndingWith(val: string): this {
683
+ this.filters.push({ "color": { "$notEndsWith": val } });
684
+ return this;
685
+ }
686
+
687
+ withColorSoundingLike(val: string): this {
688
+ this.filters.push({ "color": { "$soundLike": val } });
689
+ return this;
690
+ }
691
+
692
+ withDisplayOrderIs(val: any): this {
693
+ this.filters.push({ "displayOrder": { "$eq": val } });
694
+ return this;
695
+ }
696
+
697
+ withDisplayOrderIsNot(val: any): this {
698
+ this.filters.push({ "displayOrder": { "$ne": val } });
699
+ return this;
700
+ }
701
+
702
+ withDisplayOrderIn(...vals: any[]): this {
703
+ this.filters.push({ "displayOrder": { "$in": vals } });
704
+ return this;
705
+ }
706
+
707
+ withDisplayOrderNotIn(...vals: any[]): this {
708
+ this.filters.push({ "displayOrder": { "$notIn": vals } });
709
+ return this;
710
+ }
711
+
712
+ withDisplayOrderGreaterThan(val: any): this {
713
+ this.filters.push({ "displayOrder": { "$gt": val } });
714
+ return this;
715
+ }
716
+
717
+ withDisplayOrderGreaterThanOrEqualTo(val: any): this {
718
+ this.filters.push({ "displayOrder": { "$gte": val } });
719
+ return this;
720
+ }
721
+
722
+ withDisplayOrderLessThan(val: any): this {
723
+ this.filters.push({ "displayOrder": { "$lt": val } });
724
+ return this;
725
+ }
726
+
727
+ withDisplayOrderLessThanOrEqualTo(val: any): this {
728
+ this.filters.push({ "displayOrder": { "$lte": val } });
729
+ return this;
730
+ }
731
+
732
+ withDisplayOrderBetween(lower: any, upper: any): this {
733
+ this.filters.push({ "displayOrder": { "$between": [lower, upper] } });
734
+ return this;
735
+ }
736
+
737
+ withDisplayOrderIsKnown(): this {
738
+ this.filters.push({ "displayOrder": { "$isNull": false } });
739
+ return this;
740
+ }
741
+
742
+ withDisplayOrderIsUnknown(): this {
743
+ this.filters.push({ "displayOrder": { "$isNull": true } });
744
+ return this;
745
+ }
746
+
747
+ withVersionIs(val: any): this {
748
+ this.filters.push({ "version": { "$eq": val } });
749
+ return this;
750
+ }
751
+
752
+ withVersionIsNot(val: any): this {
753
+ this.filters.push({ "version": { "$ne": val } });
754
+ return this;
755
+ }
756
+
757
+ withVersionIn(...vals: any[]): this {
758
+ this.filters.push({ "version": { "$in": vals } });
759
+ return this;
760
+ }
761
+
762
+ withVersionNotIn(...vals: any[]): this {
763
+ this.filters.push({ "version": { "$notIn": vals } });
764
+ return this;
765
+ }
766
+
767
+ withVersionGreaterThan(val: any): this {
768
+ this.filters.push({ "version": { "$gt": val } });
769
+ return this;
770
+ }
771
+
772
+ withVersionGreaterThanOrEqualTo(val: any): this {
773
+ this.filters.push({ "version": { "$gte": val } });
774
+ return this;
775
+ }
776
+
777
+ withVersionLessThan(val: any): this {
778
+ this.filters.push({ "version": { "$lt": val } });
779
+ return this;
780
+ }
781
+
782
+ withVersionLessThanOrEqualTo(val: any): this {
783
+ this.filters.push({ "version": { "$lte": val } });
784
+ return this;
785
+ }
786
+
787
+ withVersionBetween(lower: any, upper: any): this {
788
+ this.filters.push({ "version": { "$between": [lower, upper] } });
789
+ return this;
790
+ }
791
+
792
+ withVersionIsKnown(): this {
793
+ this.filters.push({ "version": { "$isNull": false } });
794
+ return this;
795
+ }
796
+
797
+ withVersionIsUnknown(): this {
798
+ this.filters.push({ "version": { "$isNull": true } });
799
+ return this;
800
+ }
801
+
802
+ orderByIdAscending(): this {
803
+ this.query.orderBy("id", "asc");
804
+ return this;
805
+ }
806
+
807
+ orderByIdDescending(): this {
808
+ this.query.orderBy("id", "desc");
809
+ return this;
810
+ }
811
+
812
+ orderByNameAscending(): this {
813
+ this.query.orderBy("name", "asc");
814
+ return this;
815
+ }
816
+
817
+ orderByNameDescending(): this {
818
+ this.query.orderBy("name", "desc");
819
+ return this;
820
+ }
821
+
822
+ orderByCodeAscending(): this {
823
+ this.query.orderBy("code", "asc");
824
+ return this;
825
+ }
826
+
827
+ orderByCodeDescending(): this {
828
+ this.query.orderBy("code", "desc");
829
+ return this;
830
+ }
831
+
832
+ orderByColorAscending(): this {
833
+ this.query.orderBy("color", "asc");
834
+ return this;
835
+ }
836
+
837
+ orderByColorDescending(): this {
838
+ this.query.orderBy("color", "desc");
839
+ return this;
840
+ }
841
+
842
+ orderByDisplayOrderAscending(): this {
843
+ this.query.orderBy("displayOrder", "asc");
844
+ return this;
845
+ }
846
+
847
+ orderByDisplayOrderDescending(): this {
848
+ this.query.orderBy("displayOrder", "desc");
849
+ return this;
850
+ }
851
+
852
+ orderByVersionAscending(): this {
853
+ this.query.orderBy("version", "asc");
854
+ return this;
855
+ }
856
+
857
+ orderByVersionDescending(): this {
858
+ this.query.orderBy("version", "desc");
859
+ return this;
860
+ }
861
+
862
+
863
+ // --- Aggregations ---
864
+ count(): this {
865
+ this.query.aggregate("Count", "id", "count");
866
+ this._pageCountAlias = "count";
867
+ this._pageCountMethod = "count";
868
+ return this;
869
+ }
870
+
871
+ countAs(retName: string): this {
872
+ this.query.aggregate("Count", "id", retName);
873
+ this._pageCountAlias = retName;
874
+ this._pageCountMethod = "countAs";
875
+ return this;
876
+ }
877
+
878
+ minDisplayOrder(): this {
879
+ return this.minDisplayOrderAs("minOfDisplayOrder");
880
+ }
881
+
882
+ minDisplayOrderAs(retName: string): this {
883
+ this.query.aggregate("min", "displayOrder", retName);
884
+ return this;
885
+ }
886
+ maxDisplayOrder(): this {
887
+ return this.maxDisplayOrderAs("maxOfDisplayOrder");
888
+ }
889
+
890
+ maxDisplayOrderAs(retName: string): this {
891
+ this.query.aggregate("max", "displayOrder", retName);
892
+ return this;
893
+ }
894
+ sumDisplayOrder(): this {
895
+ return this.sumDisplayOrderAs("sumOfDisplayOrder");
896
+ }
897
+
898
+ sumDisplayOrderAs(retName: string): this {
899
+ this.query.aggregate("sum", "displayOrder", retName);
900
+ return this;
901
+ }
902
+ avgDisplayOrder(): this {
903
+ return this.avgDisplayOrderAs("avgOfDisplayOrder");
904
+ }
905
+
906
+ avgDisplayOrderAs(retName: string): this {
907
+ this.query.aggregate("avg", "displayOrder", retName);
908
+ return this;
909
+ }
910
+ standardDeviationDisplayOrder(): this {
911
+ return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder");
912
+ }
913
+
914
+ standardDeviationDisplayOrderAs(retName: string): this {
915
+ this.query.aggregate("stddev", "displayOrder", retName);
916
+ return this;
917
+ }
918
+ squareRootOfPopulationStandardDeviationDisplayOrder(): this {
919
+ return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder");
920
+ }
921
+
922
+ squareRootOfPopulationStandardDeviationDisplayOrderAs(retName: string): this {
923
+ this.query.aggregate("stddev_pop", "displayOrder", retName);
924
+ return this;
925
+ }
926
+ sampleVarianceDisplayOrder(): this {
927
+ return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder");
928
+ }
929
+
930
+ sampleVarianceDisplayOrderAs(retName: string): this {
931
+ this.query.aggregate("var_samp", "displayOrder", retName);
932
+ return this;
933
+ }
934
+ samplePopulationVarianceDisplayOrder(): this {
935
+ return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder");
936
+ }
937
+
938
+ samplePopulationVarianceDisplayOrderAs(retName: string): this {
939
+ this.query.aggregate("var_pop", "displayOrder", retName);
940
+ return this;
941
+ }
942
+
943
+ // --- Group By ---
944
+ groupByPlatform(): this {
945
+ this.query.groupBy("platform");
946
+ return this;
947
+ }
948
+
949
+ groupByPlatformAs(retName: string): this {
950
+ this.query.groupBy("platform"); // In TS we don't alias group by yet natively
951
+ return this;
952
+ }
953
+ groupById(): this {
954
+ this.query.groupBy("id");
955
+ return this;
956
+ }
957
+
958
+ groupByIdAs(retName: string): this {
959
+ this.query.groupBy("id"); // In TS we don't alias group by yet natively
960
+ return this;
961
+ }
962
+ groupByName(): this {
963
+ this.query.groupBy("name");
964
+ return this;
965
+ }
966
+
967
+ groupByNameAs(retName: string): this {
968
+ this.query.groupBy("name"); // In TS we don't alias group by yet natively
969
+ return this;
970
+ }
971
+ groupByCode(): this {
972
+ this.query.groupBy("code");
973
+ return this;
974
+ }
975
+
976
+ groupByCodeAs(retName: string): this {
977
+ this.query.groupBy("code"); // In TS we don't alias group by yet natively
978
+ return this;
979
+ }
980
+ groupByColor(): this {
981
+ this.query.groupBy("color");
982
+ return this;
983
+ }
984
+
985
+ groupByColorAs(retName: string): this {
986
+ this.query.groupBy("color"); // In TS we don't alias group by yet natively
987
+ return this;
988
+ }
989
+ groupByDisplayOrder(): this {
990
+ this.query.groupBy("displayOrder");
991
+ return this;
992
+ }
993
+
994
+ groupByDisplayOrderAs(retName: string): this {
995
+ this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively
996
+ return this;
997
+ }
998
+ groupByVersion(): this {
999
+ this.query.groupBy("version");
1000
+ return this;
1001
+ }
1002
+
1003
+ groupByVersionAs(retName: string): this {
1004
+ this.query.groupBy("version"); // In TS we don't alias group by yet natively
1005
+ return this;
1006
+ }
1007
+
1008
+ // --- Facets ---
1009
+ facetByPlatformAs(
1010
+ facetName: string,
1011
+ request: { toQuery(): SelectQuery },
1012
+ includeAllFacets = true,
1013
+ ): this {
1014
+ this.query.facetBy(facetName, "platform", request, includeAllFacets,
1015
+ { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName });
1016
+ return this;
1017
+ }
1018
+
1019
+
1020
+ private async executeForListInternal(context: UserContext): Promise<SmartList<OrderStatus>> {
1021
+ this.ensureIntent();
1022
+ if (this.filters.length > 0) {
1023
+ this.query.filter({ "$and": this.filters });
1024
+ }
1025
+
1026
+ const service = context.requireResource<TeaQLDataService>("dataService");
1027
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
1028
+ const queryRoot = new EntityRoot();
1029
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
1030
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
1031
+ row instanceof OrderStatus
1032
+ ? row
1033
+ : OrderStatus.fromRecord(row as Record<string, unknown>, queryRoot));
1034
+ const result = new SmartList<OrderStatus>(data);
1035
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
1036
+
1037
+ if (this.query.facets.length > 0) {
1038
+ result.facets = await executeRelationFacets(
1039
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
1040
+ }
1041
+
1042
+ return result;
1043
+ }
1044
+
1045
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
1046
+ this.ensureIntent();
1047
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
1048
+ const service = context.requireResource<TeaQLDataService>("dataService");
1049
+ return new SmartList<Record<string, unknown>>(
1050
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
1051
+ }
1052
+
1053
+ private async executeForPageInternal(
1054
+ context: UserContext, offset: number, limit: number,
1055
+ ): Promise<TeaQLPage<OrderStatus>> {
1056
+ this.ensureIntent();
1057
+ this.query.offset(offset).limit(limit);
1058
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
1059
+ const service = context.requireResource<TeaQLDataService>("dataService");
1060
+ const useIdSet = this.query.localIdSetPaginationOptions() !== undefined;
1061
+ const countOperation = { kind: "named-count" as const,
1062
+ method: this._pageCountMethod ?? "count",
1063
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
1064
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
1065
+ this.query, this._pageCountAlias, countOperation);
1066
+ const pageQuery = this.query.clone();
1067
+ // A page count describes the full filtered set, not an aggregate-only page row.
1068
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
1069
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
1070
+ const rows = await service.executeQuery(context.prepareQuery(pageQuery));
1071
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
1072
+ ? context.idSetPaginationCount!
1073
+ : (totalCountBeforeRows ?? await service.executeCount(this.query, this._pageCountAlias, countOperation));
1074
+ const queryRoot = new EntityRoot();
1075
+ const data = new SmartList(rows.map((row: unknown) =>
1076
+ row instanceof OrderStatus
1077
+ ? row
1078
+ : OrderStatus.fromRecord(row as Record<string, unknown>, queryRoot)));
1079
+ data.totalCount = totalCount;
1080
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
1081
+ if (this.query.facets.length > 0) {
1082
+ data.facets = await executeRelationFacets(
1083
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
1084
+ }
1085
+ return { data, totalCount, offset, limit };
1086
+ }
1087
+
1088
+ private async *executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<OrderStatus> {
1089
+ this.ensureIntent();
1090
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
1091
+ const service = context.requireResource<TeaQLDataService>("dataService");
1092
+ const queryRoot = new EntityRoot();
1093
+ for await (const chunk of service.executeForStream(this.query, chunkSize)) {
1094
+ for (const entity of chunk) {
1095
+ yield entity instanceof OrderStatus
1096
+ ? entity
1097
+ : OrderStatus.fromRecord(entity as Record<string, unknown>, queryRoot);
1098
+ }
1099
+ }
1100
+ }
1101
+
1102
+ private ensureIntent(): void {
1103
+ if (!this._comment?.trim()) {
1104
+ throw new Error("Security audit failure: non-empty comment() is required before execution");
1105
+ }
1106
+ if (!this._purpose?.trim()) {
1107
+ throw new Error("Security audit failure: non-empty purpose() is required before execution");
1108
+ }
1109
+ }
1110
+
1111
+ }
1112
+
1113
+ export class ExecutableOrderStatusRequest {
1114
+ constructor(
1115
+ private readonly execute: (context: UserContext) => Promise<SmartList<OrderStatus>>,
1116
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
1117
+ private readonly page: (
1118
+ context: UserContext, offset: number, limit: number,
1119
+ ) => Promise<TeaQLPage<OrderStatus>>,
1120
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<OrderStatus>,
1121
+ private readonly limitOne: () => void,
1122
+ private readonly addComment: (comment: string) => void,
1123
+ private readonly ensureIntent: () => void,
1124
+ ) {}
1125
+
1126
+ comment(c: string): this {
1127
+ this.addComment(c);
1128
+ return this;
1129
+ }
1130
+
1131
+ newEntity(context: UserContext): OrderStatus {
1132
+ this.ensureIntent();
1133
+ return new OrderStatus();
1134
+ }
1135
+
1136
+ executeForList(context: UserContext): Promise<SmartList<OrderStatus>> {
1137
+ this.ensureIntent();
1138
+ return this.execute(context);
1139
+ }
1140
+
1141
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
1142
+ this.ensureIntent();
1143
+ return this.executeRows(context);
1144
+ }
1145
+
1146
+ executeForPage(
1147
+ context: UserContext, offset: number, limit: number,
1148
+ ): Promise<TeaQLPage<OrderStatus>> {
1149
+ this.ensureIntent();
1150
+ return this.page(context, offset, limit);
1151
+ }
1152
+
1153
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<OrderStatus> {
1154
+ this.ensureIntent();
1155
+ return this.stream(context, chunkSize);
1156
+ }
1157
+
1158
+ async executeForOne(context: UserContext): Promise<OrderStatus | undefined> {
1159
+ this.limitOne();
1160
+ return (await this.executeForList(context))[0];
1161
+ }
1162
+ }
source/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, TeaQLPage, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { Platform } from '../models/Platform';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning } from 'teaql-ts';
4
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
5
+
6
+
7
+
8
+ export class PlatformRequest {
9
+ private query: SelectQuery;
10
+ private filters: any[] = [];
11
+ private _purpose: string | undefined;
12
+ private _comment: string | undefined;
13
+ private _pageCountAlias: string | undefined;
14
+ private _pageCountMethod: "count" | "countAs" | undefined;
15
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
16
+
17
+ constructor(minimal = false) {
18
+ this.query = new SelectQuery("Platform");
19
+ this.filters.push({ version: { "$gte": 1 } });
20
+ if (minimal) {
21
+ this.selectId();
22
+ this.selectVersion();
23
+ }
24
+ else this.selectSelfFields();
25
+ }
26
+
27
+ comment(c: string): this {
28
+ this.query.comment(c);
29
+ this._comment = c;
30
+ return this;
31
+ }
32
+
33
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
34
+ const base = this.query.clone();
35
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
36
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
37
+ this.query = merged.query as SelectQuery;
38
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
39
+ this._dynamicSearchWarnings.push(...merged.warnings);
40
+ return this;
41
+ }
42
+
43
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
44
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
45
+ }
46
+
47
+ purpose(p: string): ExecutablePlatformRequest {
48
+ this.query.purpose(p);
49
+ this._purpose = p;
50
+ return new ExecutablePlatformRequest(
51
+ (context) => this.executeForListInternal(context),
52
+ (context) => this.executeForRowsInternal(context),
53
+ (context, offset, limit) => this.executeForPageInternal(context, offset, limit),
54
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
55
+ () => this.limit(1),
56
+ (c) => this.comment(c),
57
+ () => this.ensureIntent());
58
+ }
59
+
60
+ optimizeForContinuousPageFetch(): this {
61
+ this.query.optimizeForContinuousPageFetch();
62
+ return this;
63
+ }
64
+
65
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
66
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
67
+ return this;
68
+ }
69
+
70
+ optimizePaginationWithIdSet(): this {
71
+ this.query.optimizePaginationWithIdSet();
72
+ return this;
73
+ }
74
+
75
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
76
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
77
+ return this;
78
+ }
79
+
80
+ topNProbeParentThreshold(threshold: number): this {
81
+ this.query.topNProbeParentThreshold(threshold);
82
+ return this;
83
+ }
84
+
85
+ limit(n: number): this {
86
+ this.query.limit(n);
87
+ return this;
88
+ }
89
+
90
+ offset(n: number): this {
91
+ this.query.offset(n);
92
+ return this;
93
+ }
94
+
95
+ toQuery(): SelectQuery {
96
+ if (this.filters.length > 0) {
97
+ this.query.filter({ "$and": this.filters });
98
+ }
99
+ return this.query;
100
+ }
101
+
102
+ withDeletedRows(): this {
103
+ this.filters = this.filters.filter(filter => !("version" in filter));
104
+ return this;
105
+ }
106
+
107
+ deletedRowsOnly(): this {
108
+ this.withDeletedRows();
109
+ this.filters.push({ version: { "$lte": -1 } });
110
+ return this;
111
+ }
112
+
113
+ selectSelfFields(): this {
114
+ this.query.select(["id", "name", "version"]);
115
+ return this;
116
+ }
117
+
118
+ selectId(): this {
119
+ this.query.select(["id"]);
120
+ return this;
121
+ }
122
+
123
+ selectName(): this {
124
+ this.query.select(["name"]);
125
+ return this;
126
+ }
127
+
128
+ selectVersion(): this {
129
+ this.query.select(["version"]);
130
+ return this;
131
+ }
132
+
133
+
134
+
135
+
136
+ selectOrderStatusListWith(request: { toQuery(): SelectQuery }): this {
137
+ this.query.relationQuery(
138
+ "orderStatusList", request.toQuery(), "id", "platform", true,
139
+ { kind: "relation-select", method: "selectOrderStatusListWith", relation: "orderStatusList" });
140
+ return this;
141
+ }
142
+ selectCustomerListWith(request: { toQuery(): SelectQuery }): this {
143
+ this.query.relationQuery(
144
+ "customerList", request.toQuery(), "id", "platform", true,
145
+ { kind: "relation-select", method: "selectCustomerListWith", relation: "customerList" });
146
+ return this;
147
+ }
148
+
149
+ haveOrderStatuses(): this {
150
+ return this.withOrderStatusListMatching({
151
+ toQuery: () => new SelectQuery("OrderStatus"),
152
+ });
153
+ }
154
+
155
+ haveNoOrderStatuses(): this {
156
+ return this.withoutOrderStatusListMatching({
157
+ toQuery: () => new SelectQuery("OrderStatus"),
158
+ });
159
+ }
160
+
161
+ withOrderStatusListMatching(request: { toQuery(): SelectQuery }): this {
162
+ this.filters.push({
163
+ "id": {
164
+ "$inSubquery": {
165
+ query: request.toQuery(), field: "platform",
166
+ },
167
+ },
168
+ });
169
+ return this;
170
+ }
171
+
172
+ withoutOrderStatusListMatching(request: { toQuery(): SelectQuery }): this {
173
+ this.filters.push({
174
+ "id": {
175
+ "$notInSubquery": {
176
+ query: request.toQuery(), field: "platform",
177
+ },
178
+ },
179
+ });
180
+ return this;
181
+ }
182
+ haveCustomers(): this {
183
+ return this.withCustomerListMatching({
184
+ toQuery: () => new SelectQuery("Customer"),
185
+ });
186
+ }
187
+
188
+ haveNoCustomers(): this {
189
+ return this.withoutCustomerListMatching({
190
+ toQuery: () => new SelectQuery("Customer"),
191
+ });
192
+ }
193
+
194
+ withCustomerListMatching(request: { toQuery(): SelectQuery }): this {
195
+ this.filters.push({
196
+ "id": {
197
+ "$inSubquery": {
198
+ query: request.toQuery(), field: "platform",
199
+ },
200
+ },
201
+ });
202
+ return this;
203
+ }
204
+
205
+ withoutCustomerListMatching(request: { toQuery(): SelectQuery }): this {
206
+ this.filters.push({
207
+ "id": {
208
+ "$notInSubquery": {
209
+ query: request.toQuery(), field: "platform",
210
+ },
211
+ },
212
+ });
213
+ return this;
214
+ }
215
+
216
+ countOrderStatuses(): this {
217
+ return this.countOrderStatusesAs("countOrderStatuses");
218
+ }
219
+
220
+ countOrderStatusesAs(alias: string): this {
221
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
222
+ this.countOrderStatusesWith(alias, { toQuery: () => query });
223
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
224
+ kind: "relation-count", method: "countOrderStatusesAs", relation: "orderStatusList", alias };
225
+ return this;
226
+ }
227
+
228
+ countOrderStatusesWith(alias: string, child: { toQuery(): SelectQuery }): this {
229
+ const query = child.toQuery().clone();
230
+ query.aggregateItems = [];
231
+ query.aggregate("Count", "id", alias);
232
+ this.query.relationAggregate("orderStatusList", alias, query, true,
233
+ { kind: "relation-count", method: "countOrderStatusesWith", relation: "orderStatusList", alias });
234
+ return this;
235
+ }
236
+
237
+ minDisplayOrderOfOrderStatuses(): this {
238
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
239
+ return this.minDisplayOrderOfOrderStatusesAs(
240
+ "minOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
241
+ }
242
+
243
+ minDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
244
+ const query = child.toQuery().clone();
245
+ query.aggregateItems = [];
246
+ query.aggregate("min", "displayOrder", alias);
247
+ this.query.relationAggregate("orderStatusList", alias, query, true,
248
+ { kind: "aggregate", method: "minDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
249
+ return this;
250
+ }
251
+ maxDisplayOrderOfOrderStatuses(): this {
252
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
253
+ return this.maxDisplayOrderOfOrderStatusesAs(
254
+ "maxOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
255
+ }
256
+
257
+ maxDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
258
+ const query = child.toQuery().clone();
259
+ query.aggregateItems = [];
260
+ query.aggregate("max", "displayOrder", alias);
261
+ this.query.relationAggregate("orderStatusList", alias, query, true,
262
+ { kind: "aggregate", method: "maxDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
263
+ return this;
264
+ }
265
+ sumDisplayOrderOfOrderStatuses(): this {
266
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
267
+ return this.sumDisplayOrderOfOrderStatusesAs(
268
+ "sumOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
269
+ }
270
+
271
+ sumDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
272
+ const query = child.toQuery().clone();
273
+ query.aggregateItems = [];
274
+ query.aggregate("sum", "displayOrder", alias);
275
+ this.query.relationAggregate("orderStatusList", alias, query, true,
276
+ { kind: "aggregate", method: "sumDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
277
+ return this;
278
+ }
279
+ avgDisplayOrderOfOrderStatuses(): this {
280
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
281
+ return this.avgDisplayOrderOfOrderStatusesAs(
282
+ "avgOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
283
+ }
284
+
285
+ avgDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
286
+ const query = child.toQuery().clone();
287
+ query.aggregateItems = [];
288
+ query.aggregate("avg", "displayOrder", alias);
289
+ this.query.relationAggregate("orderStatusList", alias, query, true,
290
+ { kind: "aggregate", method: "avgDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
291
+ return this;
292
+ }
293
+ standardDeviationDisplayOrderOfOrderStatuses(): this {
294
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
295
+ return this.standardDeviationDisplayOrderOfOrderStatusesAs(
296
+ "standardDeviationOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
297
+ }
298
+
299
+ standardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
300
+ const query = child.toQuery().clone();
301
+ query.aggregateItems = [];
302
+ query.aggregate("stddev", "displayOrder", alias);
303
+ this.query.relationAggregate("orderStatusList", alias, query, true,
304
+ { kind: "aggregate", method: "standardDeviationDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
305
+ return this;
306
+ }
307
+ squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(): this {
308
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
309
+ return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(
310
+ "squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
311
+ }
312
+
313
+ squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
314
+ const query = child.toQuery().clone();
315
+ query.aggregateItems = [];
316
+ query.aggregate("stddev_pop", "displayOrder", alias);
317
+ this.query.relationAggregate("orderStatusList", alias, query, true,
318
+ { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
319
+ return this;
320
+ }
321
+ sampleVarianceDisplayOrderOfOrderStatuses(): this {
322
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
323
+ return this.sampleVarianceDisplayOrderOfOrderStatusesAs(
324
+ "sampleVarianceOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
325
+ }
326
+
327
+ sampleVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
328
+ const query = child.toQuery().clone();
329
+ query.aggregateItems = [];
330
+ query.aggregate("var_samp", "displayOrder", alias);
331
+ this.query.relationAggregate("orderStatusList", alias, query, true,
332
+ { kind: "aggregate", method: "sampleVarianceDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
333
+ return this;
334
+ }
335
+ samplePopulationVarianceDisplayOrderOfOrderStatuses(): this {
336
+ const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } });
337
+ return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs(
338
+ "samplePopulationVarianceOfDisplayOrderOfOrderStatuses", { toQuery: () => query });
339
+ }
340
+
341
+ samplePopulationVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this {
342
+ const query = child.toQuery().clone();
343
+ query.aggregateItems = [];
344
+ query.aggregate("var_pop", "displayOrder", alias);
345
+ this.query.relationAggregate("orderStatusList", alias, query, true,
346
+ { kind: "aggregate", method: "samplePopulationVarianceDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias });
347
+ return this;
348
+ }
349
+ countCustomers(): this {
350
+ return this.countCustomersAs("countCustomers");
351
+ }
352
+
353
+ countCustomersAs(alias: string): this {
354
+ const query = new SelectQuery("Customer").filter({ version: { "$gte": 1 } });
355
+ this.countCustomersWith(alias, { toQuery: () => query });
356
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
357
+ kind: "relation-count", method: "countCustomersAs", relation: "customerList", alias };
358
+ return this;
359
+ }
360
+
361
+ countCustomersWith(alias: string, child: { toQuery(): SelectQuery }): this {
362
+ const query = child.toQuery().clone();
363
+ query.aggregateItems = [];
364
+ query.aggregate("Count", "id", alias);
365
+ this.query.relationAggregate("customerList", alias, query, true,
366
+ { kind: "relation-count", method: "countCustomersWith", relation: "customerList", alias });
367
+ return this;
368
+ }
369
+
370
+
371
+
372
+ withIdIs(val: any): this {
373
+ this.filters.push({ "id": { "$eq": val } });
374
+ return this;
375
+ }
376
+
377
+ withIdIsNot(val: any): this {
378
+ this.filters.push({ "id": { "$ne": val } });
379
+ return this;
380
+ }
381
+
382
+ withIdIn(...vals: any[]): this {
383
+ this.filters.push({ "id": { "$in": vals } });
384
+ return this;
385
+ }
386
+
387
+ withIdNotIn(...vals: any[]): this {
388
+ this.filters.push({ "id": { "$notIn": vals } });
389
+ return this;
390
+ }
391
+
392
+ withIdGreaterThan(val: any): this {
393
+ this.filters.push({ "id": { "$gt": val } });
394
+ return this;
395
+ }
396
+
397
+ withIdGreaterThanOrEqualTo(val: any): this {
398
+ this.filters.push({ "id": { "$gte": val } });
399
+ return this;
400
+ }
401
+
402
+ withIdLessThan(val: any): this {
403
+ this.filters.push({ "id": { "$lt": val } });
404
+ return this;
405
+ }
406
+
407
+ withIdLessThanOrEqualTo(val: any): this {
408
+ this.filters.push({ "id": { "$lte": val } });
409
+ return this;
410
+ }
411
+
412
+ withIdBetween(lower: any, upper: any): this {
413
+ this.filters.push({ "id": { "$between": [lower, upper] } });
414
+ return this;
415
+ }
416
+
417
+ withIdIsKnown(): this {
418
+ this.filters.push({ "id": { "$isNull": false } });
419
+ return this;
420
+ }
421
+
422
+ withIdIsUnknown(): this {
423
+ this.filters.push({ "id": { "$isNull": true } });
424
+ return this;
425
+ }
426
+
427
+ withNameContaining(val: string): this {
428
+ this.filters.push({ "name": { "$contains": val } });
429
+ return this;
430
+ }
431
+
432
+ withNameIs(val: string): this {
433
+ this.filters.push({ "name": { "$eq": val } });
434
+ return this;
435
+ }
436
+
437
+ withNameIsNot(val: any): this {
438
+ this.filters.push({ "name": { "$ne": val } });
439
+ return this;
440
+ }
441
+
442
+ withNameIn(...vals: any[]): this {
443
+ this.filters.push({ "name": { "$in": vals } });
444
+ return this;
445
+ }
446
+
447
+ withNameNotIn(...vals: any[]): this {
448
+ this.filters.push({ "name": { "$notIn": vals } });
449
+ return this;
450
+ }
451
+
452
+ withNameGreaterThan(val: any): this {
453
+ this.filters.push({ "name": { "$gt": val } });
454
+ return this;
455
+ }
456
+
457
+ withNameGreaterThanOrEqualTo(val: any): this {
458
+ this.filters.push({ "name": { "$gte": val } });
459
+ return this;
460
+ }
461
+
462
+ withNameLessThan(val: any): this {
463
+ this.filters.push({ "name": { "$lt": val } });
464
+ return this;
465
+ }
466
+
467
+ withNameLessThanOrEqualTo(val: any): this {
468
+ this.filters.push({ "name": { "$lte": val } });
469
+ return this;
470
+ }
471
+
472
+ withNameBetween(lower: any, upper: any): this {
473
+ this.filters.push({ "name": { "$between": [lower, upper] } });
474
+ return this;
475
+ }
476
+
477
+ withNameIsKnown(): this {
478
+ this.filters.push({ "name": { "$isNull": false } });
479
+ return this;
480
+ }
481
+
482
+ withNameIsUnknown(): this {
483
+ this.filters.push({ "name": { "$isNull": true } });
484
+ return this;
485
+ }
486
+ withNameNotContaining(val: string): this {
487
+ this.filters.push({ "name": { "$notContains": val } });
488
+ return this;
489
+ }
490
+
491
+ withNameStartingWith(val: string): this {
492
+ this.filters.push({ "name": { "$startsWith": val } });
493
+ return this;
494
+ }
495
+
496
+ withNameNotStartingWith(val: string): this {
497
+ this.filters.push({ "name": { "$notStartsWith": val } });
498
+ return this;
499
+ }
500
+
501
+ withNameEndingWith(val: string): this {
502
+ this.filters.push({ "name": { "$endsWith": val } });
503
+ return this;
504
+ }
505
+
506
+ withNameNotEndingWith(val: string): this {
507
+ this.filters.push({ "name": { "$notEndsWith": val } });
508
+ return this;
509
+ }
510
+
511
+ withNameSoundingLike(val: string): this {
512
+ this.filters.push({ "name": { "$soundLike": val } });
513
+ return this;
514
+ }
515
+
516
+ withVersionIs(val: any): this {
517
+ this.filters.push({ "version": { "$eq": val } });
518
+ return this;
519
+ }
520
+
521
+ withVersionIsNot(val: any): this {
522
+ this.filters.push({ "version": { "$ne": val } });
523
+ return this;
524
+ }
525
+
526
+ withVersionIn(...vals: any[]): this {
527
+ this.filters.push({ "version": { "$in": vals } });
528
+ return this;
529
+ }
530
+
531
+ withVersionNotIn(...vals: any[]): this {
532
+ this.filters.push({ "version": { "$notIn": vals } });
533
+ return this;
534
+ }
535
+
536
+ withVersionGreaterThan(val: any): this {
537
+ this.filters.push({ "version": { "$gt": val } });
538
+ return this;
539
+ }
540
+
541
+ withVersionGreaterThanOrEqualTo(val: any): this {
542
+ this.filters.push({ "version": { "$gte": val } });
543
+ return this;
544
+ }
545
+
546
+ withVersionLessThan(val: any): this {
547
+ this.filters.push({ "version": { "$lt": val } });
548
+ return this;
549
+ }
550
+
551
+ withVersionLessThanOrEqualTo(val: any): this {
552
+ this.filters.push({ "version": { "$lte": val } });
553
+ return this;
554
+ }
555
+
556
+ withVersionBetween(lower: any, upper: any): this {
557
+ this.filters.push({ "version": { "$between": [lower, upper] } });
558
+ return this;
559
+ }
560
+
561
+ withVersionIsKnown(): this {
562
+ this.filters.push({ "version": { "$isNull": false } });
563
+ return this;
564
+ }
565
+
566
+ withVersionIsUnknown(): this {
567
+ this.filters.push({ "version": { "$isNull": true } });
568
+ return this;
569
+ }
570
+
571
+ orderByIdAscending(): this {
572
+ this.query.orderBy("id", "asc");
573
+ return this;
574
+ }
575
+
576
+ orderByIdDescending(): this {
577
+ this.query.orderBy("id", "desc");
578
+ return this;
579
+ }
580
+
581
+ orderByNameAscending(): this {
582
+ this.query.orderBy("name", "asc");
583
+ return this;
584
+ }
585
+
586
+ orderByNameDescending(): this {
587
+ this.query.orderBy("name", "desc");
588
+ return this;
589
+ }
590
+
591
+ orderByVersionAscending(): this {
592
+ this.query.orderBy("version", "asc");
593
+ return this;
594
+ }
595
+
596
+ orderByVersionDescending(): this {
597
+ this.query.orderBy("version", "desc");
598
+ return this;
599
+ }
600
+
601
+
602
+ // --- Aggregations ---
603
+ count(): this {
604
+ this.query.aggregate("Count", "id", "count");
605
+ this._pageCountAlias = "count";
606
+ this._pageCountMethod = "count";
607
+ return this;
608
+ }
609
+
610
+ countAs(retName: string): this {
611
+ this.query.aggregate("Count", "id", retName);
612
+ this._pageCountAlias = retName;
613
+ this._pageCountMethod = "countAs";
614
+ return this;
615
+ }
616
+
617
+
618
+ // --- Group By ---
619
+ groupById(): this {
620
+ this.query.groupBy("id");
621
+ return this;
622
+ }
623
+
624
+ groupByIdAs(retName: string): this {
625
+ this.query.groupBy("id"); // In TS we don't alias group by yet natively
626
+ return this;
627
+ }
628
+ groupByName(): this {
629
+ this.query.groupBy("name");
630
+ return this;
631
+ }
632
+
633
+ groupByNameAs(retName: string): this {
634
+ this.query.groupBy("name"); // In TS we don't alias group by yet natively
635
+ return this;
636
+ }
637
+ groupByVersion(): this {
638
+ this.query.groupBy("version");
639
+ return this;
640
+ }
641
+
642
+ groupByVersionAs(retName: string): this {
643
+ this.query.groupBy("version"); // In TS we don't alias group by yet natively
644
+ return this;
645
+ }
646
+
647
+ // --- Facets ---
648
+
649
+ private async executeForListInternal(context: UserContext): Promise<SmartList<Platform>> {
650
+ this.ensureIntent();
651
+ if (this.filters.length > 0) {
652
+ this.query.filter({ "$and": this.filters });
653
+ }
654
+
655
+ const service = context.requireResource<TeaQLDataService>("dataService");
656
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
657
+ const queryRoot = new EntityRoot();
658
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
659
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
660
+ row instanceof Platform
661
+ ? row
662
+ : Platform.fromRecord(row as Record<string, unknown>, queryRoot));
663
+ const result = new SmartList<Platform>(data);
664
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
665
+
666
+ if (this.query.facets.length > 0) {
667
+ result.facets = await executeRelationFacets(
668
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
669
+ }
670
+
671
+ return result;
672
+ }
673
+
674
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
675
+ this.ensureIntent();
676
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
677
+ const service = context.requireResource<TeaQLDataService>("dataService");
678
+ return new SmartList<Record<string, unknown>>(
679
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
680
+ }
681
+
682
+ private async executeForPageInternal(
683
+ context: UserContext, offset: number, limit: number,
684
+ ): Promise<TeaQLPage<Platform>> {
685
+ this.ensureIntent();
686
+ this.query.offset(offset).limit(limit);
687
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
688
+ const service = context.requireResource<TeaQLDataService>("dataService");
689
+ const useIdSet = this.query.localIdSetPaginationOptions() !== undefined;
690
+ const countOperation = { kind: "named-count" as const,
691
+ method: this._pageCountMethod ?? "count",
692
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
693
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
694
+ this.query, this._pageCountAlias, countOperation);
695
+ const pageQuery = this.query.clone();
696
+ // A page count describes the full filtered set, not an aggregate-only page row.
697
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
698
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
699
+ const rows = await service.executeQuery(context.prepareQuery(pageQuery));
700
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
701
+ ? context.idSetPaginationCount!
702
+ : (totalCountBeforeRows ?? await service.executeCount(this.query, this._pageCountAlias, countOperation));
703
+ const queryRoot = new EntityRoot();
704
+ const data = new SmartList(rows.map((row: unknown) =>
705
+ row instanceof Platform
706
+ ? row
707
+ : Platform.fromRecord(row as Record<string, unknown>, queryRoot)));
708
+ data.totalCount = totalCount;
709
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
710
+ if (this.query.facets.length > 0) {
711
+ data.facets = await executeRelationFacets(
712
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
713
+ }
714
+ return { data, totalCount, offset, limit };
715
+ }
716
+
717
+ private async *executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<Platform> {
718
+ this.ensureIntent();
719
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
720
+ const service = context.requireResource<TeaQLDataService>("dataService");
721
+ const queryRoot = new EntityRoot();
722
+ for await (const chunk of service.executeForStream(this.query, chunkSize)) {
723
+ for (const entity of chunk) {
724
+ yield entity instanceof Platform
725
+ ? entity
726
+ : Platform.fromRecord(entity as Record<string, unknown>, queryRoot);
727
+ }
728
+ }
729
+ }
730
+
731
+ private ensureIntent(): void {
732
+ if (!this._comment?.trim()) {
733
+ throw new Error("Security audit failure: non-empty comment() is required before execution");
734
+ }
735
+ if (!this._purpose?.trim()) {
736
+ throw new Error("Security audit failure: non-empty purpose() is required before execution");
737
+ }
738
+ }
739
+
740
+ }
741
+
742
+ export class ExecutablePlatformRequest {
743
+ constructor(
744
+ private readonly execute: (context: UserContext) => Promise<SmartList<Platform>>,
745
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
746
+ private readonly page: (
747
+ context: UserContext, offset: number, limit: number,
748
+ ) => Promise<TeaQLPage<Platform>>,
749
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<Platform>,
750
+ private readonly limitOne: () => void,
751
+ private readonly addComment: (comment: string) => void,
752
+ private readonly ensureIntent: () => void,
753
+ ) {}
754
+
755
+ comment(c: string): this {
756
+ this.addComment(c);
757
+ return this;
758
+ }
759
+
760
+ newEntity(context: UserContext): Platform {
761
+ this.ensureIntent();
762
+ return new Platform();
763
+ }
764
+
765
+ executeForList(context: UserContext): Promise<SmartList<Platform>> {
766
+ this.ensureIntent();
767
+ return this.execute(context);
768
+ }
769
+
770
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
771
+ this.ensureIntent();
772
+ return this.executeRows(context);
773
+ }
774
+
775
+ executeForPage(
776
+ context: UserContext, offset: number, limit: number,
777
+ ): Promise<TeaQLPage<Platform>> {
778
+ this.ensureIntent();
779
+ return this.page(context, offset, limit);
780
+ }
781
+
782
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<Platform> {
783
+ this.ensureIntent();
784
+ return this.stream(context, chunkSize);
785
+ }
786
+
787
+ async executeForOne(context: UserContext): Promise<Platform | undefined> {
788
+ this.limitOne();
789
+ return (await this.executeForList(context))[0];
790
+ }
791
+ }
source/browser-sqlite/orders-lib/src/runtime-module.ts ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ObjectLocation, RuntimeModule } from "teaql-ts";
2
+ import { ENTITY_SCHEMAS } from "./teaql-schemas";
3
+ import { ensureGeneratedBootstrap } from "./generated-bootstrap";
4
+
5
+ /** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */
6
+ export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({
7
+ profile: "camelCase" as const,
8
+ entities: Object.freeze({
9
+ "Platform": Object.freeze({
10
+ entityType: "Platform",
11
+ profile: "camelCase" as const,
12
+ fields: Object.freeze({
13
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
14
+ "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }),
15
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
16
+ }),
17
+ }),
18
+ "OrderStatus": Object.freeze({
19
+ entityType: "OrderStatus",
20
+ profile: "camelCase" as const,
21
+ fields: Object.freeze({
22
+ "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }),
23
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
24
+ "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }),
25
+ "code": Object.freeze({ canonicalName: "code", wireName: "code", aliases: Object.freeze([] as string[]) }),
26
+ "color": Object.freeze({ canonicalName: "color", wireName: "color", aliases: Object.freeze([] as string[]) }),
27
+ "display_order": Object.freeze({ canonicalName: "display_order", wireName: "displayOrder", aliases: Object.freeze([] as string[]) }),
28
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
29
+ }),
30
+ }),
31
+ "Customer": Object.freeze({
32
+ entityType: "Customer",
33
+ profile: "camelCase" as const,
34
+ fields: Object.freeze({
35
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
36
+ "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }),
37
+ "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }),
38
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
39
+ }),
40
+ }),
41
+ "CustomerOrder": Object.freeze({
42
+ entityType: "CustomerOrder",
43
+ profile: "camelCase" as const,
44
+ fields: Object.freeze({
45
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
46
+ "customer": Object.freeze({ canonicalName: "customer", wireName: "customer", aliases: Object.freeze([] as string[]) }),
47
+ "status": Object.freeze({ canonicalName: "status", wireName: "status", aliases: Object.freeze([] as string[]) }),
48
+ "order_number": Object.freeze({ canonicalName: "order_number", wireName: "orderNumber", aliases: Object.freeze([] as string[]) }),
49
+ "order_date": Object.freeze({ canonicalName: "order_date", wireName: "orderDate", aliases: Object.freeze([] as string[]) }),
50
+ "total_amount": Object.freeze({ canonicalName: "total_amount", wireName: "totalAmount", aliases: Object.freeze([] as string[]) }),
51
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
52
+ }),
53
+ }),
54
+ "OrderItem": Object.freeze({
55
+ entityType: "OrderItem",
56
+ profile: "camelCase" as const,
57
+ fields: Object.freeze({
58
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
59
+ "customer_order": Object.freeze({ canonicalName: "customer_order", wireName: "customerOrder", aliases: Object.freeze([] as string[]) }),
60
+ "product_name": Object.freeze({ canonicalName: "product_name", wireName: "productName", aliases: Object.freeze([] as string[]) }),
61
+ "quantity": Object.freeze({ canonicalName: "quantity", wireName: "quantity", aliases: Object.freeze([] as string[]) }),
62
+ "unit_price": Object.freeze({ canonicalName: "unit_price", wireName: "unitPrice", aliases: Object.freeze([] as string[]) }),
63
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
64
+ }),
65
+ })
66
+ }),
67
+ });
68
+
69
+ /** Passive generated metadata manifest. It never modifies the database schema. */
70
+ export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, {
71
+ "Platform": {
72
+ checkAndFix(context, mutation, results) {
73
+ const now = context.getResource("fixTime");
74
+ if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") });
75
+ if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 });
76
+
77
+
78
+ },
79
+ },
80
+ "OrderStatus": {
81
+ checkAndFix(context, mutation, results) {
82
+ const now = context.getResource("fixTime");
83
+ if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") });
84
+
85
+
86
+ if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") });
87
+ if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 });
88
+
89
+ if ((mutation.action === "Create" && mutation.payload["code"] === undefined) || mutation.payload["code"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("code") });
90
+ if (mutation.payload["code"] != null && [...String(mutation.payload["code"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("code"), inputValue: mutation.payload["code"], systemValue: 100 });
91
+
92
+ if ((mutation.action === "Create" && mutation.payload["color"] === undefined) || mutation.payload["color"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("color") });
93
+ if (mutation.payload["color"] != null && [...String(mutation.payload["color"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("color"), inputValue: mutation.payload["color"], systemValue: 100 });
94
+
95
+ if ((mutation.action === "Create" && mutation.payload["display_order"] === undefined) || mutation.payload["display_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("display_order") });
96
+
97
+
98
+ },
99
+ },
100
+ "Customer": {
101
+ checkAndFix(context, mutation, results) {
102
+ const now = context.getResource("fixTime");
103
+ if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") });
104
+
105
+ if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") });
106
+ if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 });
107
+
108
+
109
+ },
110
+ },
111
+ "CustomerOrder": {
112
+ checkAndFix(context, mutation, results) {
113
+ const now = context.getResource("fixTime");
114
+ if ((mutation.action === "Create" && mutation.payload["customer"] === undefined) || mutation.payload["customer"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("customer") });
115
+
116
+ if ((mutation.action === "Create" && mutation.payload["status"] === undefined) || mutation.payload["status"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("status") });
117
+
118
+ if ((mutation.action === "Create" && mutation.payload["order_number"] === undefined) || mutation.payload["order_number"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("order_number") });
119
+ if (mutation.payload["order_number"] != null && [...String(mutation.payload["order_number"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("order_number"), inputValue: mutation.payload["order_number"], systemValue: 100 });
120
+
121
+ if ((mutation.action === "Create" && mutation.payload["order_date"] === undefined) || mutation.payload["order_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("order_date") });
122
+
123
+ if ((mutation.action === "Create" && mutation.payload["total_amount"] === undefined) || mutation.payload["total_amount"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("total_amount") });
124
+
125
+
126
+ },
127
+ },
128
+ "OrderItem": {
129
+ checkAndFix(context, mutation, results) {
130
+ const now = context.getResource("fixTime");
131
+ if ((mutation.action === "Create" && mutation.payload["customer_order"] === undefined) || mutation.payload["customer_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("customer_order") });
132
+
133
+ if ((mutation.action === "Create" && mutation.payload["product_name"] === undefined) || mutation.payload["product_name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("product_name") });
134
+ if (mutation.payload["product_name"] != null && [...String(mutation.payload["product_name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("product_name"), inputValue: mutation.payload["product_name"], systemValue: 100 });
135
+
136
+ if ((mutation.action === "Create" && mutation.payload["quantity"] === undefined) || mutation.payload["quantity"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("quantity") });
137
+
138
+ if ((mutation.action === "Create" && mutation.payload["unit_price"] === undefined) || mutation.payload["unit_price"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("unit_price") });
139
+
140
+
141
+ },
142
+ }
143
+ }, { ...{
144
+ defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Commerce Test Platform" } },
145
+ constants: [
146
+ { entity: "OrderStatus", id: "1001", values: { "platform": "1", "name": "New", "code": "NEW", "color": "#94A3B8", "displayOrder": 1 } },
147
+ { entity: "OrderStatus", id: "1002", values: { "platform": "1", "name": "Paid", "code": "PAID", "color": "#22C55E", "displayOrder": 2 } },
148
+ { entity: "OrderStatus", id: "1003", values: { "platform": "1", "name": "Cancelled", "code": "CANCELLED", "color": "#EF4444", "displayOrder": 3 } }
149
+ ]
150
+ }, ensure: ensureGeneratedBootstrap });
source/browser-sqlite/orders-lib/src/teaql-schemas.ts ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntitySchema } from "teaql-ts/sql/core";
2
+
3
+ export const ENTITY_SCHEMAS: Record<string, EntitySchema> = {
4
+ "Platform": {
5
+ table: "platform_data",
6
+ auditMaskFields: [],
7
+ columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
8
+ relations: {"orderStatusList": { targetEntity: "OrderStatus", localKey: "id", foreignKey: "platform", many: true }, "customerList": { targetEntity: "Customer", localKey: "id", foreignKey: "platform", many: true }}
9
+ },
10
+ "OrderStatus": {
11
+ table: "order_status_data",
12
+ auditMaskFields: [],
13
+ columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "color": { columnName: "color", modelName: "color", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
14
+ relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "status", many: true }}
15
+ },
16
+ "Customer": {
17
+ table: "customer_data",
18
+ auditMaskFields: [],
19
+ columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
20
+ relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "customer", many: true }}
21
+ },
22
+ "CustomerOrder": {
23
+ table: "customer_order_data",
24
+ auditMaskFields: [],
25
+ columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customer": { columnName: "customer", modelName: "customer", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "status": { columnName: "status", modelName: "status", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "orderNumber": { columnName: "order_number", modelName: "order_number", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "orderDate": { columnName: "order_date", modelName: "order_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "totalAmount": { columnName: "total_amount", modelName: "total_amount", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
26
+ relations: {"customer": { targetEntity: "Customer", localKey: "customer", foreignKey: "id", many: false }, "status": { targetEntity: "OrderStatus", localKey: "status", foreignKey: "id", many: false }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "customerOrder", many: true }}
27
+ },
28
+ "OrderItem": {
29
+ table: "order_item_data",
30
+ auditMaskFields: [],
31
+ columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customerOrder": { columnName: "customer_order", modelName: "customer_order", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "productName": { columnName: "product_name", modelName: "product_name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "quantity": { columnName: "quantity", modelName: "quantity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "unitPrice": { columnName: "unit_price", modelName: "unit_price", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }},
32
+ relations: {"customerOrder": { targetEntity: "CustomerOrder", localKey: "customerOrder", foreignKey: "id", many: false }}
33
+ }
34
+ };
source/browser-sqlite/orders-lib/src/teaql-ts.ts ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ CheckException, EntityChecker, RuntimeModule,
3
+ SelectQuery as RuntimeSelectQuery, UserContext,
4
+ executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession,
5
+ } from "teaql-ts";
6
+
7
+ export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts";
8
+ export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts";
9
+ export type { EntityKey } from "teaql-ts";
10
+ export type { TeaQLPage } from "teaql-ts";
11
+ import type { QueryOperation } from "teaql-ts";
12
+
13
+ function soundex(input: unknown): string {
14
+ const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, "");
15
+ if (!text) return "";
16
+ const code = (char: string): string => "BFPV".includes(char) ? "1"
17
+ : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3"
18
+ : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : "";
19
+ let result = text[0], previous = code(text[0]);
20
+ for (const char of text.slice(1)) {
21
+ const current = code(char);
22
+ if (current && current !== previous) result += current;
23
+ previous = current;
24
+ if (result.length === 4) break;
25
+ }
26
+ return (result + "000").slice(0, 4);
27
+ }
28
+
29
+ /** Generated naming adapter; query policy and execution remain in the formal runtime. */
30
+ export class SelectQuery extends RuntimeSelectQuery {
31
+ orderBy(field: string, direction: string): this {
32
+ return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any);
33
+ }
34
+
35
+ relationQuery(
36
+ name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true,
37
+ operation?: QueryOperation,
38
+ ): this {
39
+ return super.relationQuery(name, query, localKey, foreignKey, many, operation);
40
+ }
41
+ }
42
+
43
+ export interface TeaQLDataService {
44
+ executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>): Promise<T>;
45
+ preflightMutation(mutation: any): any;
46
+ afterGraphCommit(work: () => void): void;
47
+ afterGraphRollback(work: () => void): void;
48
+ executeMutation(mutation: any): Promise<any>;
49
+ executeQuery(query: any): Promise<any[]>;
50
+ executeCount(query: any, alias?: string, operation?: QueryOperation): Promise<number>;
51
+ executeForStream(query: any, chunkSize?: number): AsyncIterable<any[]>;
52
+ close?(): Promise<void>;
53
+ }
54
+
55
+ export class TeaQLClient implements TeaQLDataService {
56
+ private data: Record<string, Record<string, any>> = {};
57
+ private nextIds: Record<string, number> = {};
58
+ private readonly checkers: Record<string, EntityChecker> = {};
59
+ private userContext = new UserContext();
60
+ private graphSaveActive = false;
61
+ private graphCommitActions: Array<() => void> = [];
62
+ private graphRollbackActions: Array<() => void> = [];
63
+ private graphSaveTail: Promise<void> = Promise.resolve();
64
+ private readonly mutationGovernanceEvents: any[] = [];
65
+
66
+ constructor(private storagePath?: string) {
67
+ if (storagePath) {
68
+ const fs = require("fs");
69
+ if (fs.existsSync(storagePath)) {
70
+ const state = JSON.parse(fs.readFileSync(storagePath, "utf8"));
71
+ this.data = state.data || {};
72
+ this.nextIds = state.nextIds || {};
73
+ }
74
+ }
75
+ }
76
+
77
+ /** Installs passive generated metadata. It never mutates storage. */
78
+ install(module: RuntimeModule): this {
79
+ Object.assign(this.checkers, module.checkers);
80
+ return this;
81
+ }
82
+
83
+ setUserContext(context: UserContext): this {
84
+ this.userContext = context;
85
+ return this;
86
+ }
87
+
88
+ get mutationGovernanceTrace(): readonly any[] {
89
+ return [...this.mutationGovernanceEvents];
90
+ }
91
+
92
+ private persist() {
93
+ if (!this.storagePath) return;
94
+ const fs = require("fs");
95
+ const path = require("path");
96
+ fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true });
97
+ const temporaryPath = `${this.storagePath}.tmp`;
98
+ fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds }));
99
+ fs.renameSync(temporaryPath, this.storagePath);
100
+ }
101
+
102
+ async executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>): Promise<T> {
103
+ const graph = new GraphMutationSession(intent);
104
+ const predecessor = this.graphSaveTail;
105
+ let release!: () => void;
106
+ this.graphSaveTail = new Promise<void>(resolve => { release = resolve; });
107
+ await predecessor;
108
+ const dataSnapshot = JSON.parse(JSON.stringify(this.data));
109
+ const nextIdsSnapshot = { ...this.nextIds };
110
+ let fixEvidenceStarted = false;
111
+ let mutationPolicyGraphStarted = false;
112
+ try {
113
+ this.graphSaveActive = true;
114
+ this.graphCommitActions = [];
115
+ this.graphRollbackActions = [];
116
+ this.userContext.insertResource("fixTime", new Date());
117
+ this.userContext.beginFixEvidence();
118
+ fixEvidenceStarted = true;
119
+ this.userContext.beginMutationPolicyGraph();
120
+ mutationPolicyGraphStarted = true;
121
+ const result = await work(graph);
122
+ this.userContext.ensureMutationPolicyGraphComplete();
123
+ this.persist();
124
+ for (const action of this.graphCommitActions) action();
125
+ return result;
126
+ } catch (error) {
127
+ this.data = dataSnapshot;
128
+ this.nextIds = nextIdsSnapshot;
129
+ for (const action of [...this.graphRollbackActions].reverse()) action();
130
+ throw error;
131
+ } finally {
132
+ this.graphSaveActive = false;
133
+ this.graphCommitActions = [];
134
+ this.graphRollbackActions = [];
135
+ if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph();
136
+ this.userContext.removeResource("fixTime");
137
+ if (fixEvidenceStarted) this.userContext.finishFixEvidence();
138
+ release();
139
+ }
140
+ }
141
+
142
+ afterGraphCommit(work: () => void): void {
143
+ if (!this.graphSaveActive) throw new Error("No graph save is active");
144
+ this.graphCommitActions.push(work);
145
+ }
146
+
147
+ afterGraphRollback(work: () => void): void {
148
+ if (!this.graphSaveActive) throw new Error("No graph save is active");
149
+ this.graphRollbackActions.push(work);
150
+ }
151
+
152
+ preflightMutation(mutation: any): any {
153
+ mutation = this.checkAndFixMutation(mutation);
154
+ this.userContext.recordMutationPolicyPreflight(mutation);
155
+ return mutation;
156
+ }
157
+
158
+ private checkAndFixMutation(mutation: any): any {
159
+ if (mutation instanceof MutationRequest) mutation = mutation.mutation;
160
+ if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation");
161
+ mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } };
162
+ const checker = this.checkers[String(mutation.entity)];
163
+ if (!checker) return mutation;
164
+ const results: any[] = [];
165
+ const ownsFixTime = this.userContext.getResource("fixTime") === undefined;
166
+ if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence();
167
+ try {
168
+ checker.checkAndFix(this.userContext, mutation, results);
169
+ if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value);
170
+ this.userContext.translateCheckResults(results);
171
+ if (results.length) throw new CheckException(results);
172
+ return mutation;
173
+ } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); }
174
+ }
175
+
176
+ async executeMutation(mutation: any): Promise<any> {
177
+ mutation = this.checkAndFixMutation(mutation);
178
+ const mutationGovernance = this.userContext.enterMutationPolicy(mutation);
179
+ this.mutationGovernanceEvents.push(mutationGovernance);
180
+ const table = this.data[mutation.entity] ||= {};
181
+ if (mutation.action === "Create") {
182
+ const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1);
183
+ this.nextIds[mutation.entity] = Number(id) + 1;
184
+ const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 };
185
+ table[String(id)] = record;
186
+ if (!this.graphSaveActive) this.persist();
187
+ return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } };
188
+ }
189
+ if (mutation.action === "Update") {
190
+ const id = String(mutation.id);
191
+ if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`);
192
+ const expectedVersion = Number(mutation.version);
193
+ const currentVersion = Number(table[id].version || 0);
194
+ if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) {
195
+ throw new Error(
196
+ `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`);
197
+ }
198
+ table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 };
199
+ if (!this.graphSaveActive) this.persist();
200
+ return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } };
201
+ }
202
+ if (mutation.action === "Delete") {
203
+ const id = String(mutation.id);
204
+ if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`);
205
+ const expectedVersion = Number(mutation.version);
206
+ const currentVersion = Number(table[id].version || 0);
207
+ if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) {
208
+ throw new Error(
209
+ `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`);
210
+ }
211
+ table[id] = { ...table[id], id, version: -(currentVersion + 1) };
212
+ if (!this.graphSaveActive) this.persist();
213
+ return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } };
214
+ }
215
+ throw new Error(`Unsupported mutation action: ${mutation.action}`);
216
+ }
217
+ async query(context: any, req: any): Promise<any> {
218
+ return { rows: [] };
219
+ }
220
+ async executeQuery(query: any): Promise<any> {
221
+ if (!(query instanceof RuntimeSelectQuery)) {
222
+ throw new Error("TeaQL list execution requires the formal runtime SelectQuery");
223
+ }
224
+ query.prepareForList();
225
+ let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row }));
226
+ const matches = (row: any, expression: any): boolean => {
227
+ if (expression?.$and) return expression.$and.every((item: any) => matches(row, item));
228
+ return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => {
229
+ if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq);
230
+ if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne);
231
+ if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains));
232
+ if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains));
233
+ if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith));
234
+ if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith));
235
+ if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith));
236
+ if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith));
237
+ if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike);
238
+ if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value));
239
+ if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value));
240
+ if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1];
241
+ if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined;
242
+ if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined;
243
+ if (predicate?.$gt !== undefined) return row[field] > predicate.$gt;
244
+ if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte;
245
+ if (predicate?.$lt !== undefined) return row[field] < predicate.$lt;
246
+ if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte;
247
+ return true;
248
+ });
249
+ };
250
+ if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition));
251
+ if (query.aggregateItems?.length) {
252
+ return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => {
253
+ if (String(aggregate.function).toLowerCase() !== "count") {
254
+ throw new Error(`Unsupported local aggregate: ${aggregate.function}`);
255
+ }
256
+ return [aggregate.alias, rows.length];
257
+ }))];
258
+ }
259
+ for (const order of [...query.orderItems].reverse()) {
260
+ rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1));
261
+ }
262
+ const start = query.offsetValue || 0;
263
+ rows = rows.slice(start, start + query.limitValue);
264
+ for (const relation of (query.relations || []) as any[]) {
265
+ const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"]));
266
+ const relatedRows = (await this.executeQuery(relation.query)).filter(
267
+ (row: any) => localValues.has(row[relation.foreignKey || "id"]));
268
+ for (const row of rows) {
269
+ const matches = relatedRows.filter(
270
+ (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]);
271
+ row[relation.name] = relation.many === false ? matches[0] : matches;
272
+ }
273
+ }
274
+ if (query.selectItems.length > 0) {
275
+ const selections = new Set(query.selectItems);
276
+ for (const relation of (query.relations || []) as any[]) selections.add(relation.name);
277
+ rows = rows.map((row: any) => Object.fromEntries(
278
+ Object.entries(row).filter(([field]) => selections.has(field))));
279
+ }
280
+ return rows;
281
+ }
282
+ async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise<number> {
283
+ if (typeof query?.forExactCount !== "function") {
284
+ throw new Error("TeaQL exact count requires the formal runtime SelectQuery");
285
+ }
286
+ const alias = countAlias ?? "__teaql_total";
287
+ const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? {
288
+ kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) });
289
+ const rows = await this.executeQuery(request.query);
290
+ const value = rows[0]?.[alias];
291
+ if (typeof value !== "number" || !Number.isFinite(value)) {
292
+ throw new Error(`TeaQL provider did not return exact count alias ${alias}`);
293
+ }
294
+ return value;
295
+ }
296
+ async *executeForStream(query: any, chunkSize = 1000): AsyncIterable<any[]> {
297
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer");
298
+ const rows = await this.executeQuery(query);
299
+ for (let offset = 0; offset < rows.length; offset += chunkSize) {
300
+ yield rows.slice(offset, offset + chunkSize);
301
+ }
302
+ }
303
+ }
304
+
305
+ declare const require: any;
306
+
307
+ export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; }
308
+ export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; }
source/browser-sqlite/orders-lib/teaql-i18n.json ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "teaql.i18n/v1",
3
+ "defaultLocale": "en",
4
+ "locales": {
5
+ "de": {
6
+ "vocabulary": {
7
+ },
8
+ "messages": {
9
+ }
10
+ },
11
+ "ko": {
12
+ "vocabulary": {
13
+ },
14
+ "messages": {
15
+ }
16
+ },
17
+ "pt": {
18
+ "vocabulary": {
19
+ },
20
+ "messages": {
21
+ }
22
+ },
23
+ "zh-TW": {
24
+ "vocabulary": {
25
+ },
26
+ "messages": {
27
+ }
28
+ },
29
+ "fil": {
30
+ "vocabulary": {
31
+ },
32
+ "messages": {
33
+ }
34
+ },
35
+ "en": {
36
+ "vocabulary": {
37
+ "property.platform.name": "Name",
38
+ "property.customerOrder.orderNumber": "Order Number",
39
+ "property.orderItem.id": "Id",
40
+ "entity.orderItem": "Order Item",
41
+ "property.orderItem.customerOrder": "Customer Order",
42
+ "property.orderStatus.version": "Version",
43
+ "property.orderItem.unitPrice": "Unit Price",
44
+ "property.orderItem.productName": "Product Name",
45
+ "property.orderStatus.code": "Code",
46
+ "property.customerOrder.orderDate": "Order Date",
47
+ "entity.customerOrder": "Customer Order",
48
+ "property.orderStatus.displayOrder": "Display Order",
49
+ "entity.customer": "Customer",
50
+ "property.customerOrder.id": "Id",
51
+ "property.orderStatus.color": "Color",
52
+ "property.customerOrder.totalAmount": "Total Amount",
53
+ "property.customerOrder.version": "Version",
54
+ "entity.platform": "Platform",
55
+ "property.platform.id": "Id",
56
+ "property.customer.version": "Version",
57
+ "property.orderStatus.id": "Id",
58
+ "property.customer.id": "Id",
59
+ "property.customer.platform": "Platform",
60
+ "entity.orderStatus": "Order Status",
61
+ "property.customerOrder.customer": "Customer",
62
+ "property.customer.name": "Name",
63
+ "property.orderItem.version": "Version",
64
+ "property.orderStatus.platform": "Platform",
65
+ "property.orderStatus.name": "Name",
66
+ "property.platform.version": "Version",
67
+ "property.customerOrder.status": "Status",
68
+ "property.orderItem.quantity": "Quantity"
69
+ },
70
+ "messages": {
71
+ }
72
+ },
73
+ "fr": {
74
+ "vocabulary": {
75
+ },
76
+ "messages": {
77
+ }
78
+ },
79
+ "zh-CN": {
80
+ "vocabulary": {
81
+ },
82
+ "messages": {
83
+ }
84
+ },
85
+ "es": {
86
+ "vocabulary": {
87
+ },
88
+ "messages": {
89
+ }
90
+ },
91
+ "ar": {
92
+ "vocabulary": {
93
+ },
94
+ "messages": {
95
+ }
96
+ },
97
+ "vi": {
98
+ "vocabulary": {
99
+ },
100
+ "messages": {
101
+ }
102
+ },
103
+ "th": {
104
+ "vocabulary": {
105
+ },
106
+ "messages": {
107
+ }
108
+ },
109
+ "uk": {
110
+ "vocabulary": {
111
+ },
112
+ "messages": {
113
+ }
114
+ },
115
+ "ja": {
116
+ "vocabulary": {
117
+ },
118
+ "messages": {
119
+ }
120
+ },
121
+ "id": {
122
+ "vocabulary": {
123
+ },
124
+ "messages": {
125
+ }
126
+ }
127
+ }
128
+ }
source/browser-sqlite/orders-lib/tsconfig.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2022",
4
+ "module": "commonjs",
5
+ "strict": true,
6
+ "esModuleInterop": true,
7
+ "skipLibCheck": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "declaration": true
10
+ },
11
+ "include": ["src/**/*", "*.d.ts"]
12
+ }
source/browser-sqlite/package-lock.json ADDED
@@ -0,0 +1,1624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "teaql-browser-sqlite-example",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "teaql-browser-sqlite-example",
9
+ "version": "1.0.0",
10
+ "dependencies": {
11
+ "@sqlite.org/sqlite-wasm": "3.53.0-build1",
12
+ "teaql-ts": "file:vendor/teaql-teaql-0.3.0.tgz"
13
+ },
14
+ "devDependencies": {
15
+ "puppeteer-core": "25.10.0",
16
+ "typescript": "5.9.2",
17
+ "vite": "^7.3.6"
18
+ }
19
+ },
20
+ "node_modules/@esbuild/aix-ppc64": {
21
+ "version": "0.28.2",
22
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
23
+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
24
+ "cpu": [
25
+ "ppc64"
26
+ ],
27
+ "dev": true,
28
+ "license": "MIT",
29
+ "optional": true,
30
+ "os": [
31
+ "aix"
32
+ ],
33
+ "engines": {
34
+ "node": ">=18"
35
+ }
36
+ },
37
+ "node_modules/@esbuild/android-arm": {
38
+ "version": "0.28.2",
39
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
40
+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
41
+ "cpu": [
42
+ "arm"
43
+ ],
44
+ "dev": true,
45
+ "license": "MIT",
46
+ "optional": true,
47
+ "os": [
48
+ "android"
49
+ ],
50
+ "engines": {
51
+ "node": ">=18"
52
+ }
53
+ },
54
+ "node_modules/@esbuild/android-arm64": {
55
+ "version": "0.28.2",
56
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
57
+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
58
+ "cpu": [
59
+ "arm64"
60
+ ],
61
+ "dev": true,
62
+ "license": "MIT",
63
+ "optional": true,
64
+ "os": [
65
+ "android"
66
+ ],
67
+ "engines": {
68
+ "node": ">=18"
69
+ }
70
+ },
71
+ "node_modules/@esbuild/android-x64": {
72
+ "version": "0.28.2",
73
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
74
+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
75
+ "cpu": [
76
+ "x64"
77
+ ],
78
+ "dev": true,
79
+ "license": "MIT",
80
+ "optional": true,
81
+ "os": [
82
+ "android"
83
+ ],
84
+ "engines": {
85
+ "node": ">=18"
86
+ }
87
+ },
88
+ "node_modules/@esbuild/darwin-arm64": {
89
+ "version": "0.28.2",
90
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
91
+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
92
+ "cpu": [
93
+ "arm64"
94
+ ],
95
+ "dev": true,
96
+ "license": "MIT",
97
+ "optional": true,
98
+ "os": [
99
+ "darwin"
100
+ ],
101
+ "engines": {
102
+ "node": ">=18"
103
+ }
104
+ },
105
+ "node_modules/@esbuild/darwin-x64": {
106
+ "version": "0.28.2",
107
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
108
+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
109
+ "cpu": [
110
+ "x64"
111
+ ],
112
+ "dev": true,
113
+ "license": "MIT",
114
+ "optional": true,
115
+ "os": [
116
+ "darwin"
117
+ ],
118
+ "engines": {
119
+ "node": ">=18"
120
+ }
121
+ },
122
+ "node_modules/@esbuild/freebsd-arm64": {
123
+ "version": "0.28.2",
124
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
125
+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
126
+ "cpu": [
127
+ "arm64"
128
+ ],
129
+ "dev": true,
130
+ "license": "MIT",
131
+ "optional": true,
132
+ "os": [
133
+ "freebsd"
134
+ ],
135
+ "engines": {
136
+ "node": ">=18"
137
+ }
138
+ },
139
+ "node_modules/@esbuild/freebsd-x64": {
140
+ "version": "0.28.2",
141
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
142
+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
143
+ "cpu": [
144
+ "x64"
145
+ ],
146
+ "dev": true,
147
+ "license": "MIT",
148
+ "optional": true,
149
+ "os": [
150
+ "freebsd"
151
+ ],
152
+ "engines": {
153
+ "node": ">=18"
154
+ }
155
+ },
156
+ "node_modules/@esbuild/linux-arm": {
157
+ "version": "0.28.2",
158
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
159
+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
160
+ "cpu": [
161
+ "arm"
162
+ ],
163
+ "dev": true,
164
+ "license": "MIT",
165
+ "optional": true,
166
+ "os": [
167
+ "linux"
168
+ ],
169
+ "engines": {
170
+ "node": ">=18"
171
+ }
172
+ },
173
+ "node_modules/@esbuild/linux-arm64": {
174
+ "version": "0.28.2",
175
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
176
+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
177
+ "cpu": [
178
+ "arm64"
179
+ ],
180
+ "dev": true,
181
+ "license": "MIT",
182
+ "optional": true,
183
+ "os": [
184
+ "linux"
185
+ ],
186
+ "engines": {
187
+ "node": ">=18"
188
+ }
189
+ },
190
+ "node_modules/@esbuild/linux-ia32": {
191
+ "version": "0.28.2",
192
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
193
+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
194
+ "cpu": [
195
+ "ia32"
196
+ ],
197
+ "dev": true,
198
+ "license": "MIT",
199
+ "optional": true,
200
+ "os": [
201
+ "linux"
202
+ ],
203
+ "engines": {
204
+ "node": ">=18"
205
+ }
206
+ },
207
+ "node_modules/@esbuild/linux-loong64": {
208
+ "version": "0.28.2",
209
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
210
+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
211
+ "cpu": [
212
+ "loong64"
213
+ ],
214
+ "dev": true,
215
+ "license": "MIT",
216
+ "optional": true,
217
+ "os": [
218
+ "linux"
219
+ ],
220
+ "engines": {
221
+ "node": ">=18"
222
+ }
223
+ },
224
+ "node_modules/@esbuild/linux-mips64el": {
225
+ "version": "0.28.2",
226
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
227
+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
228
+ "cpu": [
229
+ "mips64el"
230
+ ],
231
+ "dev": true,
232
+ "license": "MIT",
233
+ "optional": true,
234
+ "os": [
235
+ "linux"
236
+ ],
237
+ "engines": {
238
+ "node": ">=18"
239
+ }
240
+ },
241
+ "node_modules/@esbuild/linux-ppc64": {
242
+ "version": "0.28.2",
243
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
244
+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
245
+ "cpu": [
246
+ "ppc64"
247
+ ],
248
+ "dev": true,
249
+ "license": "MIT",
250
+ "optional": true,
251
+ "os": [
252
+ "linux"
253
+ ],
254
+ "engines": {
255
+ "node": ">=18"
256
+ }
257
+ },
258
+ "node_modules/@esbuild/linux-riscv64": {
259
+ "version": "0.28.2",
260
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
261
+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
262
+ "cpu": [
263
+ "riscv64"
264
+ ],
265
+ "dev": true,
266
+ "license": "MIT",
267
+ "optional": true,
268
+ "os": [
269
+ "linux"
270
+ ],
271
+ "engines": {
272
+ "node": ">=18"
273
+ }
274
+ },
275
+ "node_modules/@esbuild/linux-s390x": {
276
+ "version": "0.28.2",
277
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
278
+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
279
+ "cpu": [
280
+ "s390x"
281
+ ],
282
+ "dev": true,
283
+ "license": "MIT",
284
+ "optional": true,
285
+ "os": [
286
+ "linux"
287
+ ],
288
+ "engines": {
289
+ "node": ">=18"
290
+ }
291
+ },
292
+ "node_modules/@esbuild/linux-x64": {
293
+ "version": "0.28.2",
294
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
295
+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
296
+ "cpu": [
297
+ "x64"
298
+ ],
299
+ "dev": true,
300
+ "license": "MIT",
301
+ "optional": true,
302
+ "os": [
303
+ "linux"
304
+ ],
305
+ "engines": {
306
+ "node": ">=18"
307
+ }
308
+ },
309
+ "node_modules/@esbuild/netbsd-arm64": {
310
+ "version": "0.28.2",
311
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
312
+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
313
+ "cpu": [
314
+ "arm64"
315
+ ],
316
+ "dev": true,
317
+ "license": "MIT",
318
+ "optional": true,
319
+ "os": [
320
+ "netbsd"
321
+ ],
322
+ "engines": {
323
+ "node": ">=18"
324
+ }
325
+ },
326
+ "node_modules/@esbuild/netbsd-x64": {
327
+ "version": "0.28.2",
328
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
329
+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
330
+ "cpu": [
331
+ "x64"
332
+ ],
333
+ "dev": true,
334
+ "license": "MIT",
335
+ "optional": true,
336
+ "os": [
337
+ "netbsd"
338
+ ],
339
+ "engines": {
340
+ "node": ">=18"
341
+ }
342
+ },
343
+ "node_modules/@esbuild/openbsd-arm64": {
344
+ "version": "0.28.2",
345
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
346
+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
347
+ "cpu": [
348
+ "arm64"
349
+ ],
350
+ "dev": true,
351
+ "license": "MIT",
352
+ "optional": true,
353
+ "os": [
354
+ "openbsd"
355
+ ],
356
+ "engines": {
357
+ "node": ">=18"
358
+ }
359
+ },
360
+ "node_modules/@esbuild/openbsd-x64": {
361
+ "version": "0.28.2",
362
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
363
+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
364
+ "cpu": [
365
+ "x64"
366
+ ],
367
+ "dev": true,
368
+ "license": "MIT",
369
+ "optional": true,
370
+ "os": [
371
+ "openbsd"
372
+ ],
373
+ "engines": {
374
+ "node": ">=18"
375
+ }
376
+ },
377
+ "node_modules/@esbuild/openharmony-arm64": {
378
+ "version": "0.28.2",
379
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
380
+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
381
+ "cpu": [
382
+ "arm64"
383
+ ],
384
+ "dev": true,
385
+ "license": "MIT",
386
+ "optional": true,
387
+ "os": [
388
+ "openharmony"
389
+ ],
390
+ "engines": {
391
+ "node": ">=18"
392
+ }
393
+ },
394
+ "node_modules/@esbuild/sunos-x64": {
395
+ "version": "0.28.2",
396
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
397
+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
398
+ "cpu": [
399
+ "x64"
400
+ ],
401
+ "dev": true,
402
+ "license": "MIT",
403
+ "optional": true,
404
+ "os": [
405
+ "sunos"
406
+ ],
407
+ "engines": {
408
+ "node": ">=18"
409
+ }
410
+ },
411
+ "node_modules/@esbuild/win32-arm64": {
412
+ "version": "0.28.2",
413
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
414
+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
415
+ "cpu": [
416
+ "arm64"
417
+ ],
418
+ "dev": true,
419
+ "license": "MIT",
420
+ "optional": true,
421
+ "os": [
422
+ "win32"
423
+ ],
424
+ "engines": {
425
+ "node": ">=18"
426
+ }
427
+ },
428
+ "node_modules/@esbuild/win32-ia32": {
429
+ "version": "0.28.2",
430
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
431
+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
432
+ "cpu": [
433
+ "ia32"
434
+ ],
435
+ "dev": true,
436
+ "license": "MIT",
437
+ "optional": true,
438
+ "os": [
439
+ "win32"
440
+ ],
441
+ "engines": {
442
+ "node": ">=18"
443
+ }
444
+ },
445
+ "node_modules/@esbuild/win32-x64": {
446
+ "version": "0.28.2",
447
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
448
+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
449
+ "cpu": [
450
+ "x64"
451
+ ],
452
+ "dev": true,
453
+ "license": "MIT",
454
+ "optional": true,
455
+ "os": [
456
+ "win32"
457
+ ],
458
+ "engines": {
459
+ "node": ">=18"
460
+ }
461
+ },
462
+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {
463
+ "version": "1.5.1",
464
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
465
+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",
466
+ "cpu": [
467
+ "x64"
468
+ ],
469
+ "dev": true,
470
+ "libc": [
471
+ "glibc"
472
+ ],
473
+ "license": "MIT",
474
+ "optional": true,
475
+ "os": [
476
+ "linux"
477
+ ],
478
+ "engines": {
479
+ "node": "^22.20 || ^24.12 || >=25"
480
+ }
481
+ },
482
+ "node_modules/@puppeteer/browsers": {
483
+ "version": "3.2.2",
484
+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.2.tgz",
485
+ "integrity": "sha512-q2BU4YfO9h/Wt7IcWPcggpOOqLk2Tbs1hDwolvKZrweRjy751OJBKMN9zO5bfD0pzU7X/tvKw/exQds4pM/LOg==",
486
+ "dev": true,
487
+ "license": "Apache-2.0",
488
+ "dependencies": {
489
+ "modern-tar": "^0.8.4",
490
+ "yargs": "^18.0.0"
491
+ },
492
+ "bin": {
493
+ "browsers": "lib/main-cli.js"
494
+ },
495
+ "engines": {
496
+ "node": ">=22.12.0"
497
+ },
498
+ "peerDependencies": {
499
+ "proxy-agent": ">=8.0.1",
500
+ "yauzl": "^2.10.0 || ^3.4.0"
501
+ },
502
+ "peerDependenciesMeta": {
503
+ "proxy-agent": {
504
+ "optional": true
505
+ },
506
+ "yauzl": {
507
+ "optional": true
508
+ }
509
+ }
510
+ },
511
+ "node_modules/@rollup/rollup-android-arm-eabi": {
512
+ "version": "4.63.1",
513
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz",
514
+ "integrity": "sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ==",
515
+ "cpu": [
516
+ "arm"
517
+ ],
518
+ "dev": true,
519
+ "license": "MIT",
520
+ "optional": true,
521
+ "os": [
522
+ "android"
523
+ ]
524
+ },
525
+ "node_modules/@rollup/rollup-android-arm64": {
526
+ "version": "4.63.1",
527
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.1.tgz",
528
+ "integrity": "sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ==",
529
+ "cpu": [
530
+ "arm64"
531
+ ],
532
+ "dev": true,
533
+ "license": "MIT",
534
+ "optional": true,
535
+ "os": [
536
+ "android"
537
+ ]
538
+ },
539
+ "node_modules/@rollup/rollup-darwin-arm64": {
540
+ "version": "4.63.1",
541
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.1.tgz",
542
+ "integrity": "sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q==",
543
+ "cpu": [
544
+ "arm64"
545
+ ],
546
+ "dev": true,
547
+ "license": "MIT",
548
+ "optional": true,
549
+ "os": [
550
+ "darwin"
551
+ ]
552
+ },
553
+ "node_modules/@rollup/rollup-darwin-x64": {
554
+ "version": "4.63.1",
555
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.1.tgz",
556
+ "integrity": "sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg==",
557
+ "cpu": [
558
+ "x64"
559
+ ],
560
+ "dev": true,
561
+ "license": "MIT",
562
+ "optional": true,
563
+ "os": [
564
+ "darwin"
565
+ ]
566
+ },
567
+ "node_modules/@rollup/rollup-freebsd-arm64": {
568
+ "version": "4.63.1",
569
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.1.tgz",
570
+ "integrity": "sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw==",
571
+ "cpu": [
572
+ "arm64"
573
+ ],
574
+ "dev": true,
575
+ "license": "MIT",
576
+ "optional": true,
577
+ "os": [
578
+ "freebsd"
579
+ ]
580
+ },
581
+ "node_modules/@rollup/rollup-freebsd-x64": {
582
+ "version": "4.63.1",
583
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.1.tgz",
584
+ "integrity": "sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q==",
585
+ "cpu": [
586
+ "x64"
587
+ ],
588
+ "dev": true,
589
+ "license": "MIT",
590
+ "optional": true,
591
+ "os": [
592
+ "freebsd"
593
+ ]
594
+ },
595
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
596
+ "version": "4.63.1",
597
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.1.tgz",
598
+ "integrity": "sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw==",
599
+ "cpu": [
600
+ "arm"
601
+ ],
602
+ "dev": true,
603
+ "libc": [
604
+ "glibc"
605
+ ],
606
+ "license": "MIT",
607
+ "optional": true,
608
+ "os": [
609
+ "linux"
610
+ ]
611
+ },
612
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
613
+ "version": "4.63.1",
614
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.1.tgz",
615
+ "integrity": "sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw==",
616
+ "cpu": [
617
+ "arm"
618
+ ],
619
+ "dev": true,
620
+ "libc": [
621
+ "musl"
622
+ ],
623
+ "license": "MIT",
624
+ "optional": true,
625
+ "os": [
626
+ "linux"
627
+ ]
628
+ },
629
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
630
+ "version": "4.63.1",
631
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.1.tgz",
632
+ "integrity": "sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg==",
633
+ "cpu": [
634
+ "arm64"
635
+ ],
636
+ "dev": true,
637
+ "libc": [
638
+ "glibc"
639
+ ],
640
+ "license": "MIT",
641
+ "optional": true,
642
+ "os": [
643
+ "linux"
644
+ ]
645
+ },
646
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
647
+ "version": "4.63.1",
648
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.1.tgz",
649
+ "integrity": "sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw==",
650
+ "cpu": [
651
+ "arm64"
652
+ ],
653
+ "dev": true,
654
+ "libc": [
655
+ "musl"
656
+ ],
657
+ "license": "MIT",
658
+ "optional": true,
659
+ "os": [
660
+ "linux"
661
+ ]
662
+ },
663
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
664
+ "version": "4.63.1",
665
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.1.tgz",
666
+ "integrity": "sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ==",
667
+ "cpu": [
668
+ "loong64"
669
+ ],
670
+ "dev": true,
671
+ "libc": [
672
+ "glibc"
673
+ ],
674
+ "license": "MIT",
675
+ "optional": true,
676
+ "os": [
677
+ "linux"
678
+ ]
679
+ },
680
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
681
+ "version": "4.63.1",
682
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.1.tgz",
683
+ "integrity": "sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA==",
684
+ "cpu": [
685
+ "loong64"
686
+ ],
687
+ "dev": true,
688
+ "libc": [
689
+ "musl"
690
+ ],
691
+ "license": "MIT",
692
+ "optional": true,
693
+ "os": [
694
+ "linux"
695
+ ]
696
+ },
697
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
698
+ "version": "4.63.1",
699
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.1.tgz",
700
+ "integrity": "sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA==",
701
+ "cpu": [
702
+ "ppc64"
703
+ ],
704
+ "dev": true,
705
+ "libc": [
706
+ "glibc"
707
+ ],
708
+ "license": "MIT",
709
+ "optional": true,
710
+ "os": [
711
+ "linux"
712
+ ]
713
+ },
714
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
715
+ "version": "4.63.1",
716
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.1.tgz",
717
+ "integrity": "sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA==",
718
+ "cpu": [
719
+ "ppc64"
720
+ ],
721
+ "dev": true,
722
+ "libc": [
723
+ "musl"
724
+ ],
725
+ "license": "MIT",
726
+ "optional": true,
727
+ "os": [
728
+ "linux"
729
+ ]
730
+ },
731
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
732
+ "version": "4.63.1",
733
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.1.tgz",
734
+ "integrity": "sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w==",
735
+ "cpu": [
736
+ "riscv64"
737
+ ],
738
+ "dev": true,
739
+ "libc": [
740
+ "glibc"
741
+ ],
742
+ "license": "MIT",
743
+ "optional": true,
744
+ "os": [
745
+ "linux"
746
+ ]
747
+ },
748
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
749
+ "version": "4.63.1",
750
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.1.tgz",
751
+ "integrity": "sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ==",
752
+ "cpu": [
753
+ "riscv64"
754
+ ],
755
+ "dev": true,
756
+ "libc": [
757
+ "musl"
758
+ ],
759
+ "license": "MIT",
760
+ "optional": true,
761
+ "os": [
762
+ "linux"
763
+ ]
764
+ },
765
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
766
+ "version": "4.63.1",
767
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.1.tgz",
768
+ "integrity": "sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A==",
769
+ "cpu": [
770
+ "s390x"
771
+ ],
772
+ "dev": true,
773
+ "libc": [
774
+ "glibc"
775
+ ],
776
+ "license": "MIT",
777
+ "optional": true,
778
+ "os": [
779
+ "linux"
780
+ ]
781
+ },
782
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
783
+ "version": "4.63.1",
784
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.1.tgz",
785
+ "integrity": "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w==",
786
+ "cpu": [
787
+ "x64"
788
+ ],
789
+ "dev": true,
790
+ "libc": [
791
+ "glibc"
792
+ ],
793
+ "license": "MIT",
794
+ "optional": true,
795
+ "os": [
796
+ "linux"
797
+ ]
798
+ },
799
+ "node_modules/@rollup/rollup-linux-x64-musl": {
800
+ "version": "4.63.1",
801
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.1.tgz",
802
+ "integrity": "sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow==",
803
+ "cpu": [
804
+ "x64"
805
+ ],
806
+ "dev": true,
807
+ "libc": [
808
+ "musl"
809
+ ],
810
+ "license": "MIT",
811
+ "optional": true,
812
+ "os": [
813
+ "linux"
814
+ ]
815
+ },
816
+ "node_modules/@rollup/rollup-openbsd-x64": {
817
+ "version": "4.63.1",
818
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.1.tgz",
819
+ "integrity": "sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA==",
820
+ "cpu": [
821
+ "x64"
822
+ ],
823
+ "dev": true,
824
+ "license": "MIT",
825
+ "optional": true,
826
+ "os": [
827
+ "openbsd"
828
+ ]
829
+ },
830
+ "node_modules/@rollup/rollup-openharmony-arm64": {
831
+ "version": "4.63.1",
832
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.1.tgz",
833
+ "integrity": "sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw==",
834
+ "cpu": [
835
+ "arm64"
836
+ ],
837
+ "dev": true,
838
+ "license": "MIT",
839
+ "optional": true,
840
+ "os": [
841
+ "openharmony"
842
+ ]
843
+ },
844
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
845
+ "version": "4.63.1",
846
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.1.tgz",
847
+ "integrity": "sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg==",
848
+ "cpu": [
849
+ "arm64"
850
+ ],
851
+ "dev": true,
852
+ "license": "MIT",
853
+ "optional": true,
854
+ "os": [
855
+ "win32"
856
+ ]
857
+ },
858
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
859
+ "version": "4.63.1",
860
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.1.tgz",
861
+ "integrity": "sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg==",
862
+ "cpu": [
863
+ "ia32"
864
+ ],
865
+ "dev": true,
866
+ "license": "MIT",
867
+ "optional": true,
868
+ "os": [
869
+ "win32"
870
+ ]
871
+ },
872
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
873
+ "version": "4.63.1",
874
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.1.tgz",
875
+ "integrity": "sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg==",
876
+ "cpu": [
877
+ "x64"
878
+ ],
879
+ "dev": true,
880
+ "license": "MIT",
881
+ "optional": true,
882
+ "os": [
883
+ "win32"
884
+ ]
885
+ },
886
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
887
+ "version": "4.63.1",
888
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.1.tgz",
889
+ "integrity": "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w==",
890
+ "cpu": [
891
+ "x64"
892
+ ],
893
+ "dev": true,
894
+ "license": "MIT",
895
+ "optional": true,
896
+ "os": [
897
+ "win32"
898
+ ]
899
+ },
900
+ "node_modules/@sqlite.org/sqlite-wasm": {
901
+ "version": "3.53.0-build1",
902
+ "resolved": "https://registry.npmjs.org/@sqlite.org/sqlite-wasm/-/sqlite-wasm-3.53.0-build1.tgz",
903
+ "integrity": "sha512-PfWPWN2n+/37doa8oh2/oUXk4OOsRYZsxc1W1sDXIGb/Pu5Yrb+f2eyYpgQMGITVX7HVgxhs9P18Rc6I97ym/g==",
904
+ "license": "Apache-2.0",
905
+ "workspaces": [
906
+ "demos/*"
907
+ ],
908
+ "engines": {
909
+ "node": ">=22"
910
+ }
911
+ },
912
+ "node_modules/@types/estree": {
913
+ "version": "1.0.9",
914
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
915
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
916
+ "dev": true,
917
+ "license": "MIT"
918
+ },
919
+ "node_modules/ansi-regex": {
920
+ "version": "6.3.0",
921
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz",
922
+ "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==",
923
+ "dev": true,
924
+ "license": "MIT",
925
+ "engines": {
926
+ "node": ">=12"
927
+ },
928
+ "funding": {
929
+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"
930
+ }
931
+ },
932
+ "node_modules/ansi-styles": {
933
+ "version": "6.2.3",
934
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
935
+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
936
+ "dev": true,
937
+ "license": "MIT",
938
+ "engines": {
939
+ "node": ">=12"
940
+ },
941
+ "funding": {
942
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
943
+ }
944
+ },
945
+ "node_modules/chromium-bidi": {
946
+ "version": "17.0.2",
947
+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",
948
+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",
949
+ "dev": true,
950
+ "license": "Apache-2.0",
951
+ "dependencies": {
952
+ "mitt": "^3.0.1",
953
+ "zod": "^3.24.1"
954
+ },
955
+ "engines": {
956
+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"
957
+ },
958
+ "peerDependencies": {
959
+ "devtools-protocol": "*"
960
+ }
961
+ },
962
+ "node_modules/cliui": {
963
+ "version": "9.0.1",
964
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",
965
+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",
966
+ "dev": true,
967
+ "license": "ISC",
968
+ "dependencies": {
969
+ "string-width": "^7.2.0",
970
+ "strip-ansi": "^7.1.0",
971
+ "wrap-ansi": "^9.0.0"
972
+ },
973
+ "engines": {
974
+ "node": ">=20"
975
+ }
976
+ },
977
+ "node_modules/cliui/node_modules/string-width": {
978
+ "version": "7.2.0",
979
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
980
+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
981
+ "dev": true,
982
+ "license": "MIT",
983
+ "dependencies": {
984
+ "emoji-regex": "^10.3.0",
985
+ "get-east-asian-width": "^1.0.0",
986
+ "strip-ansi": "^7.1.0"
987
+ },
988
+ "engines": {
989
+ "node": ">=18"
990
+ },
991
+ "funding": {
992
+ "url": "https://github.com/sponsors/sindresorhus"
993
+ }
994
+ },
995
+ "node_modules/devtools-protocol": {
996
+ "version": "0.0.1666840",
997
+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1666840.tgz",
998
+ "integrity": "sha512-gCcO42XCHKEs7Ag0S7aGYsnJ7hlgrO3qderYqeiY0Eqk+0GFfuvT13IA0hHreJTa2KCdDVyGMeOhdMNmrrTjVg==",
999
+ "dev": true,
1000
+ "license": "BSD-3-Clause"
1001
+ },
1002
+ "node_modules/emoji-regex": {
1003
+ "version": "10.6.0",
1004
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
1005
+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
1006
+ "dev": true,
1007
+ "license": "MIT"
1008
+ },
1009
+ "node_modules/esbuild": {
1010
+ "version": "0.28.2",
1011
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
1012
+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
1013
+ "dev": true,
1014
+ "hasInstallScript": true,
1015
+ "license": "MIT",
1016
+ "bin": {
1017
+ "esbuild": "bin/esbuild"
1018
+ },
1019
+ "engines": {
1020
+ "node": ">=18"
1021
+ },
1022
+ "optionalDependencies": {
1023
+ "@esbuild/aix-ppc64": "0.28.2",
1024
+ "@esbuild/android-arm": "0.28.2",
1025
+ "@esbuild/android-arm64": "0.28.2",
1026
+ "@esbuild/android-x64": "0.28.2",
1027
+ "@esbuild/darwin-arm64": "0.28.2",
1028
+ "@esbuild/darwin-x64": "0.28.2",
1029
+ "@esbuild/freebsd-arm64": "0.28.2",
1030
+ "@esbuild/freebsd-x64": "0.28.2",
1031
+ "@esbuild/linux-arm": "0.28.2",
1032
+ "@esbuild/linux-arm64": "0.28.2",
1033
+ "@esbuild/linux-ia32": "0.28.2",
1034
+ "@esbuild/linux-loong64": "0.28.2",
1035
+ "@esbuild/linux-mips64el": "0.28.2",
1036
+ "@esbuild/linux-ppc64": "0.28.2",
1037
+ "@esbuild/linux-riscv64": "0.28.2",
1038
+ "@esbuild/linux-s390x": "0.28.2",
1039
+ "@esbuild/linux-x64": "0.28.2",
1040
+ "@esbuild/netbsd-arm64": "0.28.2",
1041
+ "@esbuild/netbsd-x64": "0.28.2",
1042
+ "@esbuild/openbsd-arm64": "0.28.2",
1043
+ "@esbuild/openbsd-x64": "0.28.2",
1044
+ "@esbuild/openharmony-arm64": "0.28.2",
1045
+ "@esbuild/sunos-x64": "0.28.2",
1046
+ "@esbuild/win32-arm64": "0.28.2",
1047
+ "@esbuild/win32-ia32": "0.28.2",
1048
+ "@esbuild/win32-x64": "0.28.2"
1049
+ }
1050
+ },
1051
+ "node_modules/escalade": {
1052
+ "version": "3.2.0",
1053
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
1054
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
1055
+ "dev": true,
1056
+ "license": "MIT",
1057
+ "engines": {
1058
+ "node": ">=6"
1059
+ }
1060
+ },
1061
+ "node_modules/fdir": {
1062
+ "version": "6.5.0",
1063
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
1064
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
1065
+ "dev": true,
1066
+ "license": "MIT",
1067
+ "engines": {
1068
+ "node": ">=12.0.0"
1069
+ },
1070
+ "peerDependencies": {
1071
+ "picomatch": "^3 || ^4"
1072
+ },
1073
+ "peerDependenciesMeta": {
1074
+ "picomatch": {
1075
+ "optional": true
1076
+ }
1077
+ }
1078
+ },
1079
+ "node_modules/fsevents": {
1080
+ "version": "2.3.3",
1081
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
1082
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
1083
+ "dev": true,
1084
+ "hasInstallScript": true,
1085
+ "license": "MIT",
1086
+ "optional": true,
1087
+ "os": [
1088
+ "darwin"
1089
+ ],
1090
+ "engines": {
1091
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
1092
+ }
1093
+ },
1094
+ "node_modules/get-caller-file": {
1095
+ "version": "2.0.5",
1096
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
1097
+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
1098
+ "dev": true,
1099
+ "license": "ISC",
1100
+ "engines": {
1101
+ "node": "6.* || 8.* || >= 10.*"
1102
+ }
1103
+ },
1104
+ "node_modules/get-east-asian-width": {
1105
+ "version": "1.6.0",
1106
+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",
1107
+ "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==",
1108
+ "dev": true,
1109
+ "license": "MIT",
1110
+ "engines": {
1111
+ "node": ">=18"
1112
+ },
1113
+ "funding": {
1114
+ "url": "https://github.com/sponsors/sindresorhus"
1115
+ }
1116
+ },
1117
+ "node_modules/mitt": {
1118
+ "version": "3.0.1",
1119
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
1120
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
1121
+ "dev": true,
1122
+ "license": "MIT"
1123
+ },
1124
+ "node_modules/modern-tar": {
1125
+ "version": "0.8.4",
1126
+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.4.tgz",
1127
+ "integrity": "sha512-gN54ddmyzEg10orwZ2u4OOv+bjpMWdIl5jIkodK97bMq8QBSL5c0D7YX0lT1Ooz+99S7+PvFbnxzdjgHo1r41g==",
1128
+ "dev": true,
1129
+ "license": "MIT",
1130
+ "engines": {
1131
+ "node": ">=18.0.0"
1132
+ }
1133
+ },
1134
+ "node_modules/nanoid": {
1135
+ "version": "3.3.18",
1136
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
1137
+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
1138
+ "dev": true,
1139
+ "funding": [
1140
+ {
1141
+ "type": "github",
1142
+ "url": "https://github.com/sponsors/ai"
1143
+ }
1144
+ ],
1145
+ "license": "MIT",
1146
+ "bin": {
1147
+ "nanoid": "bin/nanoid.cjs"
1148
+ },
1149
+ "engines": {
1150
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
1151
+ }
1152
+ },
1153
+ "node_modules/node-fetch": {
1154
+ "version": "2.7.0",
1155
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
1156
+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
1157
+ "license": "MIT",
1158
+ "dependencies": {
1159
+ "whatwg-url": "^5.0.0"
1160
+ },
1161
+ "engines": {
1162
+ "node": "4.x || >=6.0.0"
1163
+ },
1164
+ "peerDependencies": {
1165
+ "encoding": "^0.1.0"
1166
+ },
1167
+ "peerDependenciesMeta": {
1168
+ "encoding": {
1169
+ "optional": true
1170
+ }
1171
+ }
1172
+ },
1173
+ "node_modules/picocolors": {
1174
+ "version": "1.1.1",
1175
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
1176
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
1177
+ "dev": true,
1178
+ "license": "ISC"
1179
+ },
1180
+ "node_modules/picomatch": {
1181
+ "version": "4.0.7",
1182
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
1183
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
1184
+ "dev": true,
1185
+ "license": "MIT",
1186
+ "engines": {
1187
+ "node": ">=12"
1188
+ },
1189
+ "funding": {
1190
+ "url": "https://github.com/sponsors/jonschlinkert"
1191
+ }
1192
+ },
1193
+ "node_modules/postcss": {
1194
+ "version": "8.5.28",
1195
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
1196
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
1197
+ "dev": true,
1198
+ "funding": [
1199
+ {
1200
+ "type": "opencollective",
1201
+ "url": "https://opencollective.com/postcss/"
1202
+ },
1203
+ {
1204
+ "type": "tidelift",
1205
+ "url": "https://tidelift.com/funding/github/npm/postcss"
1206
+ },
1207
+ {
1208
+ "type": "github",
1209
+ "url": "https://github.com/sponsors/ai"
1210
+ }
1211
+ ],
1212
+ "license": "MIT",
1213
+ "dependencies": {
1214
+ "nanoid": "^3.3.18",
1215
+ "picocolors": "^1.1.1",
1216
+ "source-map-js": "^1.2.1"
1217
+ },
1218
+ "engines": {
1219
+ "node": "^10 || ^12 || >=14"
1220
+ }
1221
+ },
1222
+ "node_modules/puppeteer-core": {
1223
+ "version": "25.10.0",
1224
+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.10.0.tgz",
1225
+ "integrity": "sha512-Hy5eMQshOEMil4JUUx03h5pw1HYkYCso1RG/gcpPlFSd4cYPOcopxcXEAxpLPOkOPJb9LIJtwxuj66bSdvknFg==",
1226
+ "dev": true,
1227
+ "license": "Apache-2.0",
1228
+ "dependencies": {
1229
+ "@puppeteer/browsers": "3.2.2",
1230
+ "chromium-bidi": "17.0.2",
1231
+ "devtools-protocol": "0.0.1666840",
1232
+ "typed-query-selector": "^2.12.2",
1233
+ "webdriver-bidi-protocol": "0.4.3",
1234
+ "ws": "^8.21.3"
1235
+ },
1236
+ "engines": {
1237
+ "node": ">=22.12.0"
1238
+ }
1239
+ },
1240
+ "node_modules/rollup": {
1241
+ "version": "4.63.1",
1242
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz",
1243
+ "integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==",
1244
+ "dev": true,
1245
+ "license": "MIT",
1246
+ "dependencies": {
1247
+ "@types/estree": "1.0.9"
1248
+ },
1249
+ "bin": {
1250
+ "rollup": "dist/bin/rollup"
1251
+ },
1252
+ "engines": {
1253
+ "node": ">=18.0.0",
1254
+ "npm": ">=8.0.0"
1255
+ },
1256
+ "optionalDependencies": {
1257
+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",
1258
+ "@rollup/rollup-android-arm-eabi": "4.63.1",
1259
+ "@rollup/rollup-android-arm64": "4.63.1",
1260
+ "@rollup/rollup-darwin-arm64": "4.63.1",
1261
+ "@rollup/rollup-darwin-x64": "4.63.1",
1262
+ "@rollup/rollup-freebsd-arm64": "4.63.1",
1263
+ "@rollup/rollup-freebsd-x64": "4.63.1",
1264
+ "@rollup/rollup-linux-arm-gnueabihf": "4.63.1",
1265
+ "@rollup/rollup-linux-arm-musleabihf": "4.63.1",
1266
+ "@rollup/rollup-linux-arm64-gnu": "4.63.1",
1267
+ "@rollup/rollup-linux-arm64-musl": "4.63.1",
1268
+ "@rollup/rollup-linux-loong64-gnu": "4.63.1",
1269
+ "@rollup/rollup-linux-loong64-musl": "4.63.1",
1270
+ "@rollup/rollup-linux-ppc64-gnu": "4.63.1",
1271
+ "@rollup/rollup-linux-ppc64-musl": "4.63.1",
1272
+ "@rollup/rollup-linux-riscv64-gnu": "4.63.1",
1273
+ "@rollup/rollup-linux-riscv64-musl": "4.63.1",
1274
+ "@rollup/rollup-linux-s390x-gnu": "4.63.1",
1275
+ "@rollup/rollup-linux-x64-gnu": "4.63.1",
1276
+ "@rollup/rollup-linux-x64-musl": "4.63.1",
1277
+ "@rollup/rollup-openbsd-x64": "4.63.1",
1278
+ "@rollup/rollup-openharmony-arm64": "4.63.1",
1279
+ "@rollup/rollup-win32-arm64-msvc": "4.63.1",
1280
+ "@rollup/rollup-win32-ia32-msvc": "4.63.1",
1281
+ "@rollup/rollup-win32-x64-gnu": "4.63.1",
1282
+ "@rollup/rollup-win32-x64-msvc": "4.63.1",
1283
+ "fsevents": "~2.3.2"
1284
+ }
1285
+ },
1286
+ "node_modules/source-map-js": {
1287
+ "version": "1.2.1",
1288
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
1289
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
1290
+ "dev": true,
1291
+ "license": "BSD-3-Clause",
1292
+ "engines": {
1293
+ "node": ">=0.10.0"
1294
+ }
1295
+ },
1296
+ "node_modules/string-width": {
1297
+ "version": "8.2.2",
1298
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.2.tgz",
1299
+ "integrity": "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==",
1300
+ "dev": true,
1301
+ "license": "MIT",
1302
+ "dependencies": {
1303
+ "get-east-asian-width": "^1.5.0",
1304
+ "strip-ansi": "^7.1.2"
1305
+ },
1306
+ "engines": {
1307
+ "node": ">=20"
1308
+ },
1309
+ "funding": {
1310
+ "url": "https://github.com/sponsors/sindresorhus"
1311
+ }
1312
+ },
1313
+ "node_modules/strip-ansi": {
1314
+ "version": "7.2.0",
1315
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
1316
+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
1317
+ "dev": true,
1318
+ "license": "MIT",
1319
+ "dependencies": {
1320
+ "ansi-regex": "^6.2.2"
1321
+ },
1322
+ "engines": {
1323
+ "node": ">=12"
1324
+ },
1325
+ "funding": {
1326
+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"
1327
+ }
1328
+ },
1329
+ "node_modules/teaql-ts": {
1330
+ "name": "@teaql/teaql",
1331
+ "version": "0.3.0",
1332
+ "resolved": "file:vendor/teaql-teaql-0.3.0.tgz",
1333
+ "integrity": "sha512-au422aLCU34kwRxBu4rjqbiMCxpStQzTBek73/dUKw+SbJVMDNoo/VqkcgI8C4leKEF5p4ozH+QosGuSp+PIWw==",
1334
+ "license": "Apache-2.0",
1335
+ "dependencies": {
1336
+ "node-fetch": "^2.7.0"
1337
+ },
1338
+ "peerDependencies": {
1339
+ "@opentelemetry/api": "^1.9.1",
1340
+ "@opentelemetry/api-logs": "^0.221.0",
1341
+ "@sqlite.org/sqlite-wasm": "3.53.0-build1",
1342
+ "better-sqlite3": "^12.10.0",
1343
+ "expo-sqlite": "*",
1344
+ "mysql2": "^3.11.0",
1345
+ "pg": "^8.12.0",
1346
+ "pg-query-stream": "^4.7.0"
1347
+ },
1348
+ "peerDependenciesMeta": {
1349
+ "@opentelemetry/api": {
1350
+ "optional": true
1351
+ },
1352
+ "@opentelemetry/api-logs": {
1353
+ "optional": true
1354
+ },
1355
+ "@sqlite.org/sqlite-wasm": {
1356
+ "optional": true
1357
+ },
1358
+ "better-sqlite3": {
1359
+ "optional": true
1360
+ },
1361
+ "expo-sqlite": {
1362
+ "optional": true
1363
+ },
1364
+ "mysql2": {
1365
+ "optional": true
1366
+ },
1367
+ "pg": {
1368
+ "optional": true
1369
+ },
1370
+ "pg-query-stream": {
1371
+ "optional": true
1372
+ }
1373
+ }
1374
+ },
1375
+ "node_modules/tinyglobby": {
1376
+ "version": "0.2.17",
1377
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
1378
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
1379
+ "dev": true,
1380
+ "license": "MIT",
1381
+ "dependencies": {
1382
+ "fdir": "^6.5.0",
1383
+ "picomatch": "^4.0.4"
1384
+ },
1385
+ "engines": {
1386
+ "node": ">=12.0.0"
1387
+ },
1388
+ "funding": {
1389
+ "url": "https://github.com/sponsors/SuperchupuDev"
1390
+ }
1391
+ },
1392
+ "node_modules/tr46": {
1393
+ "version": "0.0.3",
1394
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
1395
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
1396
+ "license": "MIT"
1397
+ },
1398
+ "node_modules/typed-query-selector": {
1399
+ "version": "2.12.2",
1400
+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",
1401
+ "integrity": "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==",
1402
+ "dev": true,
1403
+ "license": "MIT"
1404
+ },
1405
+ "node_modules/typescript": {
1406
+ "version": "5.9.2",
1407
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz",
1408
+ "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
1409
+ "dev": true,
1410
+ "license": "Apache-2.0",
1411
+ "bin": {
1412
+ "tsc": "bin/tsc",
1413
+ "tsserver": "bin/tsserver"
1414
+ },
1415
+ "engines": {
1416
+ "node": ">=14.17"
1417
+ }
1418
+ },
1419
+ "node_modules/vite": {
1420
+ "version": "7.3.6",
1421
+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",
1422
+ "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",
1423
+ "dev": true,
1424
+ "license": "MIT",
1425
+ "dependencies": {
1426
+ "esbuild": "^0.27.0 || ^0.28.0",
1427
+ "fdir": "^6.5.0",
1428
+ "picomatch": "^4.0.3",
1429
+ "postcss": "^8.5.6",
1430
+ "rollup": "^4.43.0",
1431
+ "tinyglobby": "^0.2.15"
1432
+ },
1433
+ "bin": {
1434
+ "vite": "bin/vite.js"
1435
+ },
1436
+ "engines": {
1437
+ "node": "^20.19.0 || >=22.12.0"
1438
+ },
1439
+ "funding": {
1440
+ "url": "https://github.com/vitejs/vite?sponsor=1"
1441
+ },
1442
+ "optionalDependencies": {
1443
+ "fsevents": "~2.3.3"
1444
+ },
1445
+ "peerDependencies": {
1446
+ "@types/node": "^20.19.0 || >=22.12.0",
1447
+ "jiti": ">=1.21.0",
1448
+ "less": "^4.0.0",
1449
+ "lightningcss": "^1.21.0",
1450
+ "sass": "^1.70.0",
1451
+ "sass-embedded": "^1.70.0",
1452
+ "stylus": ">=0.54.8",
1453
+ "sugarss": "^5.0.0",
1454
+ "terser": "^5.16.0",
1455
+ "tsx": "^4.8.1",
1456
+ "yaml": "^2.4.2"
1457
+ },
1458
+ "peerDependenciesMeta": {
1459
+ "@types/node": {
1460
+ "optional": true
1461
+ },
1462
+ "jiti": {
1463
+ "optional": true
1464
+ },
1465
+ "less": {
1466
+ "optional": true
1467
+ },
1468
+ "lightningcss": {
1469
+ "optional": true
1470
+ },
1471
+ "sass": {
1472
+ "optional": true
1473
+ },
1474
+ "sass-embedded": {
1475
+ "optional": true
1476
+ },
1477
+ "stylus": {
1478
+ "optional": true
1479
+ },
1480
+ "sugarss": {
1481
+ "optional": true
1482
+ },
1483
+ "terser": {
1484
+ "optional": true
1485
+ },
1486
+ "tsx": {
1487
+ "optional": true
1488
+ },
1489
+ "yaml": {
1490
+ "optional": true
1491
+ }
1492
+ }
1493
+ },
1494
+ "node_modules/webdriver-bidi-protocol": {
1495
+ "version": "0.4.3",
1496
+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",
1497
+ "integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",
1498
+ "dev": true,
1499
+ "license": "Apache-2.0"
1500
+ },
1501
+ "node_modules/webidl-conversions": {
1502
+ "version": "3.0.1",
1503
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
1504
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
1505
+ "license": "BSD-2-Clause"
1506
+ },
1507
+ "node_modules/whatwg-url": {
1508
+ "version": "5.0.0",
1509
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
1510
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
1511
+ "license": "MIT",
1512
+ "dependencies": {
1513
+ "tr46": "~0.0.3",
1514
+ "webidl-conversions": "^3.0.0"
1515
+ }
1516
+ },
1517
+ "node_modules/wrap-ansi": {
1518
+ "version": "9.0.2",
1519
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
1520
+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
1521
+ "dev": true,
1522
+ "license": "MIT",
1523
+ "dependencies": {
1524
+ "ansi-styles": "^6.2.1",
1525
+ "string-width": "^7.0.0",
1526
+ "strip-ansi": "^7.1.0"
1527
+ },
1528
+ "engines": {
1529
+ "node": ">=18"
1530
+ },
1531
+ "funding": {
1532
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
1533
+ }
1534
+ },
1535
+ "node_modules/wrap-ansi/node_modules/string-width": {
1536
+ "version": "7.2.0",
1537
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
1538
+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
1539
+ "dev": true,
1540
+ "license": "MIT",
1541
+ "dependencies": {
1542
+ "emoji-regex": "^10.3.0",
1543
+ "get-east-asian-width": "^1.0.0",
1544
+ "strip-ansi": "^7.1.0"
1545
+ },
1546
+ "engines": {
1547
+ "node": ">=18"
1548
+ },
1549
+ "funding": {
1550
+ "url": "https://github.com/sponsors/sindresorhus"
1551
+ }
1552
+ },
1553
+ "node_modules/ws": {
1554
+ "version": "8.21.3",
1555
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
1556
+ "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
1557
+ "dev": true,
1558
+ "license": "MIT",
1559
+ "engines": {
1560
+ "node": ">=10.0.0"
1561
+ },
1562
+ "peerDependencies": {
1563
+ "bufferutil": "^4.0.1",
1564
+ "utf-8-validate": ">=5.0.2"
1565
+ },
1566
+ "peerDependenciesMeta": {
1567
+ "bufferutil": {
1568
+ "optional": true
1569
+ },
1570
+ "utf-8-validate": {
1571
+ "optional": true
1572
+ }
1573
+ }
1574
+ },
1575
+ "node_modules/y18n": {
1576
+ "version": "5.0.8",
1577
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
1578
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
1579
+ "dev": true,
1580
+ "license": "ISC",
1581
+ "engines": {
1582
+ "node": ">=10"
1583
+ }
1584
+ },
1585
+ "node_modules/yargs": {
1586
+ "version": "18.1.0",
1587
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.1.0.tgz",
1588
+ "integrity": "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==",
1589
+ "dev": true,
1590
+ "license": "MIT",
1591
+ "dependencies": {
1592
+ "cliui": "^9.0.1",
1593
+ "escalade": "^3.1.1",
1594
+ "get-caller-file": "^2.0.5",
1595
+ "string-width": "^8.2.1",
1596
+ "y18n": "^5.0.5",
1597
+ "yargs-parser": "^22.0.0"
1598
+ },
1599
+ "engines": {
1600
+ "node": "^20.19.0 || ^22.12.0 || >=23"
1601
+ }
1602
+ },
1603
+ "node_modules/yargs-parser": {
1604
+ "version": "22.0.0",
1605
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
1606
+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
1607
+ "dev": true,
1608
+ "license": "ISC",
1609
+ "engines": {
1610
+ "node": "^20.19.0 || ^22.12.0 || >=23"
1611
+ }
1612
+ },
1613
+ "node_modules/zod": {
1614
+ "version": "3.25.76",
1615
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
1616
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
1617
+ "dev": true,
1618
+ "license": "MIT",
1619
+ "funding": {
1620
+ "url": "https://github.com/sponsors/colinhacks"
1621
+ }
1622
+ }
1623
+ }
1624
+ }
source/browser-sqlite/package.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "teaql-browser-sqlite-example",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "tsc --noEmit && vite build",
9
+ "smoke": "node scripts/smoke.mjs"
10
+ },
11
+ "dependencies": {
12
+ "@sqlite.org/sqlite-wasm": "3.53.0-build1",
13
+ "teaql-ts": "file:vendor/teaql-teaql-0.3.0.tgz"
14
+ },
15
+ "devDependencies": {
16
+ "puppeteer-core": "25.10.0",
17
+ "typescript": "5.9.2",
18
+ "vite": "^7.3.6"
19
+ }
20
+ }
source/browser-sqlite/scripts/smoke.mjs ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {spawn} from 'node:child_process';
2
+ import {readFileSync, writeFileSync} from 'node:fs';
3
+ import {createHash} from 'node:crypto';
4
+ import {join} from 'node:path';
5
+ import assert from 'node:assert/strict';
6
+ import puppeteer from 'puppeteer-core';
7
+
8
+ const generated = JSON.parse(readFileSync('generated-order-hashes.json', 'utf8'));
9
+ function checkLibrary() {
10
+ for (const [file, expected] of Object.entries(generated))
11
+ assert.equal(createHash('sha256').update(readFileSync(join('orders-lib', file))).digest('hex'), expected, `generated file changed: ${file}`);
12
+ }
13
+ checkLibrary();
14
+ const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', 'preview', '--host', '127.0.0.1', '--port', '4175', '--strictPort'],
15
+ {stdio: ['ignore', 'pipe', 'pipe']});
16
+ let serverOutput = '';
17
+ server.stdout.on('data', value => { serverOutput += value; }); server.stderr.on('data', value => { serverOutput += value; });
18
+ let browser;
19
+ const receipts = [];
20
+ try {
21
+ let ready = false;
22
+ for (let attempt = 0; attempt < 100; attempt++) {
23
+ try { ready = (await fetch('http://127.0.0.1:4175/')).ok; } catch { /* starting */ }
24
+ if (ready) break;
25
+ await new Promise(resolve => setTimeout(resolve, 100));
26
+ }
27
+ assert.ok(ready, serverOutput);
28
+ browser = await puppeteer.launch({executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome',
29
+ args: ['--no-sandbox', '--disable-dev-shm-usage'], headless: true});
30
+ const page = await browser.newPage(), errors = [];
31
+ page.on('pageerror', error => errors.push(error.message));
32
+ page.on('console', event => { if (event.type() === 'error') errors.push(event.text()); });
33
+ page.on('response', response => { if (response.status() >= 400) errors.push(`${response.status()} ${response.url()}`); });
34
+ page.on('requestfailed', request => errors.push(`${request.failure()?.errorText} ${request.url()}`));
35
+ async function waitReady(storage) {
36
+ try {
37
+ await page.waitForFunction(value => {
38
+ const text = document.querySelector('#status')?.textContent || '';
39
+ return text.startsWith(value) && text.includes('ready');
40
+ }, {timeout: 20_000}, storage);
41
+ } catch (error) {
42
+ throw new Error(`${error.message}; status=${await page.$eval('#status', element => element.textContent)}; browserErrors=${errors.join('\n')}`);
43
+ }
44
+ }
45
+ async function inspect(label, diagnostics) {
46
+ const response = JSON.parse(await page.$eval('#result', element => element.textContent));
47
+ assert.equal(response.metadata.totalCount, 3); assert.equal(response.metadata.aggregations.totalOrders, 3);
48
+ assert.equal(response.metadata.pageOffset, 1); assert.equal(response.metadata.pageSize, 1);
49
+ assert.equal(response.resultCode, 0); assert.equal(response.status, 'YES');
50
+ assert.equal(response.version, '1.001'); assert.equal(response.recordCount, 3);
51
+ assert.deepEqual(response.metadata.searchWarnings, []);
52
+ assert.equal(response.data.length, 1); const order = response.data[0];
53
+ assert.equal(order.orderNumber, 'KEEP-002'); assert.equal(order.orderDate.slice(0, 10), '2026-10-02');
54
+ assert.equal(order.version, 1); assert.equal(order.status.name, 'Paid'); assert.equal(order.status.color, '#22C55E');
55
+ assert.deepEqual(order.items.map(item => [item.productName, item.quantity]), [['Box 1', 1], ['Box 2', 2], ['Box 3', 3]]);
56
+ assert.equal(order.itemCount, 5);
57
+ assert.deepEqual(response.facets.statusCounts.map(row => [String(row.id), row.orderCount, row.orderTotalAmount]),
58
+ [['1001', 1, 100], ['1002', 2, 500], ['1003', 0, null]]);
59
+ const evidence = JSON.parse(await page.$eval('#sql', element => element.textContent));
60
+ assert.equal(evidence.length, 8);
61
+ const comments = evidence.map(entry => entry.traceChain.filter(node => node.kind === 'comment').map(node => node.detail));
62
+ const expected = [
63
+ ['load order list', "countAs('totalOrders')"], ['load order list'],
64
+ ['load order list', 'selectStatusWith(...)', 'load status'],
65
+ ['load order list', 'selectOrderItemListWith(...)', 'load item previews'],
66
+ ['load order list', "countOrderItemsAs('itemCount')"],
67
+ ['load order list', "facetByStatusAs('statusCounts')", 'aggregate status'],
68
+ ['load order list', "facetByStatusAs('statusCounts')", 'load status facets'],
69
+ ['load order list', "facetByStatusAs('statusCounts')", 'aggregate status'],
70
+ ];
71
+ assert.deepEqual(comments.map(JSON.stringify).sort(), expected.map(JSON.stringify).sort());
72
+ for (const entry of evidence) {
73
+ assert.equal(entry.purpose, 'render order list page');
74
+ assert.ok(entry.tracePath.some(node => node.kind === 'provider'));
75
+ assert.equal(entry.traceChain.filter(node => node.kind === 'purpose').length, 1);
76
+ }
77
+ const text = await page.$eval('#status', element => element.textContent);
78
+ assert.ok(text.includes(`${diagnostics} diagnostics`), text);
79
+ assert.equal(await page.$eval('#trace', element => element.textContent), evidence.map(entry => `${entry.purpose}: ${entry.traceChain
80
+ .filter(node => node.kind === 'comment').map(node => node.detail).join(' → ')}`).join('\n'));
81
+ assert.deepEqual(await page.$$eval('.evidence-table th', cells => cells.map(cell => cell.textContent)),
82
+ ['Time', 'Identity', 'Trace chain', 'SQL']);
83
+ const renderedEvidence = await page.$$eval('#evidence-rows tr', rows => rows.map(row =>
84
+ [...row.querySelectorAll('td')].map(cell => cell.textContent)));
85
+ assert.deepEqual(renderedEvidence, evidence.map(entry => [
86
+ `${entry.elapsedMicros} µs`, entry.tracePath.find(node => node.kind === 'request')?.name ?? '—',
87
+ `${entry.traceChain.find(node => node.kind === 'purpose').detail}: ${entry.traceChain
88
+ .filter(node => node.kind === 'comment').map(node => node.detail).join(' → ')}`, entry.debugSQL,
89
+ ]));
90
+ receipts.push({label, response, evidence, diagnostics, renderedEvidence});
91
+ return response;
92
+ }
93
+ await page.goto('http://127.0.0.1:4175/', {waitUntil: 'networkidle0'});
94
+ await waitReady('MEMORY'); const baseline = await inspect('memory-first', 8);
95
+ await page.select('#example', 'all');
96
+ await page.waitForFunction(() => {
97
+ const text = document.querySelector('#result')?.textContent;
98
+ return text && JSON.parse(text).metadata.totalCount === 4;
99
+ });
100
+ const all = JSON.parse(await page.$eval('#result', element => element.textContent));
101
+ assert.equal(all.data[0].orderNumber, 'KEEP-003');
102
+ assert.deepEqual(all.facets.statusCounts.map(row => [row.orderCount, row.orderTotalAmount]), [[1, 100], [3, 1400], [0, null]]);
103
+ await page.$eval('#search', element => { element.value = 'Q.constructor("return globalThis")'; });
104
+ await page.click('#query');
105
+ await page.waitForFunction(() => document.querySelector('#status')?.textContent?.includes('not allowed'));
106
+ assert.equal(await page.$$eval('#evidence-rows tr', rows => rows.length), 0);
107
+ assert.equal(await page.$eval('#sql', element => element.textContent), '[]');
108
+ await page.click('#preset'); await waitReady('MEMORY');
109
+ assert.deepEqual(await inspect('restored-preset', 8), baseline);
110
+ await page.reload({waitUntil: 'networkidle0'}); await waitReady('MEMORY');
111
+ assert.deepEqual(await inspect('memory-refresh', 8), baseline);
112
+ await page.click('#logging');
113
+ await page.waitForFunction(() => document.querySelector('#status')?.textContent?.includes('0 diagnostics'));
114
+ assert.deepEqual(await inspect('memory-logging-off', 0), baseline);
115
+ await page.click('#reset');
116
+ await page.waitForFunction(() => !document.querySelector('#reset')?.hasAttribute('disabled'));
117
+ assert.deepEqual(await inspect('memory-reset', 0), baseline);
118
+ await page.click('#persist'); await waitReady('OPFS');
119
+ assert.deepEqual(await inspect('opfs-first', 0), baseline);
120
+ await page.reload({waitUntil: 'networkidle0'}); await waitReady('OPFS');
121
+ assert.deepEqual(await inspect('opfs-refresh', 8), baseline);
122
+ await page.click('#reset');
123
+ await page.waitForFunction(() => !document.querySelector('#reset')?.hasAttribute('disabled'));
124
+ assert.deepEqual(await inspect('opfs-reset', 8), baseline);
125
+ assert.deepEqual(errors, []); checkLibrary();
126
+ if (process.env.TEAQL_BROWSER_ORDER_EVIDENCE) writeFileSync(process.env.TEAQL_BROWSER_ORDER_EVIDENCE,
127
+ JSON.stringify({receipts, queryPresetSwitch: true, forbiddenConstructorRejected: true,
128
+ generatedLibraryUnchanged: true, browserErrors: errors}, null, 2) + '\n', {flag: 'wx'});
129
+ console.log('PASS browser generated order TraceChain: memory/OPFS, refresh/reset, logging on/off, exact facets/counts/previews, actual SQL=8, unchanged generated library');
130
+ } finally { await browser?.close(); server.kill('SIGTERM'); }
source/browser-sqlite/src/main.ts ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BrowserSQLiteTeaQLClient, type BrowserSQLiteStorage } from 'teaql-ts/sql/browser-sqlite';
2
+ import { DelegatingMutationPolicyApprovalProvider, DelegatingMutationPolicyRegistry, QueryParser, UserContext } from 'teaql-ts';
3
+ import type { TeaQLPage } from 'teaql-ts';
4
+ import { SQLExecutionEvidenceStore, type SQLExecutionMetadata } from 'teaql-ts/sql/core';
5
+ import { Q } from '../orders-lib/src/generated/Q';
6
+ import { E } from '../orders-lib/src/generated/E';
7
+ import { OrderStatus } from '../orders-lib/src/generated/models/OrderStatus';
8
+ import { GENERATED_RUNTIME_MODULE } from '../orders-lib/src/runtime-module';
9
+ import { ENTITY_SCHEMAS } from '../orders-lib/src/teaql-schemas';
10
+ import { webResponse } from './web-response';
11
+ import './style.css';
12
+
13
+ const status = document.querySelector<HTMLParagraphElement>('#status')!;
14
+ const output = document.querySelector<HTMLPreElement>('#result')!;
15
+ const trace = document.querySelector<HTMLPreElement>('#trace')!;
16
+ const sql = document.querySelector<HTMLPreElement>('#sql')!;
17
+ const evidenceRows = document.querySelector<HTMLTableSectionElement>('#evidence-rows')!;
18
+ const persist = document.querySelector<HTMLInputElement>('#persist')!;
19
+ const logging = document.querySelector<HTMLInputElement>('#logging')!;
20
+ const reset = document.querySelector<HTMLButtonElement>('#reset')!;
21
+ const run = document.querySelector<HTMLButtonElement>('#query')!;
22
+ const search = document.querySelector<HTMLTextAreaElement>('#search')!;
23
+ const example = document.querySelector<HTMLSelectElement>('#example')!;
24
+ const filteredSearch = JSON.stringify(JSON.stringify({filter: {orderNumber: {$contains: 'KEEP'}}}));
25
+ const preset = `Q.customerOrdersWithMinimalFields()
26
+ .filterByJson(${filteredSearch})
27
+ .countAs("totalOrders")
28
+ .facetByStatusAs("statusCounts", Q.orderStatusesWithMinimalFields()
29
+ .selectName().selectColor().countAs("orderCount")
30
+ .sumTotalAmountOfCustomerOrdersAs("orderTotalAmount", Q.customerOrdersWithMinimalFields())
31
+ .orderByDisplayOrderAscending().comment("load status facets"))
32
+ .selectOrderNumber().selectOrderDate()
33
+ .selectStatusWith(Q.orderStatusesWithMinimalFields()
34
+ .selectName().selectColor().comment("load status"))
35
+ .selectOrderItemListWith(Q.orderItemsWithMinimalFields()
36
+ .selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews"))
37
+ .countOrderItemsAs("itemCount")
38
+ .orderByOrderDateDescending().orderByIdDescending()
39
+ .comment("load order list").purpose("render order list page")`;
40
+ search.value = preset;
41
+ type Runtime = {client: BrowserSQLiteTeaQLClient; context: UserContext; evidence: SQLExecutionEvidenceStore; diagnostics: SQLExecutionMetadata[]};
42
+ let active: Runtime | undefined;
43
+ const opfsAvailable = globalThis.crossOriginIsolated && typeof navigator.storage?.getDirectory === 'function';
44
+ persist.checked = opfsAvailable && localStorage.getItem('teaql-browser-order-storage') === 'opfs';
45
+ persist.disabled = !opfsAvailable;
46
+ if (!opfsAvailable) document.querySelector('#opfs-note')!.textContent = '(not available on this host; memory remains fully browser-local)';
47
+
48
+ async function open(storage: BrowserSQLiteStorage): Promise<Runtime> {
49
+ const worker = new Worker(new URL('./sqlite.worker.ts', import.meta.url), {type: 'module'});
50
+ const client = await BrowserSQLiteTeaQLClient.open(worker, {...ENTITY_SCHEMAS}, {
51
+ storage, databaseName: 'teaql-browser-orders.sqlite3',
52
+ });
53
+ client.install(GENERATED_RUNTIME_MODULE);
54
+ client.setDiagnosticSQLLogSink(undefined).setMutationLoggingEnabled(false);
55
+ const identity = Object.freeze({policyId: 'browser-order-seed', version: '1', fingerprint: 'sha256:browser-order-seed-v1'});
56
+ const context = new UserContext().insertResource('dataService', client)
57
+ .withMutationPolicyRegistry(new DelegatingMutationPolicyRegistry(() => ({identity,
58
+ review: (_context, plan) => plan.operations.length > 0 ? {verdict: 'allow'}
59
+ : {verdict: 'deny', code: 'EMPTY_GRAPH', message: 'empty mutation graph'},
60
+ })))
61
+ .withMutationPolicyApprovalProvider(new DelegatingMutationPolicyApprovalProvider(
62
+ policy => ({policy, approvedBy: 'browser-demo-owner', approvedAt: new Date()}),
63
+ ));
64
+ client.setUserContext(context);
65
+ await context.ensureSchema();
66
+ await context.ensureSchema();
67
+ return {client, context, evidence: new SQLExecutionEvidenceStore(), diagnostics: []};
68
+ }
69
+
70
+ async function seed({context}: Runtime): Promise<void> {
71
+ const existing = await Q.customerOrdersWithMinimalFields().limit(1)
72
+ .comment('detect existing order demo').purpose('keep mutation seeding idempotent').executeForList(context);
73
+ if (existing.length) return;
74
+ const platform = (await Q.platforms().limit(2).comment('load bootstrap platform').purpose('prepare order demo').executeForList(context))[0];
75
+ const customer = Q.customers().comment('initialize demo customer').purpose('prepare order demo').newEntity(context);
76
+ customer.updateName('North Star Retail').updatePlatform(platform.id);
77
+ await customer.auditAs('seed browser order customer').save(context);
78
+ for (let index = 1; index <= 4; index++) {
79
+ const order = Q.customerOrders().comment('initialize demo order').purpose('prepare order demo').newEntity(context);
80
+ order.updateCustomer(customer.id).updateOrderNumber(index < 4 ? `KEEP-00${index}` : 'DROP-004')
81
+ .updateOrderDate(`2026-10-0${index}`).updateTotalAmount(index < 4 ? index * 100 : 900);
82
+ if (index === 1) order.updateStatusToNew(); else order.updateStatusToPaid();
83
+ await order.auditAs('seed browser order').save(context);
84
+ for (let item = 1; item <= 5; item++) {
85
+ const line = Q.orderItems().comment('initialize demo item').purpose('prepare item previews').newEntity(context);
86
+ line.updateCustomerOrder(order.id).updateProductName(`Box ${item}`).updateQuantity(item).updateUnitPrice(20);
87
+ await line.auditAs('seed browser order item').save(context);
88
+ }
89
+ }
90
+ }
91
+
92
+ async function show(runtime: Runtime): Promise<void> {
93
+ output.textContent = '';
94
+ trace.textContent = '';
95
+ sql.textContent = '[]';
96
+ evidenceRows.replaceChildren();
97
+ runtime.evidence.enableAll(); runtime.diagnostics.length = 0;
98
+ type Order = NonNullable<Parameters<typeof E.customerOrder>[0]>;
99
+ type Executable = {executeForPage(context: UserContext, offset: number, size: number): Promise<TeaQLPage<Order>>};
100
+ const request = QueryParser.parse(search.value, Q) as Executable & {dynamicSearchWarnings?: readonly unknown[]};
101
+ if (typeof request?.executeForPage !== 'function') throw new Error('The query must contain a generated executable Q request');
102
+ runtime.client.setRuntimeTelemetrySink(runtime.evidence).setQueryLoggingEnabled(logging.checked)
103
+ .setDiagnosticSQLLogSink({write: entry => runtime.diagnostics.push(entry)});
104
+ const page = await request.executeForPage(runtime.context, 1, 1);
105
+ const responseBase = webResponse(page.data);
106
+ const response = {
107
+ resultCode: responseBase.resultCode, status: responseBase.status, version: responseBase.version,
108
+ recordCount: page.totalCount,
109
+ data: page.data.map(row => {
110
+ const expression = E.customerOrder(row);
111
+ const previewSize = expression.orderItemList().size().eval();
112
+ if (previewSize == null) throw new Error('Selected item list unexpectedly has a null size');
113
+ return {id: row.id, version: row.version, orderNumber: expression.orderNumber().eval(), orderDate: expression.orderDate().eval(),
114
+ status: {name: expression.status().name().eval(), color: expression.status().color().eval()},
115
+ items: Array.from({length: previewSize}, (_, index) => ({
116
+ productName: expression.orderItemList().get(index).productName().eval(), quantity: expression.orderItemList().get(index).quantity().eval(),
117
+ })), itemCount: (row as unknown as Record<string, unknown>).itemCount};
118
+ }),
119
+ metadata: {totalCount: page.totalCount, pageOffset: 1, pageSize: 1, aggregations: page.data.aggregations, searchWarnings: request.dynamicSearchWarnings ?? []},
120
+ facets: {statusCounts: page.data.facets.statusCounts.map(value => ({
121
+ id: value.id, name: E.orderStatus(OrderStatus.fromRecord(value)).name().eval(),
122
+ color: E.orderStatus(OrderStatus.fromRecord(value)).color().eval(), orderCount: value.orderCount, orderTotalAmount: value.orderTotalAmount,
123
+ }))},
124
+ };
125
+ output.textContent = JSON.stringify(response, null, 2);
126
+ const statements = runtime.evidence.snapshot();
127
+ // Rendering only: ownership and comments come from the actual runtime metadata.
128
+ const rows = statements.map(entry => {
129
+ const chain = entry.traceChain ?? [];
130
+ const purposes = chain.filter(node => node.kind === 'purpose');
131
+ const businessTrace = purposes.length === 1
132
+ ? `${purposes[0].detail}: ${chain.filter(node => node.kind === 'comment').map(node => node.detail).join(' → ')}`
133
+ : 'TraceChain unavailable';
134
+ const row = document.createElement('tr');
135
+ for (const value of [`${entry.elapsedMicros} µs`,
136
+ entry.tracePath.find(node => node.kind === 'request')?.name ?? '—', businessTrace, entry.debugSQL]) {
137
+ const cell = document.createElement('td');
138
+ cell.textContent = value;
139
+ row.append(cell);
140
+ }
141
+ return {row, businessTrace};
142
+ });
143
+ evidenceRows.replaceChildren(...rows.map(value => value.row));
144
+ trace.textContent = rows.map(value => value.businessTrace).join('\n');
145
+ sql.textContent = JSON.stringify(statements, null, 2);
146
+ status.textContent = `${runtime.client.storage!.toUpperCase()} · ${page.totalCount} matches · ${statements.length} SQL statements · ${runtime.diagnostics.length} diagnostics · policy installed · ready`;
147
+ }
148
+
149
+ async function replace(storage: BrowserSQLiteStorage): Promise<void> {
150
+ status.textContent = `Opening ${storage.toUpperCase()} SQLite/WASM…`;
151
+ const previous = active; active = undefined;
152
+ await previous?.client.close();
153
+ const next = await open(storage); active = next;
154
+ await seed(next); await show(next);
155
+ }
156
+ function fail(value: unknown): void {
157
+ status.textContent = value instanceof Error ? `${value.name}: ${value.message}` : String(value);
158
+ }
159
+ run.addEventListener('click', async () => {
160
+ if (!active) return;
161
+ run.disabled = true;
162
+ try { await show(active); } catch (error) { fail(error); } finally { run.disabled = false; }
163
+ });
164
+ document.querySelector('#preset')!.addEventListener('click', () => {
165
+ search.value = preset; example.value = 'filtered'; run.click();
166
+ });
167
+ example.addEventListener('change', () => {
168
+ search.value = example.value === 'all' ? preset.replace(filteredSearch, JSON.stringify('{}')) : preset;
169
+ run.click();
170
+ });
171
+ search.addEventListener('keydown', event => {
172
+ if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') run.click();
173
+ });
174
+ logging.addEventListener('change', () => { if (active) show(active).catch(fail); });
175
+ persist.addEventListener('change', () => {
176
+ const storage = persist.checked ? 'opfs' : 'memory';
177
+ localStorage.setItem('teaql-browser-order-storage', storage); replace(storage).catch(fail);
178
+ });
179
+ reset.addEventListener('click', async () => {
180
+ if (!active) return;
181
+ reset.disabled = true;
182
+ try { await active.client.reset(active.context); await seed(active); await show(active); }
183
+ catch (error) { fail(error); } finally { reset.disabled = false; }
184
+ });
185
+ replace(persist.checked ? 'opfs' : 'memory').catch(fail);
source/browser-sqlite/src/sqlite.worker.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import { startBrowserSQLiteWorker } from 'teaql-ts/sql/browser-sqlite-worker';
2
+ import sqliteWasmUrl from '@sqlite.org/sqlite-wasm/sqlite3.wasm?url';
3
+
4
+ startBrowserSQLiteWorker({ wasmUrl: sqliteWasmUrl });
source/browser-sqlite/src/style.css ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root { font: 16px/1.5 Inter, system-ui, sans-serif; color: #e8edf5; background: #090b10; }
2
+ body { margin: 0; }
3
+ main { width: min(760px, calc(100% - 40px)); margin: 10vh auto; }
4
+ .eyebrow { color: #d9ff52; font-size: 12px; font-weight: 800; letter-spacing: .16em; }
5
+ h1 { margin: 8px 0; font-size: clamp(36px, 7vw, 68px); letter-spacing: -.05em; }
6
+ .controls { display: flex; gap: 18px; align-items: center; margin: 32px 0; }
7
+ button { border: 0; border-radius: 5px; padding: 10px 14px; background: #d9ff52; font-weight: 800; }
8
+ #status { color: #aab4c4; }
9
+ pre { min-height: 260px; padding: 22px; overflow: auto; border: 1px solid #2b323e; border-radius: 8px; background: #11151c; color: #c6d1df; }
10
+ .evidence-scroll { overflow-x: auto; margin: 24px 0; }
11
+ .evidence-table { border-collapse: collapse; width: 100%; text-align: left; }
12
+ .evidence-table th, .evidence-table td { padding: 12px; border: 1px solid #2b323e; vertical-align: top; }
13
+ .evidence-table td { white-space: pre-wrap; overflow-wrap: anywhere; min-width: 110px; }
14
+ .evidence-table td:last-child { min-width: 320px; font-family: monospace; }
source/browser-sqlite/src/web-response.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { SmartList } from 'teaql-ts';
2
+
3
+ /** Application response projection; querying and facet computation stay in the runtime. */
4
+ export function webResponse<T>(rows: SmartList<T>) {
5
+ const facets = Object.fromEntries(Object.entries(rows.facets)
6
+ .map(([name, values]) => [name, Array.from(values)]));
7
+ return {
8
+ data: Array.from(rows),
9
+ resultCode: 0,
10
+ status: 'YES' as const,
11
+ recordCount: rows.totalCountOrLength(),
12
+ version: '1.001',
13
+ ...(Object.keys(facets).length ? {facets} : {}),
14
+ ...(Object.keys(rows.aggregations).length ? {aggregations: rows.aggregations} : {}),
15
+ };
16
+ }
source/browser-sqlite/tsconfig.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "strict": true,
7
+ "skipLibCheck": true,
8
+ "types": ["vite/client"],
9
+ "lib": ["ES2022", "DOM", "WebWorker"]
10
+ },
11
+ "include": ["src"]
12
+ }
source/browser-sqlite/vendor/teaql-teaql-0.3.0.tgz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d4e5cbaecc4fcc06fe3b357a4575d6e5ca4a92673b625ef2c7d5ec7d02b287d
3
+ size 349294