@rawsql-ts/ztd-cli 0.16.0 → 0.19.0

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 (242) hide show
  1. package/README.md +532 -353
  2. package/package.json +35 -17
  3. package/templates/.editorconfig +16 -16
  4. package/templates/.prettierignore +2 -2
  5. package/templates/.prettierrc +24 -24
  6. package/templates/AGENTS.md +30 -325
  7. package/templates/CONTEXT.md +11 -0
  8. package/templates/CONTEXT.webapi.md +11 -0
  9. package/templates/DESIGN.md +17 -0
  10. package/templates/DEV_NOTES.md +14 -0
  11. package/templates/PROMPT_DOGFOOD.webapi.md +49 -0
  12. package/templates/README.md +46 -217
  13. package/templates/README.webapi.md +38 -0
  14. package/templates/scripts/local-source-guard.mjs +189 -0
  15. package/templates/src/AGENTS.md +26 -0
  16. package/templates/src/application/AGENTS.md +15 -0
  17. package/templates/src/application/README.md +6 -0
  18. package/templates/src/catalog/AGENTS.md +28 -0
  19. package/templates/src/catalog/runtime/AGENTS.md +28 -0
  20. package/templates/src/catalog/runtime/_coercions.local-source.ts +30 -0
  21. package/templates/src/catalog/runtime/_coercions.ts +30 -0
  22. package/templates/src/catalog/runtime/_smoke.runtime.ts +21 -0
  23. package/templates/src/catalog/specs/AGENTS.md +41 -0
  24. package/templates/src/catalog/specs/_smoke.spec.arktype.ts +21 -0
  25. package/templates/src/catalog/specs/_smoke.spec.zod.ts +20 -0
  26. package/templates/src/db/sql-client-adapters.ts +32 -0
  27. package/templates/src/db/sql-client.ts +24 -24
  28. package/templates/src/domain/AGENTS.md +15 -0
  29. package/templates/src/domain/README.md +6 -0
  30. package/templates/src/infrastructure/AGENTS.md +14 -0
  31. package/templates/src/infrastructure/README.md +6 -0
  32. package/templates/src/infrastructure/db/AGENTS.md +14 -0
  33. package/templates/src/infrastructure/db/sql-client-adapters.ts +34 -0
  34. package/templates/src/infrastructure/db/sql-client.ts +24 -0
  35. package/templates/src/infrastructure/persistence/AGENTS.md +18 -0
  36. package/templates/src/infrastructure/persistence/README.md +8 -0
  37. package/templates/src/infrastructure/persistence/repositories/AGENTS.md +17 -0
  38. package/templates/src/infrastructure/persistence/repositories/tables/AGENTS.md +20 -0
  39. package/templates/src/infrastructure/persistence/repositories/tables/README.md +5 -0
  40. package/templates/src/infrastructure/persistence/repositories/views/AGENTS.md +16 -0
  41. package/templates/src/infrastructure/persistence/repositories/views/README.md +5 -0
  42. package/templates/src/infrastructure/telemetry/AGENTS.md +14 -0
  43. package/templates/src/infrastructure/telemetry/consoleRepositoryTelemetry.ts +66 -0
  44. package/templates/src/infrastructure/telemetry/repositoryTelemetry.ts +26 -0
  45. package/templates/src/infrastructure/telemetry/types.ts +48 -0
  46. package/templates/src/jobs/AGENTS.md +25 -0
  47. package/templates/src/jobs/README.md +3 -0
  48. package/templates/src/local/sql-contract.ts +1 -0
  49. package/templates/src/presentation/AGENTS.md +15 -0
  50. package/templates/src/presentation/http/AGENTS.md +15 -0
  51. package/templates/src/presentation/http/README.md +6 -0
  52. package/templates/src/repositories/AGENTS.md +30 -0
  53. package/templates/src/repositories/tables/AGENTS.md +29 -0
  54. package/templates/src/repositories/tables/README.md +5 -0
  55. package/templates/src/repositories/views/AGENTS.md +25 -0
  56. package/templates/src/repositories/views/README.md +5 -0
  57. package/templates/src/sql/AGENTS.md +30 -0
  58. package/templates/src/sql/README.md +6 -0
  59. package/templates/tests/AGENTS.md +29 -169
  60. package/templates/tests/generated/AGENTS.md +23 -0
  61. package/templates/tests/smoke.test.ts +25 -0
  62. package/templates/tests/smoke.validation.test.ts +34 -0
  63. package/templates/tests/support/AGENTS.md +24 -0
  64. package/templates/tests/support/global-setup.ts +15 -30
  65. package/templates/tests/support/testkit-client.ts +14 -742
  66. package/templates/tests/support/testkit-client.webapi.ts +14 -0
  67. package/templates/tests/ztd-layout.generated.ts +6 -6
  68. package/templates/tsconfig.json +15 -8
  69. package/templates/vitest.config.ts +13 -13
  70. package/templates/ztd/AGENTS.md +23 -74
  71. package/templates/ztd/README.md +6 -15
  72. package/templates/ztd/ddl/AGENTS.md +26 -0
  73. package/templates/ztd/ddl/demo.sql +74 -0
  74. package/LICENSE +0 -21
  75. package/dist/commands/ddl.d.ts +0 -7
  76. package/dist/commands/ddl.js +0 -118
  77. package/dist/commands/ddl.js.map +0 -1
  78. package/dist/commands/diff.d.ts +0 -10
  79. package/dist/commands/diff.js +0 -38
  80. package/dist/commands/diff.js.map +0 -1
  81. package/dist/commands/genEntities.d.ts +0 -6
  82. package/dist/commands/genEntities.js +0 -50
  83. package/dist/commands/genEntities.js.map +0 -1
  84. package/dist/commands/init.d.ts +0 -66
  85. package/dist/commands/init.js +0 -838
  86. package/dist/commands/init.js.map +0 -1
  87. package/dist/commands/lint.d.ts +0 -59
  88. package/dist/commands/lint.js +0 -338
  89. package/dist/commands/lint.js.map +0 -1
  90. package/dist/commands/options.d.ts +0 -9
  91. package/dist/commands/options.js +0 -48
  92. package/dist/commands/options.js.map +0 -1
  93. package/dist/commands/pull.d.ts +0 -10
  94. package/dist/commands/pull.js +0 -105
  95. package/dist/commands/pull.js.map +0 -1
  96. package/dist/commands/ztdConfig.d.ts +0 -23
  97. package/dist/commands/ztdConfig.js +0 -202
  98. package/dist/commands/ztdConfig.js.map +0 -1
  99. package/dist/commands/ztdConfigCommand.d.ts +0 -5
  100. package/dist/commands/ztdConfigCommand.js +0 -157
  101. package/dist/commands/ztdConfigCommand.js.map +0 -1
  102. package/dist/index.d.ts +0 -2
  103. package/dist/index.js +0 -22
  104. package/dist/index.js.map +0 -1
  105. package/dist/utils/agents.d.ts +0 -1
  106. package/dist/utils/agents.js +0 -48
  107. package/dist/utils/agents.js.map +0 -1
  108. package/dist/utils/collectSqlFiles.d.ts +0 -9
  109. package/dist/utils/collectSqlFiles.js +0 -58
  110. package/dist/utils/collectSqlFiles.js.map +0 -1
  111. package/dist/utils/connectionSummary.d.ts +0 -3
  112. package/dist/utils/connectionSummary.js +0 -29
  113. package/dist/utils/connectionSummary.js.map +0 -1
  114. package/dist/utils/dbConnection.d.ts +0 -29
  115. package/dist/utils/dbConnection.js +0 -210
  116. package/dist/utils/dbConnection.js.map +0 -1
  117. package/dist/utils/fs.d.ts +0 -1
  118. package/dist/utils/fs.js +0 -12
  119. package/dist/utils/fs.js.map +0 -1
  120. package/dist/utils/normalizePulledSchema.d.ts +0 -12
  121. package/dist/utils/normalizePulledSchema.js +0 -213
  122. package/dist/utils/normalizePulledSchema.js.map +0 -1
  123. package/dist/utils/pgDump.d.ts +0 -11
  124. package/dist/utils/pgDump.js +0 -55
  125. package/dist/utils/pgDump.js.map +0 -1
  126. package/dist/utils/sqlLintHelpers.d.ts +0 -18
  127. package/dist/utils/sqlLintHelpers.js +0 -270
  128. package/dist/utils/sqlLintHelpers.js.map +0 -1
  129. package/dist/utils/typeMapper.d.ts +0 -4
  130. package/dist/utils/typeMapper.js +0 -76
  131. package/dist/utils/typeMapper.js.map +0 -1
  132. package/dist/utils/ztdProjectConfig.d.ts +0 -40
  133. package/dist/utils/ztdProjectConfig.js +0 -167
  134. package/dist/utils/ztdProjectConfig.js.map +0 -1
  135. package/templates/dist/drivers/pg-testkit/src/driver/PgTestkitClient.d.ts +0 -38
  136. package/templates/dist/drivers/pg-testkit/src/driver/PgTestkitClient.js +0 -117
  137. package/templates/dist/drivers/pg-testkit/src/driver/PgTestkitClient.js.map +0 -1
  138. package/templates/dist/drivers/pg-testkit/src/driver/createPgTestkitPool.d.ts +0 -4
  139. package/templates/dist/drivers/pg-testkit/src/driver/createPgTestkitPool.js +0 -71
  140. package/templates/dist/drivers/pg-testkit/src/driver/createPgTestkitPool.js.map +0 -1
  141. package/templates/dist/drivers/pg-testkit/src/index.d.ts +0 -5
  142. package/templates/dist/drivers/pg-testkit/src/index.js +0 -11
  143. package/templates/dist/drivers/pg-testkit/src/index.js.map +0 -1
  144. package/templates/dist/drivers/pg-testkit/src/proxy/wrapPgClient.d.ts +0 -3
  145. package/templates/dist/drivers/pg-testkit/src/proxy/wrapPgClient.js +0 -79
  146. package/templates/dist/drivers/pg-testkit/src/proxy/wrapPgClient.js.map +0 -1
  147. package/templates/dist/drivers/pg-testkit/src/types.d.ts +0 -69
  148. package/templates/dist/drivers/pg-testkit/src/types.js +0 -3
  149. package/templates/dist/drivers/pg-testkit/src/types.js.map +0 -1
  150. package/templates/dist/drivers/pg-testkit/src/utils/fixtureState.d.ts +0 -15
  151. package/templates/dist/drivers/pg-testkit/src/utils/fixtureState.js +0 -34
  152. package/templates/dist/drivers/pg-testkit/src/utils/fixtureState.js.map +0 -1
  153. package/templates/dist/drivers/pg-testkit/src/utils/fixtureValidation.d.ts +0 -12
  154. package/templates/dist/drivers/pg-testkit/src/utils/fixtureValidation.js +0 -53
  155. package/templates/dist/drivers/pg-testkit/src/utils/fixtureValidation.js.map +0 -1
  156. package/templates/dist/mapper-core/src/index.d.ts +0 -160
  157. package/templates/dist/mapper-core/src/index.js +0 -637
  158. package/templates/dist/mapper-core/src/index.js.map +0 -1
  159. package/templates/dist/testkit-core/src/errors/index.d.ts +0 -49
  160. package/templates/dist/testkit-core/src/errors/index.js +0 -111
  161. package/templates/dist/testkit-core/src/errors/index.js.map +0 -1
  162. package/templates/dist/testkit-core/src/fixtures/ColumnAffinity.d.ts +0 -5
  163. package/templates/dist/testkit-core/src/fixtures/ColumnAffinity.js +0 -29
  164. package/templates/dist/testkit-core/src/fixtures/ColumnAffinity.js.map +0 -1
  165. package/templates/dist/testkit-core/src/fixtures/DdlFixtureLoader.d.ts +0 -37
  166. package/templates/dist/testkit-core/src/fixtures/DdlFixtureLoader.js +0 -182
  167. package/templates/dist/testkit-core/src/fixtures/DdlFixtureLoader.js.map +0 -1
  168. package/templates/dist/testkit-core/src/fixtures/FixtureProvider.d.ts +0 -20
  169. package/templates/dist/testkit-core/src/fixtures/FixtureProvider.js +0 -121
  170. package/templates/dist/testkit-core/src/fixtures/FixtureProvider.js.map +0 -1
  171. package/templates/dist/testkit-core/src/fixtures/FixtureStore.d.ts +0 -51
  172. package/templates/dist/testkit-core/src/fixtures/FixtureStore.js +0 -199
  173. package/templates/dist/testkit-core/src/fixtures/FixtureStore.js.map +0 -1
  174. package/templates/dist/testkit-core/src/fixtures/TableDefinitionSchemaRegistry.d.ts +0 -10
  175. package/templates/dist/testkit-core/src/fixtures/TableDefinitionSchemaRegistry.js +0 -28
  176. package/templates/dist/testkit-core/src/fixtures/TableDefinitionSchemaRegistry.js.map +0 -1
  177. package/templates/dist/testkit-core/src/fixtures/TableNameResolver.d.ts +0 -18
  178. package/templates/dist/testkit-core/src/fixtures/TableNameResolver.js +0 -80
  179. package/templates/dist/testkit-core/src/fixtures/TableNameResolver.js.map +0 -1
  180. package/templates/dist/testkit-core/src/fixtures/ddlLint.d.ts +0 -59
  181. package/templates/dist/testkit-core/src/fixtures/ddlLint.js +0 -489
  182. package/templates/dist/testkit-core/src/fixtures/ddlLint.js.map +0 -1
  183. package/templates/dist/testkit-core/src/fixtures/naming.d.ts +0 -1
  184. package/templates/dist/testkit-core/src/fixtures/naming.js +0 -6
  185. package/templates/dist/testkit-core/src/fixtures/naming.js.map +0 -1
  186. package/templates/dist/testkit-core/src/index.d.ts +0 -17
  187. package/templates/dist/testkit-core/src/index.js +0 -47
  188. package/templates/dist/testkit-core/src/index.js.map +0 -1
  189. package/templates/dist/testkit-core/src/logger/NoopLogger.d.ts +0 -8
  190. package/templates/dist/testkit-core/src/logger/NoopLogger.js +0 -16
  191. package/templates/dist/testkit-core/src/logger/NoopLogger.js.map +0 -1
  192. package/templates/dist/testkit-core/src/provider/TestkitProvider.d.ts +0 -57
  193. package/templates/dist/testkit-core/src/provider/TestkitProvider.js +0 -149
  194. package/templates/dist/testkit-core/src/provider/TestkitProvider.js.map +0 -1
  195. package/templates/dist/testkit-core/src/rewriter/ResultSelectRewriter.d.ts +0 -43
  196. package/templates/dist/testkit-core/src/rewriter/ResultSelectRewriter.js +0 -473
  197. package/templates/dist/testkit-core/src/rewriter/ResultSelectRewriter.js.map +0 -1
  198. package/templates/dist/testkit-core/src/rewriter/SelectAnalyzer.d.ts +0 -9
  199. package/templates/dist/testkit-core/src/rewriter/SelectAnalyzer.js +0 -38
  200. package/templates/dist/testkit-core/src/rewriter/SelectAnalyzer.js.map +0 -1
  201. package/templates/dist/testkit-core/src/rewriter/SelectFixtureRewriter.d.ts +0 -42
  202. package/templates/dist/testkit-core/src/rewriter/SelectFixtureRewriter.js +0 -298
  203. package/templates/dist/testkit-core/src/rewriter/SelectFixtureRewriter.js.map +0 -1
  204. package/templates/dist/testkit-core/src/sql/SqliteValuesBuilder.d.ts +0 -12
  205. package/templates/dist/testkit-core/src/sql/SqliteValuesBuilder.js +0 -63
  206. package/templates/dist/testkit-core/src/sql/SqliteValuesBuilder.js.map +0 -1
  207. package/templates/dist/testkit-core/src/types/index.d.ts +0 -69
  208. package/templates/dist/testkit-core/src/types/index.js +0 -3
  209. package/templates/dist/testkit-core/src/types/index.js.map +0 -1
  210. package/templates/dist/testkit-core/src/utils/queryHelpers.d.ts +0 -28
  211. package/templates/dist/testkit-core/src/utils/queryHelpers.js +0 -81
  212. package/templates/dist/testkit-core/src/utils/queryHelpers.js.map +0 -1
  213. package/templates/dist/writer-core/src/index.d.ts +0 -34
  214. package/templates/dist/writer-core/src/index.js +0 -115
  215. package/templates/dist/writer-core/src/index.js.map +0 -1
  216. package/templates/dist/ztd-cli/templates/src/db/sql-client.d.ts +0 -20
  217. package/templates/dist/ztd-cli/templates/src/db/sql-client.js +0 -3
  218. package/templates/dist/ztd-cli/templates/src/db/sql-client.js.map +0 -1
  219. package/templates/dist/ztd-cli/templates/src/repositories/user-accounts.d.ts +0 -36
  220. package/templates/dist/ztd-cli/templates/src/repositories/user-accounts.js +0 -85
  221. package/templates/dist/ztd-cli/templates/src/repositories/user-accounts.js.map +0 -1
  222. package/templates/dist/ztd-cli/templates/tests/generated/ztd-row-map.generated.d.ts +0 -20
  223. package/templates/dist/ztd-cli/templates/tests/generated/ztd-row-map.generated.js +0 -33
  224. package/templates/dist/ztd-cli/templates/tests/generated/ztd-row-map.generated.js.map +0 -1
  225. package/templates/dist/ztd-cli/templates/tests/support/global-setup.d.ts +0 -10
  226. package/templates/dist/ztd-cli/templates/tests/support/global-setup.js +0 -29
  227. package/templates/dist/ztd-cli/templates/tests/support/global-setup.js.map +0 -1
  228. package/templates/dist/ztd-cli/templates/tests/support/testkit-client.d.ts +0 -66
  229. package/templates/dist/ztd-cli/templates/tests/support/testkit-client.js +0 -552
  230. package/templates/dist/ztd-cli/templates/tests/support/testkit-client.js.map +0 -1
  231. package/templates/dist/ztd-cli/templates/tests/user-profiles.test.d.ts +0 -1
  232. package/templates/dist/ztd-cli/templates/tests/user-profiles.test.js +0 -82
  233. package/templates/dist/ztd-cli/templates/tests/user-profiles.test.js.map +0 -1
  234. package/templates/dist/ztd-cli/templates/tests/writer-constraints.test.d.ts +0 -1
  235. package/templates/dist/ztd-cli/templates/tests/writer-constraints.test.js +0 -29
  236. package/templates/dist/ztd-cli/templates/tests/writer-constraints.test.js.map +0 -1
  237. package/templates/dist/ztd-cli/templates/tests/ztd-layout.generated.d.ts +0 -7
  238. package/templates/dist/ztd-cli/templates/tests/ztd-layout.generated.js +0 -10
  239. package/templates/dist/ztd-cli/templates/tests/ztd-layout.generated.js.map +0 -1
  240. package/templates/src/repositories/user-accounts.ts +0 -179
  241. package/templates/tests/user-profiles.test.ts +0 -161
  242. package/templates/tests/writer-constraints.test.ts +0 -32
