@sun-asterisk/sungen 3.2.8 → 3.2.10-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/dist/capabilities/discover.js +1 -1
  2. package/dist/capabilities/discover.js.map +1 -1
  3. package/dist/capabilities/registry.d.ts +9 -0
  4. package/dist/capabilities/registry.d.ts.map +1 -1
  5. package/dist/capabilities/registry.js +4 -0
  6. package/dist/capabilities/registry.js.map +1 -1
  7. package/dist/cli/commands/delivery.d.ts.map +1 -1
  8. package/dist/cli/commands/delivery.js +15 -5
  9. package/dist/cli/commands/delivery.js.map +1 -1
  10. package/dist/cli/commands/generate.d.ts.map +1 -1
  11. package/dist/cli/commands/generate.js +16 -0
  12. package/dist/cli/commands/generate.js.map +1 -1
  13. package/dist/exporters/spec-parser.d.ts.map +1 -1
  14. package/dist/exporters/spec-parser.js +16 -5
  15. package/dist/exporters/spec-parser.js.map +1 -1
  16. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/alert-accept-action.hbs +1 -1
  17. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/alert-dismiss-action.hbs +1 -1
  18. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/alert-fill-action.hbs +1 -1
  19. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/capture-row-column.hbs +2 -0
  20. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/click-element-with-text.hbs +1 -1
  21. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/click-with-alert-action.hbs +2 -0
  22. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/recipe-sequence.hbs +3 -0
  23. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/table-action-in-row-nth.hbs +2 -0
  24. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/unknown-element-action.hbs +1 -1
  25. package/dist/generators/test-generator/adapters/playwright/templates/steps/navigation/route-assertion.hbs +3 -0
  26. package/dist/generators/test-generator/adapters/playwright/templates/steps/navigation/wait-for-element.hbs +1 -1
  27. package/dist/generators/test-generator/adapters/playwright/templates/steps/navigation/wait-table-refresh.hbs +3 -0
  28. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/has-text-value.hbs +1 -0
  29. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/locator-base.hbs +1 -1
  30. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/locator.hbs +1 -1
  31. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-blur.hbs +1 -0
  32. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-click-text.hbs +3 -0
  33. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-click.hbs +1 -0
  34. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-expect-text.hbs +1 -0
  35. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-expect-value.hbs +1 -0
  36. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-for-each.hbs +5 -0
  37. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-hover.hbs +1 -0
  38. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-press.hbs +1 -0
  39. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-scroll-into-view.hbs +1 -0
  40. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-type.hbs +1 -0
  41. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-wait-for.hbs +1 -0
  42. package/dist/generators/test-generator/app-profile.d.ts +89 -0
  43. package/dist/generators/test-generator/app-profile.d.ts.map +1 -0
  44. package/dist/generators/test-generator/app-profile.js +157 -0
  45. package/dist/generators/test-generator/app-profile.js.map +1 -0
  46. package/dist/generators/test-generator/code-generator.d.ts +4 -0
  47. package/dist/generators/test-generator/code-generator.d.ts.map +1 -1
  48. package/dist/generators/test-generator/code-generator.js +7 -0
  49. package/dist/generators/test-generator/code-generator.js.map +1 -1
  50. package/dist/generators/test-generator/diagnostics.d.ts +36 -0
  51. package/dist/generators/test-generator/diagnostics.d.ts.map +1 -0
  52. package/dist/generators/test-generator/diagnostics.js +44 -0
  53. package/dist/generators/test-generator/diagnostics.js.map +1 -0
  54. package/dist/generators/test-generator/patterns/types.d.ts +12 -0
  55. package/dist/generators/test-generator/patterns/types.d.ts.map +1 -1
  56. package/dist/generators/test-generator/recipe-expander.d.ts +32 -0
  57. package/dist/generators/test-generator/recipe-expander.d.ts.map +1 -0
  58. package/dist/generators/test-generator/recipe-expander.js +118 -0
  59. package/dist/generators/test-generator/recipe-expander.js.map +1 -0
  60. package/dist/generators/test-generator/step-mapper.d.ts +17 -0
  61. package/dist/generators/test-generator/step-mapper.d.ts.map +1 -1
  62. package/dist/generators/test-generator/step-mapper.js +70 -0
  63. package/dist/generators/test-generator/step-mapper.js.map +1 -1
  64. package/dist/generators/test-generator/template-engine.d.ts +5 -1
  65. package/dist/generators/test-generator/template-engine.d.ts.map +1 -1
  66. package/dist/generators/test-generator/template-engine.js +27 -3
  67. package/dist/generators/test-generator/template-engine.js.map +1 -1
  68. package/dist/generators/test-generator/utils/selector-resolver.d.ts +10 -1
  69. package/dist/generators/test-generator/utils/selector-resolver.d.ts.map +1 -1
  70. package/dist/generators/test-generator/utils/selector-resolver.js +32 -0
  71. package/dist/generators/test-generator/utils/selector-resolver.js.map +1 -1
  72. package/dist/harness/catalog/drivers.yaml +1 -1
  73. package/dist/harness/query-catalog.d.ts +32 -2
  74. package/dist/harness/query-catalog.d.ts.map +1 -1
  75. package/dist/harness/query-catalog.js +0 -0
  76. package/dist/harness/query-catalog.js.map +1 -1
  77. package/dist/index.d.ts +5 -2
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +5 -1
  80. package/dist/index.js.map +1 -1
  81. package/dist/orchestrator/templates/ai-src/commands/create-data-test.md +83 -0
  82. package/dist/orchestrator/templates/ai-src/commands/create-test.md +2 -2
  83. package/dist/orchestrator/templates/ai-src/commands/run-test.md +1 -1
  84. package/dist/orchestrator/templates/ai-src/config/claude.md +3 -1
  85. package/dist/orchestrator/templates/ai-src/config/copilot.md +3 -1
  86. package/dist/orchestrator/templates/ai-src/skills/sungen-data-factory/SKILL.md +93 -0
  87. package/dist/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +12 -1
  88. package/dist/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +66 -3
  89. package/dist/orchestrator/templates/ai-src/skills/sungen-selector-fix/SKILL.md +22 -0
  90. package/dist/orchestrator/templates/ai-src/skills/sungen-selector-keys/SKILL.md +14 -1
  91. package/dist/orchestrator/templates/specs-db.d.ts +204 -6
  92. package/dist/orchestrator/templates/specs-db.d.ts.map +1 -1
  93. package/dist/orchestrator/templates/specs-db.js +495 -54
  94. package/dist/orchestrator/templates/specs-db.js.map +1 -1
  95. package/dist/orchestrator/templates/specs-db.ts +507 -54
  96. package/dist/orchestrator/templates/specs-test-data.ts +39 -3
  97. package/package.json +10 -4
  98. package/src/capabilities/discover.ts +1 -1
  99. package/src/capabilities/registry.ts +13 -0
  100. package/src/cli/commands/delivery.ts +13 -5
  101. package/src/cli/commands/generate.ts +15 -0
  102. package/src/exporters/spec-parser.ts +17 -5
  103. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/alert-accept-action.hbs +1 -1
  104. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/alert-dismiss-action.hbs +1 -1
  105. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/alert-fill-action.hbs +1 -1
  106. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/capture-row-column.hbs +2 -0
  107. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/click-element-with-text.hbs +1 -1
  108. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/click-with-alert-action.hbs +2 -0
  109. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/recipe-sequence.hbs +3 -0
  110. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/table-action-in-row-nth.hbs +2 -0
  111. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/unknown-element-action.hbs +1 -1
  112. package/src/generators/test-generator/adapters/playwright/templates/steps/navigation/route-assertion.hbs +3 -0
  113. package/src/generators/test-generator/adapters/playwright/templates/steps/navigation/wait-for-element.hbs +1 -1
  114. package/src/generators/test-generator/adapters/playwright/templates/steps/navigation/wait-table-refresh.hbs +3 -0
  115. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/has-text-value.hbs +1 -0
  116. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/locator-base.hbs +1 -1
  117. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/locator.hbs +1 -1
  118. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-blur.hbs +1 -0
  119. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-click-text.hbs +3 -0
  120. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-click.hbs +1 -0
  121. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-expect-text.hbs +1 -0
  122. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-expect-value.hbs +1 -0
  123. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-for-each.hbs +5 -0
  124. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-hover.hbs +1 -0
  125. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-press.hbs +1 -0
  126. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-scroll-into-view.hbs +1 -0
  127. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-type.hbs +1 -0
  128. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/recipe-wait-for.hbs +1 -0
  129. package/src/generators/test-generator/app-profile.ts +185 -0
  130. package/src/generators/test-generator/code-generator.ts +9 -0
  131. package/src/generators/test-generator/diagnostics.ts +51 -0
  132. package/src/generators/test-generator/patterns/types.ts +12 -0
  133. package/src/generators/test-generator/recipe-expander.ts +129 -0
  134. package/src/generators/test-generator/step-mapper.ts +73 -0
  135. package/src/generators/test-generator/template-engine.ts +29 -3
  136. package/src/generators/test-generator/utils/selector-resolver.ts +49 -2
  137. package/src/harness/catalog/drivers.yaml +1 -1
  138. package/src/harness/query-catalog.ts +0 -0
  139. package/src/index.ts +5 -2
  140. package/src/orchestrator/templates/ai-src/commands/create-data-test.md +83 -0
  141. package/src/orchestrator/templates/ai-src/commands/create-test.md +2 -2
  142. package/src/orchestrator/templates/ai-src/commands/run-test.md +1 -1
  143. package/src/orchestrator/templates/ai-src/config/claude.md +3 -1
  144. package/src/orchestrator/templates/ai-src/config/copilot.md +3 -1
  145. package/src/orchestrator/templates/ai-src/skills/sungen-data-factory/SKILL.md +93 -0
  146. package/src/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +12 -1
  147. package/src/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +66 -3
  148. package/src/orchestrator/templates/ai-src/skills/sungen-selector-fix/SKILL.md +22 -0
  149. package/src/orchestrator/templates/ai-src/skills/sungen-selector-keys/SKILL.md +14 -1
  150. package/src/orchestrator/templates/specs-db.ts +507 -54
  151. package/src/orchestrator/templates/specs-test-data.ts +39 -3