@@ -0,0 +1,21 @@
1
+ import { parseSmokeOutput, type SmokeOutput } from '../specs/_smoke.spec';
2
+ import { normalizeTimestamp } from './_coercions';
3
+
4
+ /**
5
+ * Validate runtime output against the catalog smoke invariant.
6
+ */
7
+ export function ensureSmokeOutput(value: unknown): SmokeOutput {
8
+ // Normalize driver-dependent timestamp representations before contract validation.
9
+ if (isRecord(value) && 'createdAt' in value) {
10
+ return parseSmokeOutput({
11
+ ...value,
12
+ createdAt: normalizeTimestamp(value.createdAt, 'createdAt')
13
+ });
14
+ }
15
+
16
+ return parseSmokeOutput(value);
17
+ }
18
+
19
+ function isRecord(value: unknown): value is Record<string, unknown> {
20
+ return typeof value === 'object' && value !== null;
21
+ }
@@ -0,0 +1,41 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/catalog/specs`.
3
+ - Defines human-owned query/command contracts for params, DTOs, and semantics.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Specs MUST define public input and output validators.
8
+ - Specs MUST preserve declared parameter shape, DTO shape, nullability, cardinality, and semantics.
9
+ - Driver-dependent normalization behavior MUST be specified for runtime handling, not SQL workaround encoding.
10
+
11
+ ## ALLOWED
12
+ - Specs MAY acknowledge driver representation variance when runtime normalization is defined.
13
+
14
+ ## PROHIBITED
15
+ - Inferring or modifying contract shape without explicit instruction.
16
+ - Adding executors, DB connections, or ZTD internal dependencies.
17
+
18
+ # Mandatory Workflow
19
+ - Contract changes MUST run tests that validate success and failure paths.
20
+
21
+ ## Generating initial output types
22
+
23
+ Use `npx ztd model-gen <sql-file> --probe-mode ztd --out src/catalog/specs/<spec-file>.ts` to derive the first QuerySpec scaffold from the local DDL snapshot.
24
+
25
+ - SQL assets are expected to use named parameters (`:name`).
26
+ - `ztd model-gen` is names-first and derives `sqlFile` / `spec id` from the SQL path under `src/sql` by default.
27
+ - `ztd model-gen --probe-mode ztd` is the recommended fast-loop path when the referenced schema already exists in `ztd/ddl/*.sql`.
28
+ - In `--probe-mode ztd`, unqualified table references follow the configured `defaultSchema` / `searchPath` priority from `ztd.config.json`.
29
+ - The CLI default remains `--probe-mode live` for backward compatibility, but project guidance should treat `--probe-mode ztd` as the preferred inner-loop mode.
30
+ - `ztd model-gen --probe-mode ztd` uses the ZTD-owned test database from `ZTD_TEST_DATABASE_URL`.
31
+ - `ztd model-gen --probe-mode live` is an explicit target inspection path and MUST be used with `--url` or a complete `--db-*` flag set.
32
+ - `DATABASE_URL` is a runtime concern and is not read implicitly by `ztd-cli`.
33
+ - Positional placeholders are legacy and should be rewritten whenever possible.
34
+ - Use `--allow-positional` only when a legacy SQL asset cannot be rewritten immediately.
35
+ - Review the generated file before commit: confirm imports, nullability, cardinality, rowMapping key, runtime normalization, and example values.
36
+
37
+ # Hygiene
38
+ - Keep contract definitions isolated from runtime wiring and SQL implementation logic.
39
+
40
+ # References
41
+ - Parent catalog policy: [../AGENTS.md](../AGENTS.md)
@@ -0,0 +1,21 @@
1
+ import { type } from 'arktype';
2
+
3
+ /**
4
+ * Validator invariant contract used to prove runtime validation wiring.
5
+ *
6
+ * This file is intentionally minimal and domain-agnostic.
7
+ */
8
+ export const smokeOutputSchema = type({
9
+ id: 'number.integer',
10
+ createdAt: 'Date'
11
+ });
12
+
13
+ export type SmokeOutput = ReturnType<typeof smokeOutputSchema>;
14
+
15
+ /**
16
+ * Parse and validate an unknown runtime payload.
17
+ */
18
+ export function parseSmokeOutput(value: unknown): SmokeOutput {
19
+ smokeOutputSchema.assert(value);
20
+ return value as SmokeOutput;
21
+ }
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Validator invariant contract used to prove runtime validation wiring.
5
+ *
6
+ * This file is intentionally minimal and domain-agnostic.
7
+ */
8
+ export const smokeOutputSchema = z.object({
9
+ id: z.number().int(),
10
+ createdAt: z.date()
11
+ });
12
+
13
+ export type SmokeOutput = z.infer<typeof smokeOutputSchema>;
14
+
15
+ /**
16
+ * Parse and validate an unknown runtime payload.
17
+ */
18
+ export function parseSmokeOutput(value: unknown): SmokeOutput {
19
+ return smokeOutputSchema.parse(value);
20
+ }
@@ -0,0 +1,32 @@
1
+ import type { SqlClient } from './sql-client';
2
+
3
+ /**
4
+ * Adapt a `pg`-style queryable (Client or Pool) into a SqlClient.
5
+ *
6
+ * pg's `query()` returns `QueryResult<T>` with a `.rows` property.
7
+ * This helper unwraps the result so it satisfies the `SqlClient` contract.
8
+ *
9
+ * Usage:
10
+ * const pool = new Pool({ connectionString: process.env.DATABASE_URL });
11
+ * const client = fromPg(pool);
12
+ * const users = await client.query<{ id: number }>('SELECT id ...', []);
13
+ */
14
+ export function fromPg(
15
+ queryable: {
16
+ query(text: string, values?: readonly unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
17
+ }
18
+ ): SqlClient {
19
+ return {
20
+ query<T extends Record<string, unknown> = Record<string, unknown>>(
21
+ text: string,
22
+ values?: readonly unknown[] | Record<string, unknown>
23
+ ): Promise<T[]> {
24
+ if (values != null && !Array.isArray(values)) {
25
+ throw new Error('fromPg adapter does not support named parameter objects; use positional parameter arrays');
26
+ }
27
+ return queryable
28
+ .query(text, values as readonly unknown[])
29
+ .then((result) => result.rows as T[]);
30
+ }
31
+ };
32
+ }
@@ -1,24 +1,24 @@
1
- /**
2
- * Promise that resolves to the array of rows produced by an SQL query.
3
- * @template T Shape of each row yielded by the SQL client.
4
- * @example
5
- * const rows: SqlQueryRows<{ id: number; name: string }> = client.query('SELECT id, name FROM users');
6
- */
7
- export type SqlQueryRows<T> = Promise<T[]>;
8
-
9
- /**
10
- * Minimal SQL client interface required by the repository layer.
11
- *
12
- * - Production: adapt `pg` (or other drivers) to normalize results into `T[]`
13
- * - Tests: compatible with the `testkit-postgres` pipeline exposed by `@rawsql-ts/adapter-node-pg` clients returned by `createTestkitClient()`
14
- *
15
- * Connection strategy note:
16
- * - Prefer a shared client per worker process for performance.
17
- * - Do not share a live client across parallel workers.
18
- */
19
- export type SqlClient = {
20
- query<T extends Record<string, unknown> = Record<string, unknown>>(
21
- text: string,
22
- values?: readonly unknown[]
23
- ): SqlQueryRows<T>;
24
- };
1
+ /**
2
+ * Promise that resolves to the array of rows produced by an SQL query.
3
+ * @template T Shape of each row yielded by the SQL client.
4
+ * @example
5
+ * const rows: SqlQueryRows<{ id: number; name: string }> = client.query('SELECT id, name FROM users');
6
+ */
7
+ export type SqlQueryRows<T> = Promise<T[]>;
8
+
9
+ /**
10
+ * Minimal SQL client interface required by the repository layer.
11
+ *
12
+ * - Production: adapt this interface to your preferred driver (pg, mysql2, etc.) and normalize the results to `T[]`.
13
+ * - Tests: replace the implementation with a mock, a fixture helper, or an adapter that follows this contract.
14
+ *
15
+ * Connection strategy note:
16
+ * - Prefer a shared client per worker process for better performance.
17
+ * - Do not share a live client across parallel workers without proper synchronization.
18
+ */
19
+ export type SqlClient = {
20
+ query<T extends Record<string, unknown> = Record<string, unknown>>(
21
+ text: string,
22
+ values?: readonly unknown[] | Record<string, unknown>
23
+ ): SqlQueryRows<T>;
24
+ };
@@ -0,0 +1,15 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/domain`.
3
+ - Defines the domain layer for WebAPI-oriented scaffolds.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Domain code MUST remain independent from SQL, DDL, QuerySpecs, and generated test artifacts.
8
+ - Domain modules MUST express business rules in transport-agnostic types.
9
+
10
+ ## PROHIBITED
11
+ - Importing `src/sql`, `src/catalog`, `ztd`, or telemetry scaffolds into domain code.
12
+ - Encoding HTTP or persistence concerns in domain rules.
13
+
14
+ # Mandatory Workflow
15
+ - Domain changes MUST run the relevant typecheck and unit tests.
@@ -0,0 +1,6 @@
1
+ # Domain
2
+
3
+ Domain types, invariants, and business rules live here.
4
+
5
+ - Do not import SQL files, QuerySpecs, or ZTD-generated artifacts into this layer.
6
+ - Prefer ports or plain interfaces for dependencies on application or infrastructure code.
@@ -0,0 +1,14 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/infrastructure`.
3
+ - Defines infrastructure adapters for WebAPI-oriented scaffolds.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Infrastructure code MUST adapt external systems to application or domain-facing contracts.
8
+ - Persistence-specific ZTD workflow rules MUST stay in `src/infrastructure/persistence` and related assets.
9
+
10
+ ## PROHIBITED
11
+ - Treating infrastructure rules as domain or application rules.
12
+
13
+ # Mandatory Workflow
14
+ - Infrastructure changes MUST run targeted tests for adapter behavior.
@@ -0,0 +1,6 @@
1
+ # Infrastructure
2
+
3
+ Infrastructure adapters live here.
4
+
5
+ - Database, telemetry, and persistence integration belong here.
6
+ - Keep domain and application contracts stable while swapping implementations.
@@ -0,0 +1,14 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/infrastructure/db`.
3
+ - Defines SQL client seams and driver adapters for WebAPI-oriented scaffolds.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Driver adapters MUST fulfill the `SqlClient` contract without leaking driver-specific result objects.
8
+ - Connection lifecycle decisions MUST remain explicit.
9
+
10
+ ## PROHIBITED
11
+ - Embedding repository business rules in DB adapter code.
12
+
13
+ # Mandatory Workflow
14
+ - DB adapter changes MUST run typecheck and adapter-focused tests.
@@ -0,0 +1,34 @@
1
+ import type { SqlClient } from './sql-client';
2
+
3
+ /**
4
+ * Adapt a `pg`-style queryable (Client or Pool) into a SqlClient.
5
+ *
6
+ * pg's `query()` returns `QueryResult<T>` with a `.rows` property.
7
+ * This helper unwraps the result so it satisfies the `SqlClient` contract.
8
+ *
9
+ * Usage:
10
+ * // This runtime example uses DATABASE_URL for application code.
11
+ * // ztd-cli itself does not read DATABASE_URL implicitly.
12
+ * const pool = new Pool({ connectionString: process.env.DATABASE_URL });
13
+ * const client = fromPg(pool);
14
+ * const users = await client.query<{ id: number }>('SELECT id ...', []);
15
+ */
16
+ export function fromPg(
17
+ queryable: {
18
+ query(text: string, values?: readonly unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
19
+ }
20
+ ): SqlClient {
21
+ return {
22
+ query<T extends Record<string, unknown> = Record<string, unknown>>(
23
+ text: string,
24
+ values?: readonly unknown[] | Record<string, unknown>
25
+ ): Promise<T[]> {
26
+ if (values != null && !Array.isArray(values)) {
27
+ throw new Error('fromPg adapter does not support named parameter objects; use positional parameter arrays');
28
+ }
29
+ return queryable
30
+ .query(text, values as readonly unknown[])
31
+ .then((result) => result.rows as T[]);
32
+ }
33
+ };
34
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Promise that resolves to the array of rows produced by an SQL query.
3
+ * @template T Shape of each row yielded by the SQL client.
4
+ * @example
5
+ * const rows: SqlQueryRows<{ id: number; name: string }> = client.query('SELECT id, name FROM users');
6
+ */
7
+ export type SqlQueryRows<T> = Promise<T[]>;
8
+
9
+ /**
10
+ * Minimal SQL client interface required by the persistence layer.
11
+ *
12
+ * - Production: adapt this interface to your preferred driver (pg, mysql2, etc.) and normalize the results to `T[]`.
13
+ * - Tests: replace the implementation with a mock, a fixture helper, or an adapter that follows this contract.
14
+ *
15
+ * Connection strategy note:
16
+ * - Prefer a shared client per worker process for better performance.
17
+ * - Do not share a live client across parallel workers without proper synchronization.
18
+ */
19
+ export type SqlClient = {
20
+ query<T extends Record<string, unknown> = Record<string, unknown>>(
21
+ text: string,
22
+ values?: readonly unknown[] | Record<string, unknown>
23
+ ): SqlQueryRows<T>;
24
+ };
@@ -0,0 +1,18 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/infrastructure/persistence`.
3
+ - Defines persistence-layer rules for WebAPI-oriented scaffolds.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - ZTD-specific workflow rules apply here and in the related `src/sql`, `src/catalog`, and `ztd` assets.
8
+ - Persistence adapters MUST keep handwritten SQL, QuerySpecs, and DDL aligned.
9
+ - Repository code MUST rely on explicit contracts and generated/runtime helpers instead of hidden driver behavior.
10
+ - `ZTD_TEST_DATABASE_URL` is the only implicit database owned by `ztd-cli`.
11
+ - Non-ZTD database targets MUST be passed explicitly via `--url` or a complete `--db-*` flag set for inspection work.
12
+ - Migration SQL artifacts MAY be generated here, but applying them remains outside `ztd-cli` ownership.
13
+
14
+ ## PROHIBITED
15
+ - Leaking persistence rules into domain, application, or presentation layers.
16
+
17
+ # Mandatory Workflow
18
+ - Persistence changes MUST run `ztd ztd-config`, relevant tests, and the persistence-focused verification flow.
@@ -0,0 +1,8 @@
1
+ # Persistence Infrastructure
2
+
3
+ This is the primary ZTD-aware layer.
4
+
5
+ - Store SQL assets in `src/sql`.
6
+ - Place QuerySpecs in `src/catalog/specs`.
7
+ - Maintain runtime mapping helpers in `src/catalog/runtime`.
8
+ - Keep DDL in `ztd/ddl`.
@@ -0,0 +1,17 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/infrastructure/persistence/repositories`.
3
+ - Defines repository responsibilities for WebAPI-oriented persistence infrastructure.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Repositories MUST load SQL assets from `src/sql` through shared loader infrastructure.
8
+ - Repository CUD behavior MUST follow contract rules for `RETURNING`, rowCount handling, and explicit unsupported-driver failures.
9
+ - Repositories MUST reference SQL by stable logical keys.
10
+ - Constructors for repositories SHOULD accept an optional telemetry dependency from `src/infrastructure/telemetry/repositoryTelemetry.ts`.
11
+ - Tests MUST cover every public repository method.
12
+
13
+ ## PROHIBITED
14
+ - Inline SQL strings or ad-hoc SQL file path resolution.
15
+
16
+ # Mandatory Workflow
17
+ - Repository changes MUST run tests covering mapping, rowCount behavior, and error surfaces.
@@ -0,0 +1,20 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/infrastructure/persistence/repositories/tables`.
3
+ - Defines table-oriented CRUD repository contract behavior.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - CREATE SQL MUST use identifier-focused `RETURNING` when generated keys are required.
8
+ - CREATE repository methods MUST return identifier-only results by default.
9
+ - UPDATE and DELETE MUST rely on affected-row counts where available.
10
+ - `rowCount === 0` conditions MUST surface explicitly according to contract behavior.
11
+ - Patch contracts MUST distinguish omitted fields from explicit null values.
12
+ - Public repository methods MUST be test-covered for mapping and CUD error behavior.
13
+
14
+ ## PROHIBITED
15
+ - UPDATE/DELETE `RETURNING`-based success emulation.
16
+ - Follow-up SELECT workarounds for CUD verification.
17
+ - Ambiguous patch patterns that hide omitted-vs-null intent.
18
+
19
+ # Mandatory Workflow
20
+ - Table repository changes MUST run tests for affected-row handling and explicit failure surfaces.
@@ -0,0 +1,5 @@
1
+ # Table Repositories
2
+
3
+ Write-focused repositories that execute CRUD SQL from `src/sql`.
4
+
5
+ Accept an optional telemetry hook from `src/infrastructure/telemetry/repositoryTelemetry.ts` and default it through `resolveRepositoryTelemetry(...)` so applications can replace the sink without editing repository internals.
@@ -0,0 +1,16 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/infrastructure/persistence/repositories/views`.
3
+ - Defines read-model repository behavior for complex SELECT-only queries.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Queries in this subtree MUST remain read-only.
8
+ - Read-model DTO validation MUST run at repository/catalog boundaries.
9
+ - Query naming MUST make cardinality assumptions explicit.
10
+
11
+ ## PROHIBITED
12
+ - INSERT/UPDATE/DELETE behavior in this subtree.
13
+ - Hidden write side effects in read-model query paths.
14
+
15
+ # Mandatory Workflow
16
+ - View repository changes MUST run tests for DTO validation and result ordering assumptions.
@@ -0,0 +1,5 @@
1
+ # View Repositories
2
+
3
+ Read-only repositories backed by SELECT SQL in `src/sql`.
4
+
5
+ Accept an optional telemetry hook from `src/infrastructure/telemetry/repositoryTelemetry.ts` and default it through `resolveRepositoryTelemetry(...)` so applications can bridge structured events into their own logging stack.
@@ -0,0 +1,14 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/infrastructure/telemetry`.
3
+ - Defines repository telemetry seams and adapters.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Telemetry hooks MUST remain replaceable by application-owned wiring.
8
+ - Default telemetry behavior MUST stay conservative about query text emission.
9
+
10
+ ## PROHIBITED
11
+ - Making telemetry mandatory for non-persistence layers.
12
+
13
+ # Mandatory Workflow
14
+ - Telemetry changes MUST run the focused scaffold verification tests.
@@ -0,0 +1,66 @@
1
+ import type {
2
+ RepositoryTelemetry,
3
+ RepositoryTelemetryConsoleOptions,
4
+ RepositoryTelemetryEvent,
5
+ } from './types';
6
+
7
+ /**
8
+ * Create a conservative console-backed telemetry hook for repositories.
9
+ *
10
+ * The default policy keeps SQL text disabled so applications opt in before
11
+ * query text is emitted to logs or forwarded to another sink.
12
+ */
13
+ export function createConsoleRepositoryTelemetry(
14
+ options: RepositoryTelemetryConsoleOptions = {},
15
+ ): RepositoryTelemetry {
16
+ const logger = options.logger ?? console;
17
+
18
+ return {
19
+ emit(event: RepositoryTelemetryEvent): void {
20
+ const payload = serializeEvent(event, options.includeSqlText === true);
21
+ if (event.kind === 'query.execute.error') {
22
+ logger.error('[repository-telemetry]', payload);
23
+ return;
24
+ }
25
+
26
+ logger.info('[repository-telemetry]', payload);
27
+ },
28
+ };
29
+ }
30
+
31
+ function serializeEvent(
32
+ event: RepositoryTelemetryEvent,
33
+ includeSqlText: boolean,
34
+ ): Record<string, unknown> {
35
+ const payload: Record<string, unknown> = {
36
+ kind: event.kind,
37
+ timestamp: event.timestamp,
38
+ repositoryName: event.repositoryName,
39
+ methodName: event.methodName,
40
+ };
41
+
42
+ if (event.queryName) {
43
+ payload.queryName = event.queryName;
44
+ }
45
+ if (event.fallback !== undefined) {
46
+ payload.fallback = event.fallback;
47
+ }
48
+
49
+ // Keep SQL text out of default logs so applications make that policy choice.
50
+ if (includeSqlText && event.sqlText) {
51
+ payload.sqlText = event.sqlText;
52
+ }
53
+
54
+ if (event.kind !== 'query.execute.start') {
55
+ payload.durationMs = event.durationMs;
56
+ }
57
+ if (event.kind === 'query.execute.success' && event.rowCount !== undefined) {
58
+ payload.rowCount = event.rowCount;
59
+ }
60
+ if (event.kind === 'query.execute.error') {
61
+ payload.errorName = event.errorName;
62
+ payload.errorMessage = event.errorMessage;
63
+ }
64
+
65
+ return payload;
66
+ }
@@ -0,0 +1,26 @@
1
+ import { createConsoleRepositoryTelemetry } from './consoleRepositoryTelemetry';
2
+ import type { RepositoryTelemetry } from './types';
3
+
4
+ export type {
5
+ RepositoryTelemetry,
6
+ RepositoryTelemetryConsoleOptions,
7
+ RepositoryTelemetryContext,
8
+ RepositoryTelemetryEvent,
9
+ RepositoryTelemetryEventKind,
10
+ } from './types';
11
+
12
+ export { createConsoleRepositoryTelemetry } from './consoleRepositoryTelemetry';
13
+
14
+ export const defaultRepositoryTelemetry = createConsoleRepositoryTelemetry();
15
+
16
+ /**
17
+ * Resolve the repository telemetry hook that application code wants to use.
18
+ *
19
+ * Repository constructors can accept an optional telemetry dependency and call
20
+ * this helper so the default console hook works without extra setup.
21
+ */
22
+ export function resolveRepositoryTelemetry(
23
+ telemetry?: RepositoryTelemetry,
24
+ ): RepositoryTelemetry {
25
+ return telemetry ?? defaultRepositoryTelemetry;
26
+ }
@@ -0,0 +1,48 @@
1
+ export type RepositoryTelemetryEventKind =
2
+ | 'query.execute.start'
3
+ | 'query.execute.success'
4
+ | 'query.execute.error';
5
+
6
+ export interface RepositoryTelemetryContext {
7
+ repositoryName: string;
8
+ methodName: string;
9
+ queryName?: string;
10
+ sqlText?: string;
11
+ fallback?: boolean;
12
+ }
13
+
14
+ interface RepositoryTelemetryEventBase extends RepositoryTelemetryContext {
15
+ kind: RepositoryTelemetryEventKind;
16
+ timestamp: string;
17
+ }
18
+
19
+ export interface RepositoryQueryExecuteStartEvent extends RepositoryTelemetryEventBase {
20
+ kind: 'query.execute.start';
21
+ }
22
+
23
+ export interface RepositoryQueryExecuteSuccessEvent extends RepositoryTelemetryEventBase {
24
+ kind: 'query.execute.success';
25
+ durationMs: number;
26
+ rowCount?: number;
27
+ }
28
+
29
+ export interface RepositoryQueryExecuteErrorEvent extends RepositoryTelemetryEventBase {
30
+ kind: 'query.execute.error';
31
+ durationMs: number;
32
+ errorName: string;
33
+ errorMessage: string;
34
+ }
35
+
36
+ export type RepositoryTelemetryEvent =
37
+ | RepositoryQueryExecuteStartEvent
38
+ | RepositoryQueryExecuteSuccessEvent
39
+ | RepositoryQueryExecuteErrorEvent;
40
+
41
+ export interface RepositoryTelemetry {
42
+ emit(event: RepositoryTelemetryEvent): void | Promise<void>;
43
+ }
44
+
45
+ export interface RepositoryTelemetryConsoleOptions {
46
+ includeSqlText?: boolean;
47
+ logger?: Pick<Console, 'info' | 'error'>;
48
+ }
@@ -0,0 +1,25 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/jobs`.
3
+ - Defines contract rules for procedural and batch SQL job code.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Jobs MUST declare explicit transaction boundaries.
8
+ - Jobs MUST emit start/end operational events or logs.
9
+ - Job tests MUST validate observable outcomes.
10
+
11
+ ## ALLOWED
12
+ - Jobs MAY execute multiple SQL statements, including temporary-table workflows.
13
+ - Heavy jobs MAY split verification across integration and focused fixture tests.
14
+
15
+ ## PROHIBITED
16
+ - Coupling job logic to test-only helpers.
17
+
18
+ # Mandatory Workflow
19
+ - Job changes MUST run integration-style tests for affected job paths.
20
+
21
+ # Hygiene
22
+ - Job logic MUST remain idempotent for rerun safety.
23
+
24
+ # References
25
+ - Parent runtime policy: [../AGENTS.md](../AGENTS.md)
@@ -0,0 +1,3 @@
1
+ # Jobs
2
+
3
+ Job runners that orchestrate repository or SQL workflows.
@@ -0,0 +1 @@
1
+ export * from '@rawsql-ts/sql-contract';
@@ -0,0 +1,15 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/presentation`.
3
+ - Defines transport adapters for WebAPI-oriented scaffolds.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - Presentation code MUST translate external input/output without embedding domain or persistence rules.
8
+ - Request/response contracts MUST remain explicit.
9
+
10
+ ## PROHIBITED
11
+ - Direct SQL, DDL, or QuerySpec ownership.
12
+ - Hidden business rules in controllers or handlers.
13
+
14
+ # Mandatory Workflow
15
+ - Presentation changes MUST run tests for request parsing and response shaping.
@@ -0,0 +1,15 @@
1
+ # Package Scope
2
+ - Applies to `packages/ztd-cli/templates/src/presentation/http`.
3
+ - Defines HTTP-specific transport behavior for WebAPI-oriented scaffolds.
4
+
5
+ # Policy
6
+ ## REQUIRED
7
+ - HTTP adapters MUST translate transport concerns into application-layer inputs and outputs.
8
+ - Handler code MUST keep status codes, headers, and serialization explicit.
9
+
10
+ ## PROHIBITED
11
+ - Direct SQL execution.
12
+ - Embedding persistence-specific retries or ZTD workflow rules in handlers.
13
+
14
+ # Mandatory Workflow
15
+ - HTTP adapter changes MUST run transport-focused tests.
@@ -0,0 +1,6 @@
1
+ # HTTP Presentation
2
+
3
+ HTTP handlers, controllers, and transport mapping live here.
4
+
5
+ - Keep framework-specific code here.
6
+ - Delegate use-case orchestration to `src/application`.