@@ -6,7 +6,7 @@
6
6
  * table/column identifiers are validated against a strict allowlist pattern (identifiers
7
7
  * can't be bound as parameters). Secrets come from .env.qa / process.env, never inline.
8
8
  *
9
- * Engines: PostgreSQL (`pg`) and SQLite (`better-sqlite3`), lazy-loaded on first use.
9
+ * Engines: PostgreSQL (`pg`), MySQL (`mysql2`), and SQLite (`better-sqlite3`), lazy-loaded on first use.
10
10
  * Config: a `datasources.yaml` at the project root (or qa/), with ${VAR} resolved from env.
11
11
  *
12
12
  * DO NOT EDIT — regenerated by `sungen generate`.
@@ -21,6 +21,14 @@ const ident = (s: string): string => {
21
21
  return s;
22
22
  };
23
23
 
24
+ // SQL engines: verified via the direct guarded-SELECT path and needing the `$n`→`?` placeholder
25
+ // rewrite. This literal is the single source of truth for that rewrite condition and is quoted, by
26
+ // name, in the sungen-gherkin-syntax skill's "direct SQL verification" note — keep them in sync.
27
+ const SUPPORTED_ENGINES = ['postgres', 'sqlite', 'mysql'] as const;
28
+ // NoSQL engines: implement the Engine contract natively (no SQL rewrite). Tracked separately so the
29
+ // SQL-rewrite guard and its skill-parity test stay pinned to the three SQL engines above.
30
+ const NOSQL_ENGINES = ['cosmos', 'mongodb', 'dynamodb'] as const;
31
+
24
32
  interface SshConfig {
25
33
  host: string; // jump host reachable from the runner
26
34
  port?: number; // default 22
@@ -32,14 +40,25 @@ interface SshConfig {
32
40
  }
33
41
 
34
42
  interface DataSourceConfig {
35
- engine: 'postgres' | 'mysql' | 'sqlite';
43
+ engine: 'postgres' | 'mysql' | 'sqlite' | 'cosmos' | 'mongodb' | 'dynamodb';
36
44
  url: string;
37
45
  readonly?: boolean;
38
46
  statement_timeout_ms?: number;
39
47
  max_rows?: number;
40
- // Cách B (fallback): tunnel the DB SOCKET through an SSH bastion. DB-only — the browser/E2E
41
- // still run on the runner; only PG traffic crosses. See docs/spec/sungen_data_driver_ssh_tunnel_spec.md.
48
+ // Fallback path: tunnel the DB SOCKET through an SSH bastion. DB-only — the browser/E2E
49
+ // still run on the runner; only DB traffic crosses. See docs/spec/sungen_data_driver_ssh_tunnel_spec.md.
42
50
  ssh?: SshConfig;
51
+ // Cosmos DB (NoSQL API): connect via endpoint+key (or a connection-string `url`); `database` is the
52
+ // Cosmos database, `container` the default container when a step/catalog names no `[table]`.
53
+ endpoint?: string;
54
+ key?: string;
55
+ database?: string;
56
+ container?: string;
57
+ // DynamoDB: no connection URL — `region` + credentials from the AWS env chain (AWS_* / IAM role).
58
+ // `keySchema` maps each table to its key attributes so declarative steps can route GetItem/Query
59
+ // instead of an unaffordable full-table Scan; a non-key filter is refused (use a raw @query SELECT).
60
+ region?: string;
61
+ keySchema?: Record<string, { partitionKey: string; sortKey?: string | null }>;
43
62
  }
44
63
 
45
64
  /**
@@ -120,12 +139,366 @@ function loadConfig(): Record<string, DataSourceConfig> {
120
139
  return doc.datasources;
121
140
  }
122
141
 
123
- type Engine = { query(sql: string, params: any[]): Promise<any[]>; };
142
+ /**
143
+ * `build()` always emits PG-style `$1..$n` placeholders; mysql2/better-sqlite3 both bind with
144
+ * positional `?` (left-to-right). Rewriting `$n`→`?` must therefore ALSO reorder the params to the
145
+ * textual placeholder order: an author-written catalog query `WHERE a = $2 AND b = $1` becomes
146
+ * `a = ? AND b = ?`, so the params must be bound `[params[1], params[0]]` — otherwise the values
147
+ * silently swap and the query returns wrong rows. A repeated `$k` duplicates its value at each `?`.
148
+ * Postgres binds `$n` natively, so it is returned untouched.
149
+ *
150
+ * Only real placeholders are rewritten — a `$1` inside a single-quoted string literal (e.g.
151
+ * `WHERE label = '$1 off'`) is left untouched. SQL escapes an inner quote by doubling it (`''`),
152
+ * which the simple in-string toggle handles (an even number of quotes returns to the same state).
153
+ *
154
+ * DynamoDB PartiQL binds the same positional `?` as mysql2/sqlite, so it shares this path — the
155
+ * reorder is essential there too (an author-written PartiQL `WHERE sk = $2 AND pk = $1`).
156
+ */
157
+ export function rewritePlaceholders(engine: string, sql: string, params: any[]): { sql: string; params: any[] } {
158
+ if (engine !== 'sqlite' && engine !== 'mysql' && engine !== 'dynamodb') return { sql, params };
159
+ let out = '';
160
+ let inStr = false;
161
+ const newParams: any[] = [];
162
+ for (let i = 0; i < sql.length; i++) {
163
+ const c = sql[i];
164
+ if (c === "'") { inStr = !inStr; out += c; continue; }
165
+ if (!inStr && c === '$' && sql[i + 1] >= '0' && sql[i + 1] <= '9') {
166
+ let j = i + 1;
167
+ while (j < sql.length && sql[j] >= '0' && sql[j] <= '9') j++;
168
+ const k = Number(sql.slice(i + 1, j)); // 1-based placeholder index
169
+ out += '?';
170
+ newParams.push(params[k - 1]);
171
+ i = j - 1;
172
+ continue;
173
+ }
174
+ out += c;
175
+ }
176
+ return { sql: out, params: newParams };
177
+ }
178
+
179
+ /**
180
+ * Engine contract — the assertion surface is engine-agnostic; each engine owns its own dialect so
181
+ * a NoSQL store (Cosmos / MongoDB / DynamoDB) can back the same declarative steps as SQL.
182
+ * findRows(table, filter, limit) — rows matching an equality filter, capped at `limit`
183
+ * countRows(table, filter) — count of rows matching an equality filter
184
+ * runQuery(label, sql, params) — a raw catalog query (read-only). SQL dialects (incl. Cosmos SQL
185
+ * and DynamoDB PartiQL) take a SQL string; MongoDB's non-SQL
186
+ * find/pipeline shapes are dispatched separately via fetchQueryShape.
187
+ */
188
+ interface Engine {
189
+ findRows(table: string, filter: Record<string, any>, limit: number): Promise<any[]>;
190
+ countRows(table: string, filter: Record<string, any>): Promise<number>;
191
+ runQuery(label: string, sql: string, params: any[]): Promise<any[]>;
192
+ // Non-SQL raw query (MongoDB find/pipeline). Only engines with a non-SQL catalog shape implement it;
193
+ // fetchQueryShape refuses the call on an engine that doesn't.
194
+ runShape?(label: string, shape: ShapeQuery, params: Record<string, any>): Promise<any[]>;
195
+ }
196
+
197
+ /** A MongoDB catalog entry's runtime shape: exactly one of find/pipeline, with `:param` placeholders bound at runtime. */
198
+ type ShapeQuery = {
199
+ find?: { collection: string; filter?: Record<string, any>; projection?: Record<string, any>; sort?: Record<string, any>; limit?: number };
200
+ pipeline?: { collection: string; stages: any[] };
201
+ };
202
+
203
+ /** Read-only guard (second layer): a named SQL query must be a single SELECT/WITH statement. */
204
+ function assertSelectOnly(label: string, sql: string): void {
205
+ const s = sql.trim().replace(/;\s*$/, '');
206
+ if (!/^(SELECT|WITH)\b/i.test(s)) throw new Error(`Data Driver: ${label} is not a read-only SELECT — refused.`);
207
+ if (s.includes(';')) throw new Error(`Data Driver: ${label} contains multiple statements — refused.`);
208
+ if (/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE|GRANT|REVOKE|MERGE|REPLACE|CALL|EXEC|EXECUTE|ATTACH|PRAGMA|VACUUM)\b/i.test(s)) {
209
+ throw new Error(`Data Driver: ${label} contains a write/DDL keyword — refused.`);
210
+ }
211
+ }
212
+
213
+ /**
214
+ * SQL engine (postgres / mysql / sqlite). Builds the exact guarded, parameterized SELECTs the Data
215
+ * Driver has always emitted — `SELECT * … WHERE col = $n LIMIT`, `SELECT count(*)`, the `$n`→`?`
216
+ * reorder, and the read-only catalog guard — so the query strings are byte-identical to the
217
+ * pre-refactor path. `exec` is the lazy-loaded driver call (pg/mysql2/better-sqlite3).
218
+ */
219
+ class SqlEngine implements Engine {
220
+ constructor(private engineName: string, private exec: (sql: string, params: any[]) => Promise<any[]>) {}
221
+
222
+ private rewrite(sql: string, params: any[]): { sql: string; params: any[] } {
223
+ return rewritePlaceholders(this.engineName, sql, params);
224
+ }
225
+
226
+ async findRows(table: string, filter: Record<string, any>, limit: number): Promise<any[]> {
227
+ const cols = Object.keys(filter);
228
+ const where = cols.map((c, i) => `${ident(c)} = $${i + 1}`).join(' AND ');
229
+ const sql = `SELECT * FROM ${ident(table)}${where ? ' WHERE ' + where : ''} LIMIT ${limit}`;
230
+ const q = this.rewrite(sql, cols.map((c) => filter[c]));
231
+ return this.exec(q.sql, q.params);
232
+ }
233
+
234
+ async countRows(table: string, filter: Record<string, any>): Promise<number> {
235
+ const cols = Object.keys(filter);
236
+ const where = cols.map((c, i) => `${ident(c)} = $${i + 1}`).join(' AND ');
237
+ const sql = `SELECT count(*) AS n FROM ${ident(table)}${where ? ' WHERE ' + where : ''}`;
238
+ const q = this.rewrite(sql, cols.map((c) => filter[c]));
239
+ const rows = await this.exec(q.sql, q.params);
240
+ return Number(rows[0]?.n ?? rows[0]?.['count(*)'] ?? 0);
241
+ }
242
+
243
+ async runQuery(label: string, sql: string, params: any[]): Promise<any[]> {
244
+ assertSelectOnly(label, sql);
245
+ const q = this.rewrite(sql, params);
246
+ return this.exec(q.sql, q.params);
247
+ }
248
+ }
249
+
250
+ /** Minimal shape of an @azure/cosmos container the engine uses — kept local so the SDK stays a lazy dep. */
251
+ type CosmosContainer = { items: { query(spec: { query: string; parameters: Array<{ name: string; value: any }> }, opts?: any): { fetchAll(): Promise<{ resources: any[] }> } } };
252
+
253
+ /**
254
+ * Azure Cosmos DB (NoSQL API) engine. The Cosmos query API is read-only by construction — `.query()`
255
+ * only ever reads; mutations require item-level APIs this engine never calls — so the SELECT guard is
256
+ * defense-in-depth. Cosmos binds NAMED params (`@p`), so it is immune to the positional-`?` reorder
257
+ * hazard. A step/catalog `[table]` selects the container; `SELECT * FROM c` uses the mandatory `c` alias.
258
+ */
259
+ export class CosmosEngine implements Engine {
260
+ constructor(
261
+ private getContainer: (name?: string) => CosmosContainer,
262
+ private opts: { timeoutMs: number; maxRows: number },
263
+ ) {}
264
+
265
+ private async query(container: CosmosContainer, spec: { query: string; parameters: Array<{ name: string; value: any }> }): Promise<any[]> {
266
+ const ac = new AbortController();
267
+ const timer = setTimeout(() => ac.abort(), this.opts.timeoutMs);
268
+ try {
269
+ const res = await container.items.query(spec, { maxItemCount: this.opts.maxRows, abortSignal: ac.signal }).fetchAll();
270
+ return res.resources.slice(0, this.opts.maxRows);
271
+ } finally {
272
+ clearTimeout(timer);
273
+ }
274
+ }
275
+
276
+ /** Build `c.<col> = @p<i>` equality predicates over the mandatory `c` alias. Columns are identifier-checked. */
277
+ private whereFor(filter: Record<string, any>): { where: string; parameters: Array<{ name: string; value: any }> } {
278
+ const cols = Object.keys(filter);
279
+ const where = cols.map((c, i) => `c.${ident(c)} = @p${i}`).join(' AND ');
280
+ const parameters = cols.map((c, i) => ({ name: `@p${i}`, value: filter[c] }));
281
+ return { where: where ? ` WHERE ${where}` : '', parameters };
282
+ }
283
+
284
+ async findRows(table: string, filter: Record<string, any>, limit: number): Promise<any[]> {
285
+ const { where, parameters } = this.whereFor(filter);
286
+ // TOP bounds the fetch server-side (like the SQL engine's LIMIT) — without it, fetchAll() would
287
+ // drain every matching row into memory before the client-side slice, wasting RUs + latency.
288
+ const cap = Math.min(limit, this.opts.maxRows);
289
+ const rows = await this.query(this.getContainer(table), { query: `SELECT TOP ${cap} * FROM c${where}`, parameters });
290
+ return rows.slice(0, limit);
291
+ }
292
+
293
+ async countRows(table: string, filter: Record<string, any>): Promise<number> {
294
+ const { where, parameters } = this.whereFor(filter);
295
+ // SELECT VALUE COUNT(1) returns the scalar count as the single resource.
296
+ const rows = await this.query(this.getContainer(table), { query: `SELECT VALUE COUNT(1) FROM c${where}`, parameters });
297
+ return Number(rows[0] ?? 0);
298
+ }
299
+
300
+ async runQuery(label: string, sql: string, params: any[]): Promise<any[]> {
301
+ assertSelectOnly(label, sql); // defense-in-depth; the query API is read-only anyway
302
+ const { query, parameters } = cosmosBindParams(sql, params);
303
+ return this.query(this.getContainer(), { query, parameters });
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Rewrite compiled positional `$n` placeholders to Cosmos NAMED params (`@pN`) and collect the
309
+ * matching parameter list. A `$n` inside a single-quoted string literal is left untouched (same
310
+ * in-string toggle as the SQL rewrite); a repeated `$n` reuses its one `@pN` entry.
311
+ */
312
+ export function cosmosBindParams(sql: string, params: any[]): { query: string; parameters: Array<{ name: string; value: any }> } {
313
+ const parameters: Array<{ name: string; value: any }> = [];
314
+ const seen = new Set<number>();
315
+ let out = '';
316
+ let inStr = false;
317
+ for (let i = 0; i < sql.length; i++) {
318
+ const c = sql[i];
319
+ if (c === "'") { inStr = !inStr; out += c; continue; }
320
+ if (!inStr && c === '$' && sql[i + 1] >= '0' && sql[i + 1] <= '9') {
321
+ let j = i + 1;
322
+ while (j < sql.length && sql[j] >= '0' && sql[j] <= '9') j++;
323
+ const k = Number(sql.slice(i + 1, j));
324
+ out += `@p${k}`;
325
+ if (!seen.has(k)) { seen.add(k); parameters.push({ name: `@p${k}`, value: params[k - 1] }); }
326
+ i = j - 1;
327
+ continue;
328
+ }
329
+ out += c;
330
+ }
331
+ return { query: out, parameters };
332
+ }
333
+
334
+ /** Minimal shapes of the mongodb driver objects the engine uses — kept local so the SDK stays a lazy dep. */
335
+ type MongoCursor = { project(p: any): MongoCursor; sort(s: any): MongoCursor; limit(n: number): MongoCursor; maxTimeMS(t: number): MongoCursor; toArray(): Promise<any[]> };
336
+ type MongoCollection = { find(filter: any): MongoCursor; countDocuments(filter: any, opts?: any): Promise<number>; aggregate(pipeline: any[], opts?: any): { toArray(): Promise<any[]> } };
337
+
338
+ /** Forbidden MongoDB operators (write-out / server-side JS) — refused at runtime as defense-in-depth. */
339
+ const MONGO_FORBIDDEN = /\$out|\$merge|\$where|\$function|\$accumulator|mapReduce/i;
340
+
341
+ /** Replace every whole-string `:param` in a find/pipeline shape with its bound native value (type-preserving). */
342
+ function substituteShapeParams(obj: any, params: Record<string, any>): any {
343
+ if (typeof obj === 'string') {
344
+ const m = obj.match(/^:([A-Za-z_][A-Za-z0-9_]*)$/);
345
+ return m ? params[m[1]] : obj;
346
+ }
347
+ if (Array.isArray(obj)) return obj.map((v) => substituteShapeParams(v, params));
348
+ if (obj && typeof obj === 'object') {
349
+ const out: Record<string, any> = {};
350
+ for (const [k, v] of Object.entries(obj)) out[k] = substituteShapeParams(v, params);
351
+ return out;
352
+ }
353
+ return obj;
354
+ }
355
+
356
+ /** Refuse a shape whose serialized form contains a write/JS-exec operator (nested or aliased). */
357
+ function assertMongoReadOnly(label: string, shape: any): void {
358
+ const m = JSON.stringify(shape ?? {}).match(MONGO_FORBIDDEN);
359
+ if (m) throw new Error(`Data Driver: ${label} uses forbidden MongoDB operator "${m[0]}" — refused (read-only find/aggregate only).`);
360
+ }
361
+
362
+ /**
363
+ * MongoDB engine. There is no SQL — declarative steps map to native find()/countDocuments(), and the
364
+ * raw `@query` path takes a find/pipeline shape (via fetchQueryShape → runShape) rather than a SQL
365
+ * string. Type-strict matching (`{age:30}` ≠ `{age:"30"}`) is why DB params bind via raw() (native
366
+ * type), not the stringifying get(). Read-only is enforced first by the server-side read role, with
367
+ * the operator blocklist as in-driver defense-in-depth. Per-query `maxTimeMS` + row cap bound cost.
368
+ */
369
+ export class MongoEngine implements Engine {
370
+ constructor(
371
+ private getCollection: (name: string) => MongoCollection,
372
+ private opts: { timeoutMs: number; maxRows: number },
373
+ ) {}
374
+
375
+ async findRows(table: string, filter: Record<string, any>, limit: number): Promise<any[]> {
376
+ return this.getCollection(table).find(filter).limit(limit).maxTimeMS(this.opts.timeoutMs).toArray();
377
+ }
378
+
379
+ async countRows(table: string, filter: Record<string, any>): Promise<number> {
380
+ return this.getCollection(table).countDocuments(filter, { maxTimeMS: this.opts.timeoutMs });
381
+ }
382
+
383
+ async runQuery(label: string): Promise<any[]> {
384
+ throw new Error(`Data Driver: ${label} — MongoDB has no SQL; author a find:/pipeline: catalog entry instead of sql:.`);
385
+ }
386
+
387
+ async runShape(label: string, shape: ShapeQuery, params: Record<string, any>): Promise<any[]> {
388
+ if (shape.find) {
389
+ const f = substituteShapeParams(shape.find, params) as NonNullable<ShapeQuery['find']>;
390
+ assertMongoReadOnly(label, f);
391
+ let cursor = this.getCollection(f.collection).find(f.filter ?? {});
392
+ if (f.projection) cursor = cursor.project(f.projection);
393
+ if (f.sort) cursor = cursor.sort(f.sort);
394
+ cursor = cursor.limit(f.limit ?? this.opts.maxRows).maxTimeMS(this.opts.timeoutMs);
395
+ return cursor.toArray();
396
+ }
397
+ if (shape.pipeline) {
398
+ const p = substituteShapeParams(shape.pipeline, params) as NonNullable<ShapeQuery['pipeline']>;
399
+ assertMongoReadOnly(label, p);
400
+ const rows = await this.getCollection(p.collection).aggregate(p.stages, { maxTimeMS: this.opts.timeoutMs }).toArray();
401
+ return rows.slice(0, this.opts.maxRows);
402
+ }
403
+ throw new Error(`Data Driver: ${label} — catalog shape has neither find: nor pipeline:.`);
404
+ }
405
+ }
406
+
407
+ /** The three read-only DynamoDB operations the engine needs, over the auto-marshalling Document client. */
408
+ type DynamoOps = {
409
+ executeStatement(input: { Statement: string; Parameters?: any[]; Limit?: number; NextToken?: string }, signal?: AbortSignal): Promise<{ Items?: any[]; NextToken?: string }>;
410
+ getItem(input: { TableName: string; Key: Record<string, any> }, signal?: AbortSignal): Promise<{ Item?: any }>;
411
+ query(input: { TableName: string; KeyConditionExpression: string; ExpressionAttributeNames: Record<string, string>; ExpressionAttributeValues: Record<string, any>; Select?: string; Limit?: number; ExclusiveStartKey?: Record<string, any> }, signal?: AbortSignal): Promise<{ Items?: any[]; Count?: number; LastEvaluatedKey?: Record<string, any> }>;
412
+ };
413
+
414
+ type KeySchema = Record<string, { partitionKey: string; sortKey?: string | null }>;
415
+ type DynamoRoute = { kind: 'get'; key: Record<string, any> } | { kind: 'query'; pk: string; value: any };
416
+
417
+ /**
418
+ * DynamoDB engine. The clean primary path is raw `@query` PartiQL SELECT (positional `?`, reordered
419
+ * via the shared placeholder rewrite). Declarative assertRow/count is structurally constrained by
420
+ * DynamoDB's key model: it routes GetItem/Query only for pk / pk+sk filters (via the `keySchema`
421
+ * registry) and REFUSES a non-key filter rather than falling back to an unaffordable full-table Scan.
422
+ * Read-only is primarily IAM (`dynamodb:PartiQLSelect` only); the SELECT guard is defense-in-depth.
423
+ */
424
+ export class DynamoEngine implements Engine {
425
+ constructor(
426
+ private ops: DynamoOps,
427
+ private keySchema: KeySchema,
428
+ private opts: { timeoutMs: number; maxRows: number },
429
+ ) {}
430
+
431
+ private async withTimeout<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
432
+ const ac = new AbortController();
433
+ const timer = setTimeout(() => ac.abort(), this.opts.timeoutMs);
434
+ try { return await fn(ac.signal); } finally { clearTimeout(timer); }
435
+ }
436
+
437
+ /** Decide how a flat equality filter maps to a key-based access pattern, or refuse it. */
438
+ private route(table: string, filter: Record<string, any>): DynamoRoute {
439
+ const ks = this.keySchema[table];
440
+ if (!ks) throw new Error(`Data Driver: DynamoDB table "${table}" has no keySchema entry — add it under the datasource's keySchema:, or use a raw @query PartiQL SELECT.`);
441
+ const pk = ks.partitionKey;
442
+ const sk = ks.sortKey || undefined;
443
+ const keyAttrs = sk ? [pk, sk] : [pk];
444
+ const keys = Object.keys(filter);
445
+ const nonKey = keys.filter((k) => !keyAttrs.includes(k));
446
+ if (nonKey.length) throw new Error(`Data Driver: DynamoDB "${table}" filter has non-key attribute(s) [${nonKey.join(', ')}] — routing would require a full-table Scan (refused). Use a raw @query PartiQL SELECT instead.`);
447
+ if (!keys.includes(pk)) throw new Error(`Data Driver: DynamoDB "${table}" filter must include the partition key "${pk}".`);
448
+ if (sk && keys.includes(sk)) return { kind: 'get', key: { [pk]: filter[pk], [sk]: filter[sk] } };
449
+ if (!sk) return { kind: 'get', key: { [pk]: filter[pk] } };
450
+ return { kind: 'query', pk, value: filter[pk] }; // pk only on a table that has a sort key → Query
451
+ }
452
+
453
+ async findRows(table: string, filter: Record<string, any>, limit: number): Promise<any[]> {
454
+ const route = this.route(table, filter);
455
+ const cap = Math.min(limit, this.opts.maxRows);
456
+ if (route.kind === 'get') {
457
+ const res = await this.withTimeout((s) => this.ops.getItem({ TableName: table, Key: route.key }, s));
458
+ return res.Item ? [res.Item] : [];
459
+ }
460
+ const res = await this.withTimeout((s) => this.ops.query({ TableName: table, KeyConditionExpression: '#pk = :pk', ExpressionAttributeNames: { '#pk': route.pk }, ExpressionAttributeValues: { ':pk': route.value }, Limit: cap }, s));
461
+ return (res.Items ?? []).slice(0, cap);
462
+ }
463
+
464
+ async countRows(table: string, filter: Record<string, any>): Promise<number> {
465
+ const route = this.route(table, filter);
466
+ if (route.kind === 'get') {
467
+ const res = await this.withTimeout((s) => this.ops.getItem({ TableName: table, Key: route.key }, s));
468
+ return res.Item ? 1 : 0;
469
+ }
470
+ // A Query with Select:COUNT evaluates at most ~1MB per request and returns a PARTIAL Count with a
471
+ // LastEvaluatedKey for the rest — accumulate across pages so the exact-equality assert is correct.
472
+ let count = 0;
473
+ let startKey: Record<string, any> | undefined;
474
+ do {
475
+ const res = await this.withTimeout((s) => this.ops.query({ TableName: table, KeyConditionExpression: '#pk = :pk', ExpressionAttributeNames: { '#pk': route.pk }, ExpressionAttributeValues: { ':pk': route.value }, Select: 'COUNT', ExclusiveStartKey: startKey }, s));
476
+ count += Number(res.Count ?? 0);
477
+ startKey = res.LastEvaluatedKey;
478
+ } while (startKey);
479
+ return count;
480
+ }
481
+
482
+ async runQuery(label: string, sql: string, params: any[]): Promise<any[]> {
483
+ assertSelectOnly(label, sql); // defense-in-depth; primary read-only guarantee is IAM PartiQLSelect-only
484
+ const bound = rewritePlaceholders('dynamodb', sql, params); // $n → ? positional, reordered to textual order
485
+ const items: any[] = [];
486
+ let nextToken: string | undefined;
487
+ do {
488
+ const page = await this.withTimeout((s) => this.ops.executeStatement({ Statement: bound.sql, Parameters: bound.params.length ? bound.params : undefined, Limit: this.opts.maxRows, NextToken: nextToken }, s));
489
+ items.push(...(page.Items ?? []));
490
+ nextToken = page.NextToken;
491
+ } while (nextToken && items.length < this.opts.maxRows); // manual pagination, bounded by the row cap
492
+ return items.slice(0, this.opts.maxRows);
493
+ }
494
+ }
124
495
 
125
496
  class DataSource {
126
497
  private configs: Record<string, DataSourceConfig> | null = null;
127
498
  private engines = new Map<string, Engine>();
128
499
  private tunnels: Array<{ close: () => void }> = [];
500
+ private mysqlPools: Array<{ end: () => Promise<void> }> = [];
501
+ private mongoClients: Array<{ close: () => Promise<void> }> = [];
129
502
 
130
503
  private cfg(name?: string): { key: string; conf: DataSourceConfig } {
131
504
  if (!this.configs) this.configs = loadConfig();
@@ -138,11 +511,30 @@ class DataSource {
138
511
  private async engine(name?: string): Promise<{ engine: Engine; conf: DataSourceConfig }> {
139
512
  const { key, conf } = this.cfg(name);
140
513
  if (this.engines.has(key)) return { engine: this.engines.get(key)!, conf };
141
- if (!conf.url) throw new Error(`Data Driver: datasource "${key}" has no url (set it in .env.qa).`);
142
514
  let engine: Engine;
515
+ if (conf.engine === 'postgres' || conf.engine === 'mysql' || conf.engine === 'sqlite') {
516
+ // url is required for the SQL engines (host-based, or a sqlite file path). NoSQL engines that
517
+ // have no connection URL (e.g. DynamoDB region+creds) supply their own config and skip this.
518
+ if (!conf.url) throw new Error(`Data Driver: datasource "${key}" has no url (set it in .env.qa).`);
519
+ engine = new SqlEngine(conf.engine, await this.sqlExec(key, conf));
520
+ } else if (conf.engine === 'cosmos') {
521
+ engine = this.cosmosEngine(key, conf);
522
+ } else if (conf.engine === 'mongodb') {
523
+ engine = this.mongoEngine(key, conf);
524
+ } else if (conf.engine === 'dynamodb') {
525
+ engine = this.dynamoEngine(key, conf);
526
+ } else {
527
+ throw new Error(`Data Driver: engine "${conf.engine}" not supported (supported: ${[...SUPPORTED_ENGINES, ...NOSQL_ENGINES].join(' | ')}). For an unlisted store, verify via @api or @manual.`);
528
+ }
529
+ this.engines.set(key, engine);
530
+ return { engine, conf };
531
+ }
532
+
533
+ /** Build the lazy driver-call closure for a SQL engine (pg/mysql/sqlite), incl. the optional SSH-tunnel fallback. */
534
+ private async sqlExec(key: string, conf: DataSourceConfig): Promise<(sql: string, params: any[]) => Promise<any[]>> {
143
535
  if (conf.engine === 'postgres') {
144
536
  let connectionString = conf.url;
145
- if (conf.ssh) { // Cách B: tunnel the DB socket through a bastion
537
+ if (conf.ssh) { // Fallback path: tunnel the DB socket through a bastion
146
538
  const u = new URL(conf.url);
147
539
  const t = await openSshTunnel(conf.ssh, u.hostname, Number(u.port || 5432));
148
540
  this.tunnels.push(t);
@@ -151,37 +543,108 @@ class DataSource {
151
543
  }
152
544
  const { Pool } = require('pg');
153
545
  const pool = new Pool({ connectionString, max: 2, statement_timeout: conf.statement_timeout_ms ?? 4000 });
154
- engine = { query: async (sql, params) => (await pool.query(sql, params)).rows };
155
- } else if (conf.engine === 'sqlite') {
156
- if (conf.ssh) console.warn(`Data Driver: datasource "${key}" sets ssh: but engine is sqlite (file-based) — ssh ignored.`);
157
- const Database = require('better-sqlite3');
158
- const db = new Database(conf.url.replace(/^sqlite:/, ''), { readonly: conf.readonly !== false });
159
- engine = { query: async (sql, params) => db.prepare(sql).all(...params) };
160
- } else {
161
- throw new Error(`Data Driver: engine "${conf.engine}" not supported yet (postgres | sqlite).`);
546
+ return async (sql, params) => (await pool.query(sql, params)).rows;
162
547
  }
163
- this.engines.set(key, engine);
164
- return { engine, conf };
548
+ if (conf.engine === 'mysql') {
549
+ let connectionString = conf.url;
550
+ if (conf.ssh) { // Fallback path: tunnel the DB socket through a bastion
551
+ const u = new URL(conf.url);
552
+ const t = await openSshTunnel(conf.ssh, u.hostname, Number(u.port || 3306));
553
+ this.tunnels.push(t);
554
+ u.hostname = t.host; u.port = String(t.port); // rewrite host:port → 127.0.0.1:<tunnel> (keep user/pass/db/query)
555
+ connectionString = u.toString();
556
+ }
557
+ const mysql = require('mysql2/promise');
558
+ const pool = mysql.createPool({ uri: connectionString, connectionLimit: 2 });
559
+ this.mysqlPools.push(pool);
560
+ // mysql2 ignores the mysqljs per-query `timeout` field, and destroying the connection does
561
+ // not interrupt an in-flight query — so bound the wait client-side by racing the query
562
+ // against a timer. On overrun we reject and destroy the connection (removes it from the pool
563
+ // rather than releasing a still-busy socket); on success we release it back.
564
+ const timeoutMs = conf.statement_timeout_ms ?? 4000;
565
+ return async (sql, params) => {
566
+ const conn = await pool.getConnection();
567
+ const qp = conn.query(sql, params);
568
+ qp.catch(() => { /* swallow the post-timeout rejection from the abandoned query */ });
569
+ let timer: NodeJS.Timeout | undefined;
570
+ let timedOut = false;
571
+ const guard = new Promise<never>((_, reject) => {
572
+ timer = setTimeout(() => { timedOut = true; reject(new Error(`Data Driver: mysql query exceeded ${timeoutMs}ms — aborted.`)); }, timeoutMs);
573
+ });
574
+ try {
575
+ const [rows] = await Promise.race([qp, guard]);
576
+ return rows as any[];
577
+ } finally {
578
+ clearTimeout(timer);
579
+ if (timedOut) { try { conn.destroy(); } catch { /* best-effort */ } }
580
+ else { try { conn.release(); } catch { /* already gone */ } }
581
+ }
582
+ };
583
+ }
584
+ // sqlite
585
+ if (conf.ssh) console.warn(`Data Driver: datasource "${key}" sets ssh: but engine is sqlite (file-based) — ssh ignored.`);
586
+ const Database = require('better-sqlite3');
587
+ const db = new Database(conf.url.replace(/^sqlite:/, ''), { readonly: conf.readonly !== false });
588
+ return async (sql, params) => db.prepare(sql).all(...params);
589
+ }
590
+
591
+ /** Build the Cosmos engine — connect via endpoint+key or a connection-string url; resolve containers by name. */
592
+ private cosmosEngine(key: string, conf: DataSourceConfig): Engine {
593
+ const { CosmosClient } = require('@azure/cosmos');
594
+ let client: any;
595
+ if (conf.endpoint && conf.key) client = new CosmosClient({ endpoint: conf.endpoint, key: conf.key });
596
+ else if (conf.url) client = new CosmosClient(conf.url); // AccountEndpoint=…;AccountKey=…; connection string
597
+ else throw new Error(`Data Driver: cosmos datasource "${key}" needs endpoint+key (or a connection-string url).`);
598
+ if (!conf.database) throw new Error(`Data Driver: cosmos datasource "${key}" needs a database name.`);
599
+ const getContainer = (name?: string): CosmosContainer => {
600
+ const cn = name || conf.container;
601
+ if (!cn) throw new Error(`Data Driver: cosmos datasource "${key}" — no container (set container: in config, or name a [table]).`);
602
+ return client.database(conf.database!).container(cn);
603
+ };
604
+ return new CosmosEngine(getContainer, { timeoutMs: conf.statement_timeout_ms ?? 4000, maxRows: conf.max_rows ?? 100 });
605
+ }
606
+
607
+ /** Build the MongoDB engine — one reused client per datasource; the db comes from `database` or the URI default. */
608
+ private mongoEngine(key: string, conf: DataSourceConfig): Engine {
609
+ if (!conf.url) throw new Error(`Data Driver: mongodb datasource "${key}" needs a url (mongodb:// URI).`);
610
+ const { MongoClient } = require('mongodb');
611
+ const client = new MongoClient(conf.url); // operations auto-connect; one client is reused
612
+ this.mongoClients.push(client);
613
+ const dbHandle = client.db(conf.database); // undefined → the URI's default database
614
+ return new MongoEngine((name: string) => dbHandle.collection(name), { timeoutMs: conf.statement_timeout_ms ?? 5000, maxRows: conf.max_rows ?? 50 });
165
615
  }
166
616
 
167
- /** Close any open SSH tunnels (optional explicit teardown; tunnels are unref'd so the process exits regardless). */
617
+ /** Build the DynamoDB engine region + credentials from the AWS env chain; wraps the Document client's three read ops. */
618
+ private dynamoEngine(key: string, conf: DataSourceConfig): Engine {
619
+ if (!conf.region) throw new Error(`Data Driver: dynamodb datasource "${key}" needs a region (DynamoDB has no url).`);
620
+ const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
621
+ const { DynamoDBDocumentClient, ExecuteStatementCommand, GetCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb');
622
+ const base = new DynamoDBClient({ region: conf.region }); // creds resolved from env / IAM role
623
+ const doc = DynamoDBDocumentClient.from(base, { marshallOptions: { removeUndefinedValues: true } });
624
+ const ops: DynamoOps = {
625
+ executeStatement: (input, signal) => doc.send(new ExecuteStatementCommand(input), { abortSignal: signal }),
626
+ getItem: (input, signal) => doc.send(new GetCommand(input), { abortSignal: signal }),
627
+ query: (input, signal) => doc.send(new QueryCommand(input), { abortSignal: signal }),
628
+ };
629
+ return new DynamoEngine(ops, conf.keySchema ?? {}, { timeoutMs: conf.statement_timeout_ms ?? 4000, maxRows: conf.max_rows ?? 1000 });
630
+ }
631
+
632
+ /** Close open MySQL pools + Mongo clients + SSH tunnels (optional explicit teardown; tunnels are unref'd so the process exits regardless). */
168
633
  close(): void {
634
+ for (const p of this.mysqlPools) { try { void p.end(); } catch { /* best-effort */ } }
635
+ this.mysqlPools = [];
636
+ for (const c of this.mongoClients) { try { void c.close(); } catch { /* best-effort */ } }
637
+ this.mongoClients = [];
169
638
  for (const t of this.tunnels) t.close();
170
639
  this.tunnels = [];
171
640
  }
172
641
 
173
- private build(table: string, filter: Record<string, any>): { sql: string; params: any[] } {
174
- const cols = Object.keys(filter);
175
- const where = cols.map((c, i) => `${ident(c)} = $${i + 1}`).join(' AND ');
176
- const sql = `SELECT * FROM ${ident(table)}${where ? ' WHERE ' + where : ''} LIMIT 50`;
177
- return { sql, params: cols.map((c) => filter[c]) };
178
- }
642
+ // --- Engine-agnostic assertions: build nothing, just delegate to the engine + compare here ----
179
643
 
180
644
  /** A row matching `filter` must exist; if `expected` given, assert those columns on the first match. */
181
645
  async assertRow(table: string, filter: Record<string, any>, expected?: Record<string, any>, datasource?: string): Promise<void> {
182
- const { engine, conf } = await this.engine(datasource);
183
- const { sql, params } = this.build(table, filter);
184
- const rows = await engine.query(this.sqlFor(conf, sql), params);
646
+ const { engine } = await this.engine(datasource);
647
+ const rows = await engine.findRows(table, filter, 50);
185
648
  expect(rows.length, `Expected a row in "${table}" where ${desc(filter)} — found ${rows.length}`).toBeGreaterThanOrEqual(1);
186
649
  if (expected) {
187
650
  const row = rows[0];
@@ -194,48 +657,38 @@ class DataSource {
194
657
 
195
658
  /** No row matching `filter` may exist. */
196
659
  async assertNoRow(table: string, filter: Record<string, any>, datasource?: string): Promise<void> {
197
- const { engine, conf } = await this.engine(datasource);
198
- const { sql, params } = this.build(table, filter);
199
- const rows = await engine.query(this.sqlFor(conf, sql), params);
660
+ const { engine } = await this.engine(datasource);
661
+ const rows = await engine.findRows(table, filter, 50);
200
662
  expect(rows.length, `Expected NO row in "${table}" where ${desc(filter)} — found ${rows.length}`).toBe(0);
201
663
  }
202
664
 
203
665
  /** Exactly `count` rows must match `filter`. */
204
666
  async assertCount(table: string, filter: Record<string, any>, count: number, datasource?: string): Promise<void> {
205
- const { engine, conf } = await this.engine(datasource);
667
+ const { engine } = await this.engine(datasource);
668
+ const n = await engine.countRows(table, filter);
206
669
  const cols = Object.keys(filter);
207
- const where = cols.map((c, i) => `${ident(c)} = $${i + 1}`).join(' AND ');
208
- const sql = `SELECT count(*) AS n FROM ${ident(table)}${where ? ' WHERE ' + where : ''}`;
209
- const rows = await engine.query(this.sqlFor(conf, sql), cols.map((c) => filter[c]));
210
- const n = Number(rows[0]?.n ?? rows[0]?.['count(*)'] ?? 0);
211
670
  expect(n, `Expected ${count} row(s) in "${table}"${cols.length ? ' where ' + desc(filter) : ''} — found ${n}`).toBe(Number(count));
212
671
  }
213
672
 
214
- /** Rewrites $1/$2 placeholders to `?` for SQLite. */
215
- private sqlFor(conf: DataSourceConfig, sql: string): string {
216
- return conf.engine === 'sqlite' ? sql.replace(/\$\d+/g, '?') : sql;
217
- }
218
-
219
- // --- Named queries (catalog-backed; SQL is resolved + embedded at compile time) -----------
220
- /** Read-only guard (second layer): a named query must be a single SELECT/WITH statement. */
221
- private assertSelectOnly(label: string, sql: string): void {
222
- const s = sql.trim().replace(/;\s*$/, '');
223
- if (!/^(SELECT|WITH)\b/i.test(s)) throw new Error(`Data Driver: ${label} is not a read-only SELECT — refused.`);
224
- if (s.includes(';')) throw new Error(`Data Driver: ${label} contains multiple statements — refused.`);
225
- if (/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE|GRANT|REVOKE|MERGE|REPLACE|CALL|EXEC|EXECUTE|ATTACH|PRAGMA|VACUUM)\b/i.test(s)) {
226
- throw new Error(`Data Driver: ${label} contains a write/DDL keyword — refused.`);
227
- }
228
- }
229
-
230
673
  /**
231
674
  * Run a catalog query (read-only) and return its rows. The result is bound to a `{{name}}`
232
675
  * variable via `testData.bind(...)`, so the scenario asserts on it with `expect …` steps and
233
676
  * path access (`{{name.count}}`, `{{name.first.col}}`, `{{name[2].col}}`).
234
677
  */
235
678
  async fetchQuery(label: string, sql: string, params: any[], datasource?: string): Promise<any[]> {
236
- this.assertSelectOnly(label, sql);
237
- const { engine, conf } = await this.engine(datasource);
238
- return engine.query(this.sqlFor(conf, sql), params);
679
+ const { engine } = await this.engine(datasource);
680
+ return engine.runQuery(label, sql, params);
681
+ }
682
+
683
+ /**
684
+ * Run a MongoDB find/pipeline catalog query (read-only) and return its documents. Same binding
685
+ * contract as fetchQuery, but the query is a structured shape (not SQL) with `:param` placeholders
686
+ * bound from `params` at runtime. Refused on an engine that has no non-SQL shape support.
687
+ */
688
+ async fetchQueryShape(label: string, shape: ShapeQuery, params: Record<string, any>, datasource?: string): Promise<any[]> {
689
+ const { engine } = await this.engine(datasource);
690
+ if (!engine.runShape) throw new Error(`Data Driver: ${label} is a find/pipeline query, but this datasource's engine has no such support (find:/pipeline: is MongoDB-only).`);
691
+ return engine.runShape(label, shape, params);
239
692
  }
240
693
  }
241
694