ts-procedures 6.0.2 → 6.2.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 (199) hide show
  1. package/agent_config/bin/setup.mjs +2 -2
  2. package/agent_config/claude-code/skills/ts-procedures/SKILL.md +2 -0
  3. package/agent_config/claude-code/skills/ts-procedures/api-reference.md +2 -0
  4. package/agent_config/claude-code/skills/ts-procedures-kotlin/SKILL.md +106 -0
  5. package/agent_config/claude-code/skills/ts-procedures-swift/SKILL.md +119 -0
  6. package/agent_config/copilot/copilot-instructions.md +3 -0
  7. package/agent_config/cursor/cursorrules +3 -0
  8. package/agent_config/lib/install-claude.mjs +1 -1
  9. package/build/codegen/bin/cli.d.ts +39 -0
  10. package/build/codegen/bin/cli.js +164 -0
  11. package/build/codegen/bin/cli.js.map +1 -1
  12. package/build/codegen/bin/cli.test.js +180 -1
  13. package/build/codegen/bin/cli.test.js.map +1 -1
  14. package/build/codegen/index.d.ts +36 -0
  15. package/build/codegen/index.js +8 -0
  16. package/build/codegen/index.js.map +1 -1
  17. package/build/codegen/pipeline.d.ts +22 -4
  18. package/build/codegen/pipeline.js +44 -86
  19. package/build/codegen/pipeline.js.map +1 -1
  20. package/build/codegen/pipeline.test.js +162 -0
  21. package/build/codegen/pipeline.test.js.map +1 -1
  22. package/build/codegen/targets/_shared/error-schemas.d.ts +10 -0
  23. package/build/codegen/targets/_shared/error-schemas.js +17 -0
  24. package/build/codegen/targets/_shared/error-schemas.js.map +1 -0
  25. package/build/codegen/targets/_shared/error-schemas.test.d.ts +1 -0
  26. package/build/codegen/targets/_shared/error-schemas.test.js +38 -0
  27. package/build/codegen/targets/_shared/error-schemas.test.js.map +1 -0
  28. package/build/codegen/targets/_shared/indent.d.ts +6 -0
  29. package/build/codegen/targets/_shared/indent.js +13 -0
  30. package/build/codegen/targets/_shared/indent.js.map +1 -0
  31. package/build/codegen/targets/_shared/indent.test.d.ts +1 -0
  32. package/build/codegen/targets/_shared/indent.test.js +21 -0
  33. package/build/codegen/targets/_shared/indent.test.js.map +1 -0
  34. package/build/codegen/targets/_shared/pascal-case.d.ts +6 -0
  35. package/build/codegen/targets/_shared/pascal-case.js +13 -0
  36. package/build/codegen/targets/_shared/pascal-case.js.map +1 -0
  37. package/build/codegen/targets/_shared/pascal-case.test.d.ts +1 -0
  38. package/build/codegen/targets/_shared/pascal-case.test.js +25 -0
  39. package/build/codegen/targets/_shared/pascal-case.test.js.map +1 -0
  40. package/build/codegen/targets/_shared/path-utils.d.ts +12 -0
  41. package/build/codegen/targets/_shared/path-utils.js +20 -0
  42. package/build/codegen/targets/_shared/path-utils.js.map +1 -0
  43. package/build/codegen/targets/_shared/path-utils.test.d.ts +1 -0
  44. package/build/codegen/targets/_shared/path-utils.test.js +42 -0
  45. package/build/codegen/targets/_shared/path-utils.test.js.map +1 -0
  46. package/build/codegen/targets/_shared/pick-defined.d.ts +11 -0
  47. package/build/codegen/targets/_shared/pick-defined.js +21 -0
  48. package/build/codegen/targets/_shared/pick-defined.js.map +1 -0
  49. package/build/codegen/targets/_shared/pick-defined.test.d.ts +1 -0
  50. package/build/codegen/targets/_shared/pick-defined.test.js +25 -0
  51. package/build/codegen/targets/_shared/pick-defined.test.js.map +1 -0
  52. package/build/codegen/targets/_shared/route-slots.d.ts +17 -0
  53. package/build/codegen/targets/_shared/route-slots.js +17 -0
  54. package/build/codegen/targets/_shared/route-slots.js.map +1 -0
  55. package/build/codegen/targets/_shared/route-slots.test.d.ts +1 -0
  56. package/build/codegen/targets/_shared/route-slots.test.js +43 -0
  57. package/build/codegen/targets/_shared/route-slots.test.js.map +1 -0
  58. package/build/codegen/targets/_shared/target-run.d.ts +27 -0
  59. package/build/codegen/targets/_shared/target-run.js +2 -0
  60. package/build/codegen/targets/_shared/target-run.js.map +1 -0
  61. package/build/codegen/targets/_shared/write-files.d.ts +24 -0
  62. package/build/codegen/targets/_shared/write-files.js +35 -0
  63. package/build/codegen/targets/_shared/write-files.js.map +1 -0
  64. package/build/codegen/targets/_shared/write-files.test.d.ts +1 -0
  65. package/build/codegen/targets/_shared/write-files.test.js +79 -0
  66. package/build/codegen/targets/_shared/write-files.test.js.map +1 -0
  67. package/build/codegen/targets/kotlin/ajsc-adapter.d.ts +6 -4
  68. package/build/codegen/targets/kotlin/ajsc-adapter.js +12 -7
  69. package/build/codegen/targets/kotlin/ajsc-adapter.js.map +1 -1
  70. package/build/codegen/targets/kotlin/ajsc-adapter.test.js +20 -2
  71. package/build/codegen/targets/kotlin/ajsc-adapter.test.js.map +1 -1
  72. package/build/codegen/targets/kotlin/e2e-compile.test.js +41 -9
  73. package/build/codegen/targets/kotlin/e2e-compile.test.js.map +1 -1
  74. package/build/codegen/targets/kotlin/emit-route-kotlin.d.ts +6 -2
  75. package/build/codegen/targets/kotlin/emit-route-kotlin.js +18 -28
  76. package/build/codegen/targets/kotlin/emit-route-kotlin.js.map +1 -1
  77. package/build/codegen/targets/kotlin/emit-route-kotlin.test.js +120 -1
  78. package/build/codegen/targets/kotlin/emit-route-kotlin.test.js.map +1 -1
  79. package/build/codegen/targets/kotlin/emit-scope-kotlin.d.ts +4 -1
  80. package/build/codegen/targets/kotlin/emit-scope-kotlin.js +12 -11
  81. package/build/codegen/targets/kotlin/emit-scope-kotlin.js.map +1 -1
  82. package/build/codegen/targets/kotlin/emit-scope-kotlin.test.js +39 -0
  83. package/build/codegen/targets/kotlin/emit-scope-kotlin.test.js.map +1 -1
  84. package/build/codegen/targets/kotlin/format-kotlin.d.ts +0 -1
  85. package/build/codegen/targets/kotlin/format-kotlin.js +0 -7
  86. package/build/codegen/targets/kotlin/format-kotlin.js.map +1 -1
  87. package/build/codegen/targets/kotlin/format-kotlin.test.js +1 -8
  88. package/build/codegen/targets/kotlin/format-kotlin.test.js.map +1 -1
  89. package/build/codegen/targets/kotlin/integration.test.js +27 -10
  90. package/build/codegen/targets/kotlin/integration.test.js.map +1 -1
  91. package/build/codegen/targets/kotlin/probe-unsupported-unions.test.d.ts +1 -0
  92. package/build/codegen/targets/kotlin/probe-unsupported-unions.test.js +50 -0
  93. package/build/codegen/targets/kotlin/probe-unsupported-unions.test.js.map +1 -0
  94. package/build/codegen/targets/kotlin/run.d.ts +11 -0
  95. package/build/codegen/targets/kotlin/run.js +51 -0
  96. package/build/codegen/targets/kotlin/run.js.map +1 -0
  97. package/build/codegen/targets/swift/access-level.test.d.ts +1 -0
  98. package/build/codegen/targets/swift/access-level.test.js +98 -0
  99. package/build/codegen/targets/swift/access-level.test.js.map +1 -0
  100. package/build/codegen/targets/swift/ajsc-adapter.d.ts +27 -0
  101. package/build/codegen/targets/swift/ajsc-adapter.js +38 -0
  102. package/build/codegen/targets/swift/ajsc-adapter.js.map +1 -0
  103. package/build/codegen/targets/swift/ajsc-adapter.test.d.ts +1 -0
  104. package/build/codegen/targets/swift/ajsc-adapter.test.js +37 -0
  105. package/build/codegen/targets/swift/ajsc-adapter.test.js.map +1 -0
  106. package/build/codegen/targets/swift/e2e-compile.test.d.ts +1 -0
  107. package/build/codegen/targets/swift/e2e-compile.test.js +57 -0
  108. package/build/codegen/targets/swift/e2e-compile.test.js.map +1 -0
  109. package/build/codegen/targets/swift/emit-route-swift.d.ts +15 -0
  110. package/build/codegen/targets/swift/emit-route-swift.js +64 -0
  111. package/build/codegen/targets/swift/emit-route-swift.js.map +1 -0
  112. package/build/codegen/targets/swift/emit-route-swift.test.d.ts +1 -0
  113. package/build/codegen/targets/swift/emit-route-swift.test.js +258 -0
  114. package/build/codegen/targets/swift/emit-route-swift.test.js.map +1 -0
  115. package/build/codegen/targets/swift/emit-scope-swift.d.ts +13 -0
  116. package/build/codegen/targets/swift/emit-scope-swift.js +36 -0
  117. package/build/codegen/targets/swift/emit-scope-swift.js.map +1 -0
  118. package/build/codegen/targets/swift/emit-scope-swift.test.d.ts +1 -0
  119. package/build/codegen/targets/swift/emit-scope-swift.test.js +136 -0
  120. package/build/codegen/targets/swift/emit-scope-swift.test.js.map +1 -0
  121. package/build/codegen/targets/swift/format-swift.d.ts +2 -0
  122. package/build/codegen/targets/swift/format-swift.js +10 -0
  123. package/build/codegen/targets/swift/format-swift.js.map +1 -0
  124. package/build/codegen/targets/swift/format-swift.test.d.ts +1 -0
  125. package/build/codegen/targets/swift/format-swift.test.js +14 -0
  126. package/build/codegen/targets/swift/format-swift.test.js.map +1 -0
  127. package/build/codegen/targets/swift/integration.test.d.ts +1 -0
  128. package/build/codegen/targets/swift/integration.test.js +53 -0
  129. package/build/codegen/targets/swift/integration.test.js.map +1 -0
  130. package/build/codegen/targets/swift/run.d.ts +11 -0
  131. package/build/codegen/targets/swift/run.js +47 -0
  132. package/build/codegen/targets/swift/run.js.map +1 -0
  133. package/build/codegen/targets/ts/run.d.ts +4 -0
  134. package/build/codegen/targets/ts/run.js +86 -0
  135. package/build/codegen/targets/ts/run.js.map +1 -0
  136. package/build/codegen/test-helpers/golden.d.ts +15 -0
  137. package/build/codegen/test-helpers/golden.js +30 -0
  138. package/build/codegen/test-helpers/golden.js.map +1 -0
  139. package/build/codegen/test-helpers/golden.test.d.ts +1 -0
  140. package/build/codegen/test-helpers/golden.test.js +76 -0
  141. package/build/codegen/test-helpers/golden.test.js.map +1 -0
  142. package/docs/codegen-kotlin.md +176 -0
  143. package/docs/codegen-swift.md +314 -0
  144. package/docs/superpowers/plans/2026-04-25-ajsc-v7-kotlin-polish.md +1993 -0
  145. package/docs/superpowers/specs/2026-04-24-kotlin-swift-codegen-design.md +1 -1
  146. package/docs/superpowers/specs/2026-04-25-ajsc-v7-kotlin-polish-design.md +314 -0
  147. package/docs/superpowers/specs/2026-04-25-swift-codegen-design.md +264 -0
  148. package/package.json +2 -2
  149. package/src/codegen/__fixtures__/users-envelope.json +144 -0
  150. package/src/codegen/bin/cli.test.ts +200 -1
  151. package/src/codegen/bin/cli.ts +187 -0
  152. package/src/codegen/index.ts +50 -0
  153. package/src/codegen/pipeline.test.ts +175 -0
  154. package/src/codegen/pipeline.ts +58 -101
  155. package/src/codegen/targets/_shared/error-schemas.test.ts +42 -0
  156. package/src/codegen/targets/_shared/error-schemas.ts +17 -0
  157. package/src/codegen/targets/_shared/indent.test.ts +25 -0
  158. package/src/codegen/targets/_shared/indent.ts +12 -0
  159. package/src/codegen/targets/_shared/pascal-case.test.ts +30 -0
  160. package/src/codegen/targets/_shared/pascal-case.ts +12 -0
  161. package/src/codegen/targets/_shared/path-utils.test.ts +51 -0
  162. package/src/codegen/targets/_shared/path-utils.ts +21 -0
  163. package/src/codegen/targets/_shared/pick-defined.test.ts +48 -0
  164. package/src/codegen/targets/_shared/pick-defined.ts +23 -0
  165. package/src/codegen/targets/_shared/route-slots.test.ts +55 -0
  166. package/src/codegen/targets/_shared/route-slots.ts +32 -0
  167. package/src/codegen/targets/_shared/target-run.ts +28 -0
  168. package/src/codegen/targets/_shared/write-files.test.ts +110 -0
  169. package/src/codegen/targets/_shared/write-files.ts +53 -0
  170. package/src/codegen/targets/kotlin/__fixtures__/users-golden.kt +121 -0
  171. package/src/codegen/targets/kotlin/__snapshots__/probe-unsupported-unions.test.ts.snap +27 -0
  172. package/src/codegen/targets/kotlin/ajsc-adapter.test.ts +47 -0
  173. package/src/codegen/targets/kotlin/ajsc-adapter.ts +66 -0
  174. package/src/codegen/targets/kotlin/e2e-compile.test.ts +86 -0
  175. package/src/codegen/targets/kotlin/emit-route-kotlin.test.ts +239 -0
  176. package/src/codegen/targets/kotlin/emit-route-kotlin.ts +89 -0
  177. package/src/codegen/targets/kotlin/emit-scope-kotlin.test.ts +112 -0
  178. package/src/codegen/targets/kotlin/emit-scope-kotlin.ts +60 -0
  179. package/src/codegen/targets/kotlin/format-kotlin.test.ts +26 -0
  180. package/src/codegen/targets/kotlin/format-kotlin.ts +13 -0
  181. package/src/codegen/targets/kotlin/integration.test.ts +77 -0
  182. package/src/codegen/targets/kotlin/probe-unsupported-unions.test.ts +64 -0
  183. package/src/codegen/targets/kotlin/run.ts +78 -0
  184. package/src/codegen/targets/swift/__fixtures__/users-golden.swift +123 -0
  185. package/src/codegen/targets/swift/access-level.test.ts +108 -0
  186. package/src/codegen/targets/swift/ajsc-adapter.test.ts +47 -0
  187. package/src/codegen/targets/swift/ajsc-adapter.ts +67 -0
  188. package/src/codegen/targets/swift/e2e-compile.test.ts +66 -0
  189. package/src/codegen/targets/swift/emit-route-swift.test.ts +300 -0
  190. package/src/codegen/targets/swift/emit-route-swift.ts +90 -0
  191. package/src/codegen/targets/swift/emit-scope-swift.test.ts +164 -0
  192. package/src/codegen/targets/swift/emit-scope-swift.ts +59 -0
  193. package/src/codegen/targets/swift/format-swift.test.ts +23 -0
  194. package/src/codegen/targets/swift/format-swift.ts +9 -0
  195. package/src/codegen/targets/swift/integration.test.ts +80 -0
  196. package/src/codegen/targets/swift/run.ts +74 -0
  197. package/src/codegen/targets/ts/run.ts +117 -0
  198. package/src/codegen/test-helpers/golden.test.ts +80 -0
  199. package/src/codegen/test-helpers/golden.ts +34 -0
@@ -0,0 +1,86 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { execFileSync, execSync } from 'node:child_process'
3
+ import { mkdtempSync, writeFileSync, readFileSync, readdirSync, existsSync } from 'node:fs'
4
+ import { tmpdir } from 'node:os'
5
+ import { dirname, join } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { runPipeline } from '../../pipeline.js'
8
+ import { resolveProductionKotlinEmitter } from './ajsc-adapter.js'
9
+
10
+ const __filename = fileURLToPath(import.meta.url)
11
+ const __dirname = dirname(__filename)
12
+
13
+ function kotlincAvailable(): boolean {
14
+ try {
15
+ execSync('kotlinc -version', { stdio: 'ignore' })
16
+ return true
17
+ } catch {
18
+ return false
19
+ }
20
+ }
21
+
22
+ const RUN = process.env.TS_PROCEDURES_KOTLIN_E2E === '1'
23
+
24
+ /**
25
+ * E2E: real ajsc → real .kt output → real kotlinc compile.
26
+ *
27
+ * Gated on (a) `kotlinc` on PATH and (b) opt-in via env var so default
28
+ * `npm test` runs stay green for contributors without the toolchain.
29
+ *
30
+ * **Classpath setup (one-time, local):**
31
+ *
32
+ * Download kotlinx-serialization jars (matching versions, e.g. 1.6.3) from
33
+ * Maven Central or a local Gradle/Maven cache. The classpath value is a
34
+ * `:`-separated list (`;` on Windows). Concrete example:
35
+ *
36
+ * export TS_PROCEDURES_KOTLIN_E2E_CLASSPATH="\
37
+ * $HOME/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-serialization-json-jvm/1.6.3/<hash>/kotlinx-serialization-json-jvm-1.6.3.jar:\
38
+ * $HOME/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-serialization-core-jvm/1.6.3/<hash>/kotlinx-serialization-core-jvm-1.6.3.jar"
39
+ *
40
+ * If the env var is unset the compile uses kotlinc's default classpath which
41
+ * lacks the kotlinx jars and fails — that's the expected mode when checking
42
+ * gating works.
43
+ */
44
+ describe('kotlin codegen — kotlinc compile (gated)', () => {
45
+ it.skipIf(!kotlincAvailable() || !RUN)(
46
+ 'compiles generated output without errors',
47
+ async () => {
48
+ const emitter = await resolveProductionKotlinEmitter()
49
+ const envelope = JSON.parse(
50
+ readFileSync(join(__dirname, '../../__fixtures__/users-envelope.json'), 'utf8'),
51
+ )
52
+ const files = await runPipeline({
53
+ envelope,
54
+ outDir: 'out',
55
+ dryRun: true,
56
+ target: 'kotlin',
57
+ kotlinPackage: 'com.example.api',
58
+ kotlinEmitter: emitter,
59
+ })
60
+ const dir = mkdtempSync(join(tmpdir(), 'tsp-kotlin-e2e-'))
61
+ for (const f of files) {
62
+ writeFileSync(join(dir, f.path.split('/').pop()!), f.code)
63
+ }
64
+
65
+ // Expand the source glob in Node and pass kotlinc args as an array so
66
+ // the shell never sees user-controlled input. The classpath env var is
67
+ // only forwarded as a single -classpath argument; even a value with
68
+ // shell metachars cannot escape into command parsing.
69
+ const ktFiles = readdirSync(dir)
70
+ .filter((name) => name.endsWith('.kt'))
71
+ .map((name) => join(dir, name))
72
+
73
+ const outJar = join(dir, 'out.jar')
74
+ const cp = process.env.TS_PROCEDURES_KOTLIN_E2E_CLASSPATH
75
+ const args: string[] = []
76
+ if (cp != null && cp.length > 0) {
77
+ args.push('-classpath', cp)
78
+ }
79
+ args.push(...ktFiles, '-d', outJar)
80
+
81
+ execFileSync('kotlinc', args, { stdio: 'inherit' })
82
+
83
+ expect(existsSync(outJar)).toBe(true)
84
+ },
85
+ )
86
+ })
@@ -0,0 +1,239 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { AnyHttpRouteDoc } from '../../../implementations/types.js'
3
+ import { emitKotlinRoute } from './emit-route-kotlin.js'
4
+ import { createStubKotlinEmitter, type KotlinEmitOptions, type KotlinEmitResult } from './ajsc-adapter.js'
5
+
6
+ const ok = (code: string, rootTypeName: string): KotlinEmitResult => ({
7
+ code,
8
+ rootTypeName,
9
+ extractedTypeNames: [],
10
+ imports: ['kotlinx.serialization.Serializable'],
11
+ })
12
+
13
+ const noErrors = new Map<string, unknown>()
14
+
15
+ interface CapturedCall { schema: unknown; opts: KotlinEmitOptions }
16
+
17
+ function makeSpyEmitter(results: Record<string, KotlinEmitResult>) {
18
+ const calls: CapturedCall[] = []
19
+ const emitter = {
20
+ emit(schema: unknown, opts: KotlinEmitOptions) {
21
+ calls.push({ schema, opts })
22
+ const r = results[opts.rootTypeName]
23
+ if (r == null) throw new Error(`No stubbed result for "${opts.rootTypeName}"`)
24
+ return r
25
+ },
26
+ }
27
+ return { emitter, calls }
28
+ }
29
+
30
+ describe('emitKotlinRoute', () => {
31
+ it('emits an api-kind route with path params and a response', () => {
32
+ const route: AnyHttpRouteDoc = {
33
+ kind: 'api',
34
+ name: 'GetUser',
35
+ method: 'GET',
36
+ fullPath: '/users/:id',
37
+ schema: {
38
+ input: {
39
+ pathParams: { type: 'object' },
40
+ },
41
+ returnType: { type: 'object' },
42
+ },
43
+ errors: [],
44
+ } as unknown as AnyHttpRouteDoc
45
+
46
+ const emitter = createStubKotlinEmitter({
47
+ PathParams: ok('@Serializable data class PathParams(val id: String)', 'PathParams'),
48
+ Response: ok('@Serializable data class Response(val id: String, val name: String)', 'Response'),
49
+ })
50
+
51
+ const result = emitKotlinRoute(route, emitter, noErrors)
52
+
53
+ expect(result.imports).toContain('kotlinx.serialization.Serializable')
54
+ expect(result.code).toContain('const val method = "GET"')
55
+ expect(result.code).toContain('const val pathTemplate = "/users/{id}"')
56
+ expect(result.code).toContain('fun path(p: PathParams): String = "/users/${p.id}"')
57
+ expect(result.code).toContain('@Serializable data class PathParams(val id: String)')
58
+ expect(result.code).toContain('@Serializable data class Response(val id: String, val name: String)')
59
+ })
60
+
61
+ it('emits a route with no path params using a path constant', () => {
62
+ const route = {
63
+ kind: 'api',
64
+ name: 'CreateUser',
65
+ method: 'POST',
66
+ fullPath: '/users',
67
+ schema: { input: { body: { type: 'object' } }, returnType: { type: 'object' } },
68
+ errors: [],
69
+ } as unknown as AnyHttpRouteDoc
70
+
71
+ const emitter = createStubKotlinEmitter({
72
+ Body: ok('@Serializable data class Body(val name: String)', 'Body'),
73
+ Response: ok('@Serializable data class Response(val id: String)', 'Response'),
74
+ })
75
+
76
+ const result = emitKotlinRoute(route, emitter, noErrors)
77
+ expect(result.code).toContain('const val path = "/users"')
78
+ expect(result.code).not.toContain('fun path(')
79
+ })
80
+
81
+ it('emits an Errors namespace for routes whose error keys have schemas in the envelope', () => {
82
+ const route = {
83
+ kind: 'api',
84
+ name: 'GetUser',
85
+ method: 'GET',
86
+ fullPath: '/users/:id',
87
+ schema: { input: { pathParams: { type: 'object' } }, returnType: { type: 'object' } },
88
+ errors: ['NotFound'],
89
+ } as unknown as AnyHttpRouteDoc
90
+
91
+ const emitter = createStubKotlinEmitter({
92
+ PathParams: ok('@Serializable data class PathParams(val id: String)', 'PathParams'),
93
+ Response: ok('@Serializable data class Response(val id: String)', 'Response'),
94
+ NotFound: ok('@Serializable data class NotFound(val name: String, val message: String)', 'NotFound'),
95
+ })
96
+
97
+ const errorSchemas = new Map<string, unknown>([['NotFound', { type: 'object' }]])
98
+ const result = emitKotlinRoute(route, emitter, errorSchemas)
99
+ expect(result.code).toContain('object Errors {')
100
+ expect(result.code).toContain('@Serializable data class NotFound(val name: String, val message: String)')
101
+ })
102
+
103
+ it('silently skips error keys with no schema in the envelope map', () => {
104
+ const route = {
105
+ kind: 'api', name: 'GetUser', method: 'GET', fullPath: '/users',
106
+ schema: {}, errors: ['UnknownTaxonomyKey'],
107
+ } as unknown as AnyHttpRouteDoc
108
+ const result = emitKotlinRoute(route, createStubKotlinEmitter({}), new Map())
109
+ expect(result.code).not.toContain('object Errors {')
110
+ })
111
+
112
+ it('returns skipped:true for stream routes', () => {
113
+ const route = { kind: 'stream', name: 'WatchUsers', method: 'GET', path: '/users/stream', schema: {}, errors: [] } as unknown as AnyHttpRouteDoc
114
+ const result = emitKotlinRoute(route, createStubKotlinEmitter({}), noErrors)
115
+ expect(result.code).toBe('')
116
+ expect(result.skipped).toBe(true)
117
+ })
118
+
119
+ it('passes inlineTypes:true plus serializer/unsupportedUnions to every slot emit', () => {
120
+ const route = {
121
+ kind: 'api',
122
+ name: 'GetUser',
123
+ method: 'GET',
124
+ fullPath: '/users/:id',
125
+ schema: {
126
+ input: { pathParams: { type: 'object' } },
127
+ returnType: { type: 'object' },
128
+ },
129
+ errors: ['NotFound'],
130
+ } as unknown as AnyHttpRouteDoc
131
+
132
+ const { emitter, calls } = makeSpyEmitter({
133
+ PathParams: ok('@Serializable data class PathParams(val id: String)', 'PathParams'),
134
+ Response: ok('@Serializable data class Response(val id: String)', 'Response'),
135
+ NotFound: ok('@Serializable data class NotFound(val message: String)', 'NotFound'),
136
+ })
137
+
138
+ emitKotlinRoute(route, emitter, new Map([['NotFound', { type: 'object' }]]), {
139
+ serializer: 'none',
140
+ unsupportedUnions: 'fallback',
141
+ })
142
+
143
+ // 3 emits: PathParams, Response, NotFound
144
+ expect(calls.length).toBe(3)
145
+ for (const c of calls) {
146
+ expect(c.opts.inlineTypes).toBe(true)
147
+ expect(c.opts.serializer).toBe('none')
148
+ expect(c.opts.unsupportedUnions).toBe('fallback')
149
+ }
150
+ })
151
+
152
+ it('preserves slot order: pathParams → query → body → response → errors', () => {
153
+ const route = {
154
+ kind: 'api',
155
+ name: 'X',
156
+ method: 'POST',
157
+ fullPath: '/x/:id',
158
+ schema: {
159
+ input: {
160
+ pathParams: { type: 'object' },
161
+ query: { type: 'object' },
162
+ body: { type: 'object' },
163
+ },
164
+ returnType: { type: 'object' },
165
+ },
166
+ errors: ['Z'],
167
+ } as unknown as AnyHttpRouteDoc
168
+
169
+ const { emitter, calls } = makeSpyEmitter({
170
+ PathParams: ok('a', 'PathParams'),
171
+ Query: ok('b', 'Query'),
172
+ Body: ok('c', 'Body'),
173
+ Response: ok('d', 'Response'),
174
+ Z: ok('e', 'Z'),
175
+ })
176
+
177
+ emitKotlinRoute(route, emitter, new Map([['Z', { type: 'object' }]]), {})
178
+
179
+ expect(calls.map((c) => c.opts.rootTypeName)).toEqual([
180
+ 'PathParams', 'Query', 'Body', 'Response', 'Z',
181
+ ])
182
+ })
183
+
184
+ it('threads passthrough opts (arrayItemNaming/depluralize/uncountableWords) verbatim', () => {
185
+ const route = {
186
+ kind: 'api',
187
+ name: 'X',
188
+ method: 'GET',
189
+ fullPath: '/x',
190
+ schema: { returnType: { type: 'object' } },
191
+ errors: [],
192
+ } as unknown as AnyHttpRouteDoc
193
+
194
+ const { emitter, calls } = makeSpyEmitter({
195
+ Response: ok('@Serializable data class Response(val ok: Boolean)', 'Response'),
196
+ })
197
+
198
+ emitKotlinRoute(route, emitter, new Map(), {
199
+ arrayItemNaming: false,
200
+ depluralize: true,
201
+ uncountableWords: ['data', 'metadata'],
202
+ })
203
+
204
+ expect(calls).toHaveLength(1)
205
+ expect(calls[0]!.opts.arrayItemNaming).toBe(false)
206
+ expect(calls[0]!.opts.depluralize).toBe(true)
207
+ expect(calls[0]!.opts.uncountableWords).toEqual(['data', 'metadata'])
208
+ })
209
+
210
+ it('does not include passthrough keys when caller omits them', () => {
211
+ const route = {
212
+ kind: 'api',
213
+ name: 'X',
214
+ method: 'GET',
215
+ fullPath: '/x',
216
+ schema: { returnType: { type: 'object' } },
217
+ errors: [],
218
+ } as unknown as AnyHttpRouteDoc
219
+
220
+ const { emitter, calls } = makeSpyEmitter({
221
+ Response: ok('@Serializable data class Response(val ok: Boolean)', 'Response'),
222
+ })
223
+
224
+ emitKotlinRoute(route, emitter, new Map(), {})
225
+
226
+ expect(calls).toHaveLength(1)
227
+ // Conditional-spread invariant: undefined opts must NOT be forwarded as keys
228
+ // (otherwise ajsc would receive `{ arrayItemNaming: undefined }` etc, which
229
+ // could shadow ajsc-side defaults).
230
+ expect('arrayItemNaming' in calls[0]!.opts).toBe(false)
231
+ expect('depluralize' in calls[0]!.opts).toBe(false)
232
+ expect('uncountableWords' in calls[0]!.opts).toBe(false)
233
+ // serializer / unsupportedUnions same invariant
234
+ expect('serializer' in calls[0]!.opts).toBe(false)
235
+ expect('unsupportedUnions' in calls[0]!.opts).toBe(false)
236
+ // inlineTypes is always set
237
+ expect(calls[0]!.opts.inlineTypes).toBe(true)
238
+ })
239
+ })
@@ -0,0 +1,89 @@
1
+ import type { AnyHttpRouteDoc } from '../../../implementations/types.js'
2
+ import type { KotlinEmitter, KotlinEmitOptions } from './ajsc-adapter.js'
3
+ import { indent } from '../_shared/indent.js'
4
+ import { pickDefined } from '../_shared/pick-defined.js'
5
+ import { toBracePath, pathParamNames } from '../_shared/path-utils.js'
6
+ import { extractRouteSlots } from '../_shared/route-slots.js'
7
+
8
+ export interface EmitRouteResult {
9
+ /** Inner body of the `object RouteName { ... }` block — already indented one level. */
10
+ code: string
11
+ /** Imports collected from every ajsc emit + any helpers this route used. */
12
+ imports: string[]
13
+ /** Outer route name used as the `object RouteName` identifier. */
14
+ routeName: string
15
+ /** True when the route was a stream (out-of-scope). Caller logs once. */
16
+ skipped?: boolean
17
+ }
18
+
19
+ /** Subset of KotlinEmitOptions threaded by the pipeline; per-call rootTypeName is set inside. */
20
+ export type EmitRouteOpts = Omit<KotlinEmitOptions, 'rootTypeName' | 'inlineTypes'>
21
+
22
+ function buildPathFn(bracePath: string, params: string[]): string {
23
+ if (params.length === 0) return `const val path = "${bracePath}"`
24
+ let body = bracePath
25
+ for (const name of params) body = body.replace(`{${name}}`, `\${p.${name}}`)
26
+ return `fun path(p: PathParams): String = "${body}"`
27
+ }
28
+
29
+ function emitOptsFor(rootTypeName: string, routeOpts: EmitRouteOpts): KotlinEmitOptions {
30
+ const PASSTHROUGH_KEYS = ['serializer', 'unsupportedUnions', 'arrayItemNaming', 'depluralize', 'uncountableWords'] as const
31
+ return {
32
+ rootTypeName,
33
+ inlineTypes: true,
34
+ ...pickDefined(routeOpts, PASSTHROUGH_KEYS),
35
+ }
36
+ }
37
+
38
+ export function emitKotlinRoute(
39
+ route: AnyHttpRouteDoc,
40
+ emitter: KotlinEmitter,
41
+ errorSchemas: Map<string, unknown>,
42
+ routeOpts: EmitRouteOpts = {},
43
+ ): EmitRouteResult {
44
+ const kind = (route as { kind?: string }).kind
45
+ if (kind === 'stream') {
46
+ return { code: '', imports: [], routeName: route.name, skipped: true }
47
+ }
48
+
49
+ const isApi = kind === 'api' || 'fullPath' in route
50
+ const rawPath = isApi ? (route as { fullPath: string }).fullPath : (route as { path: string }).path
51
+ const method = String((route as { method: string }).method).toUpperCase()
52
+ const bracePath = toBracePath(rawPath)
53
+ const params = pathParamNames(rawPath)
54
+
55
+ const lines: string[] = [
56
+ `const val method = "${method}"`,
57
+ `const val pathTemplate = "${bracePath}"`,
58
+ buildPathFn(bracePath, params),
59
+ ]
60
+ const imports: string[] = []
61
+
62
+ // Per-slot emission. Order is fixed for deterministic output.
63
+ for (const slot of extractRouteSlots(route)) {
64
+ const result = emitter.emit(slot.source as Record<string, unknown>, emitOptsFor(slot.rootName, routeOpts))
65
+ lines.push('')
66
+ lines.push(result.code)
67
+ imports.push(...result.imports)
68
+ }
69
+
70
+ // Errors namespace — route.errors is `string[]` of taxonomy keys; look up each schema
71
+ // from the envelope-level errors map. Keys without schemas are skipped silently
72
+ // (matching the existing TS scope emitter's `errorKeys` filter).
73
+ const routeErrorKeys = ((route as { errors?: string[] }).errors ?? [])
74
+ .filter((key) => errorSchemas.has(key))
75
+ if (routeErrorKeys.length > 0) {
76
+ const inner: string[] = []
77
+ for (const key of routeErrorKeys) {
78
+ const r = emitter.emit(errorSchemas.get(key) as Record<string, unknown>, emitOptsFor(key, routeOpts))
79
+ inner.push(r.code)
80
+ imports.push(...r.imports)
81
+ }
82
+ lines.push('')
83
+ lines.push('object Errors {')
84
+ lines.push(indent(inner.join('\n\n'), 1))
85
+ lines.push('}')
86
+ }
87
+
88
+ return { code: lines.join('\n'), imports, routeName: route.name, skipped: false }
89
+ }
@@ -0,0 +1,112 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { AnyHttpRouteDoc } from '../../../implementations/types.js'
3
+ import type { ScopeGroup } from '../../group-routes.js'
4
+ import { emitKotlinScope } from './emit-scope-kotlin.js'
5
+ import { createStubKotlinEmitter, type KotlinEmitOptions, type KotlinEmitResult } from './ajsc-adapter.js'
6
+
7
+ const ok = (code: string, rootTypeName: string): KotlinEmitResult => ({
8
+ code,
9
+ rootTypeName,
10
+ extractedTypeNames: [],
11
+ imports: ['kotlinx.serialization.Serializable'],
12
+ })
13
+
14
+ describe('emitKotlinScope', () => {
15
+ it('produces a complete kotlin source file for a single-route scope', () => {
16
+ const route: AnyHttpRouteDoc = {
17
+ kind: 'api',
18
+ name: 'GetUser',
19
+ method: 'GET',
20
+ fullPath: '/users/:id',
21
+ schema: { input: { pathParams: { type: 'object' } }, returnType: { type: 'object' } },
22
+ errors: [],
23
+ } as unknown as AnyHttpRouteDoc
24
+
25
+ const group: ScopeGroup = { scopeKey: 'users', camelCase: 'users', routes: [route] }
26
+ const emitter = createStubKotlinEmitter({
27
+ PathParams: ok('@Serializable data class PathParams(val id: String)', 'PathParams'),
28
+ Response: ok('@Serializable data class Response(val id: String)', 'Response'),
29
+ })
30
+
31
+ const file = emitKotlinScope(group, { kotlinPackage: 'com.example.api', sourceHash: 'abc123' }, emitter, new Map())
32
+
33
+ expect(file.filename).toBe('Users.kt')
34
+ expect(file.code).toContain('package com.example.api')
35
+ expect(file.code).toContain('// Source hash: abc123')
36
+ expect(file.code).toContain('import kotlinx.serialization.Serializable')
37
+ expect(file.code).toContain('object Users {')
38
+ expect(file.code).toContain('object GetUser {')
39
+ expect(file.code).toContain('const val method = "GET"')
40
+ })
41
+
42
+ it('joins multiple routes inside one scope object', () => {
43
+ const route1 = { kind: 'api', name: 'GetUser', method: 'GET', fullPath: '/users/:id', schema: {}, errors: [] } as unknown as AnyHttpRouteDoc
44
+ const route2 = { kind: 'api', name: 'CreateUser', method: 'POST', fullPath: '/users', schema: {}, errors: [] } as unknown as AnyHttpRouteDoc
45
+ const group: ScopeGroup = { scopeKey: 'users', camelCase: 'users', routes: [route1, route2] }
46
+ const emitter = createStubKotlinEmitter({})
47
+
48
+ const file = emitKotlinScope(group, { kotlinPackage: 'com.example.api', sourceHash: 'h' }, emitter, new Map())
49
+ expect(file.code).toContain('object GetUser {')
50
+ expect(file.code).toContain('object CreateUser {')
51
+ // exactly one outer scope object
52
+ expect((file.code.match(/^object Users \{/gm) ?? []).length).toBe(1)
53
+ })
54
+
55
+ it('uses PascalCase scope name for the filename and outer object', () => {
56
+ const group: ScopeGroup = { scopeKey: 'admin-users', camelCase: 'adminUsers', routes: [] }
57
+ const file = emitKotlinScope(group, { kotlinPackage: 'p', sourceHash: 'h' }, createStubKotlinEmitter({}), new Map())
58
+ expect(file.filename).toBe('AdminUsers.kt')
59
+ expect(file.code).toContain('object AdminUsers {')
60
+ })
61
+
62
+ it('threads all 5 passthrough opts to every emitter call', () => {
63
+ const route = { kind: 'api', name: 'X', method: 'GET', fullPath: '/x', schema: { returnType: { type: 'object' } }, errors: [] } as unknown as AnyHttpRouteDoc
64
+ const group: ScopeGroup = { scopeKey: 'x', camelCase: 'x', routes: [route] }
65
+
66
+ const calls: KotlinEmitOptions[] = []
67
+ const emitter = {
68
+ emit(_s: unknown, opts: KotlinEmitOptions) {
69
+ calls.push(opts)
70
+ return { code: 'data class Response', rootTypeName: 'Response', extractedTypeNames: [], imports: [] }
71
+ },
72
+ }
73
+
74
+ emitKotlinScope(
75
+ group,
76
+ {
77
+ kotlinPackage: 'p',
78
+ sourceHash: 'h',
79
+ serializer: 'none',
80
+ unsupportedUnions: 'fallback',
81
+ arrayItemNaming: false,
82
+ depluralize: true,
83
+ uncountableWords: ['data', 'metadata'],
84
+ },
85
+ emitter,
86
+ new Map(),
87
+ )
88
+
89
+ expect(calls.length).toBe(1)
90
+ expect(calls[0]!.inlineTypes).toBe(true)
91
+ expect(calls[0]!.serializer).toBe('none')
92
+ expect(calls[0]!.unsupportedUnions).toBe('fallback')
93
+ expect(calls[0]!.arrayItemNaming).toBe(false)
94
+ expect(calls[0]!.depluralize).toBe(true)
95
+ expect(calls[0]!.uncountableWords).toEqual(['data', 'metadata'])
96
+ })
97
+
98
+ it('collects skipped stream-route names', () => {
99
+ const stream = { kind: 'stream', name: 'WatchUsers', method: 'GET', path: '/u/stream', schema: {}, errors: [] } as unknown as AnyHttpRouteDoc
100
+ const api = { kind: 'api', name: 'GetUser', method: 'GET', fullPath: '/u', schema: { returnType: { type: 'object' } }, errors: [] } as unknown as AnyHttpRouteDoc
101
+ const group: ScopeGroup = { scopeKey: 'u', camelCase: 'u', routes: [stream, api] }
102
+
103
+ const emitter = createStubKotlinEmitter({
104
+ Response: ok('data class Response(val id: String)', 'Response'),
105
+ })
106
+ const result = emitKotlinScope(group, { kotlinPackage: 'p', sourceHash: 'h' }, emitter, new Map())
107
+
108
+ expect(result.skippedStreams).toEqual(['WatchUsers'])
109
+ expect(result.code).toContain('object GetUser')
110
+ expect(result.code).not.toContain('object WatchUsers')
111
+ })
112
+ })
@@ -0,0 +1,60 @@
1
+ import type { ScopeGroup } from '../../group-routes.js'
2
+ import type { KotlinEmitter } from './ajsc-adapter.js'
3
+ import { emitKotlinRoute, type EmitRouteOpts } from './emit-route-kotlin.js'
4
+ import { kotlinPackageDecl, kotlinSourceHashHeader, kotlinImports } from './format-kotlin.js'
5
+ import { indent } from '../_shared/indent.js'
6
+ import { pickDefined } from '../_shared/pick-defined.js'
7
+ import { pascalCase } from '../_shared/pascal-case.js'
8
+
9
+ export interface EmitScopeOptions extends EmitRouteOpts {
10
+ kotlinPackage: string
11
+ sourceHash: string
12
+ }
13
+
14
+ export interface EmittedKotlinFile {
15
+ filename: string
16
+ code: string
17
+ /** Names of stream routes within this scope that were skipped. */
18
+ skippedStreams: string[]
19
+ }
20
+
21
+ export function emitKotlinScope(
22
+ group: ScopeGroup,
23
+ opts: EmitScopeOptions,
24
+ emitter: KotlinEmitter,
25
+ errorSchemas: Map<string, unknown>,
26
+ ): EmittedKotlinFile {
27
+ const scopeName = pascalCase(group.scopeKey)
28
+ const allImports: string[] = []
29
+ const routeBlocks: string[] = []
30
+ const skippedStreams: string[] = []
31
+
32
+ const PASSTHROUGH_KEYS = ['serializer', 'unsupportedUnions', 'arrayItemNaming', 'depluralize', 'uncountableWords'] as const
33
+ const routeOpts: EmitRouteOpts = pickDefined(opts, PASSTHROUGH_KEYS)
34
+
35
+ for (const route of group.routes) {
36
+ const r = emitKotlinRoute(route, emitter, errorSchemas, routeOpts)
37
+ if (r.skipped) {
38
+ skippedStreams.push(r.routeName)
39
+ continue
40
+ }
41
+ allImports.push(...r.imports)
42
+ const wrapped = `object ${r.routeName} {\n${indent(r.code, 1)}\n}`
43
+ routeBlocks.push(wrapped)
44
+ }
45
+
46
+ const innerScope = routeBlocks.length === 0 ? '' : indent(routeBlocks.join('\n\n'), 1)
47
+ const scopeBlock = innerScope === ''
48
+ ? `object ${scopeName} {\n}`
49
+ : `object ${scopeName} {\n${innerScope}\n}`
50
+
51
+ const importsBlock = kotlinImports(allImports)
52
+ const parts = [
53
+ kotlinPackageDecl(opts.kotlinPackage),
54
+ kotlinSourceHashHeader(opts.sourceHash),
55
+ importsBlock,
56
+ scopeBlock,
57
+ ].filter((p) => p.length > 0)
58
+
59
+ return { filename: `${scopeName}.kt`, code: parts.join('\n\n') + '\n', skippedStreams }
60
+ }
@@ -0,0 +1,26 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ kotlinPackageDecl,
4
+ kotlinSourceHashHeader,
5
+ kotlinImports,
6
+ } from './format-kotlin.js'
7
+
8
+ describe('format-kotlin', () => {
9
+ it('emits a package declaration', () => {
10
+ expect(kotlinPackageDecl('com.example.api')).toBe('package com.example.api')
11
+ })
12
+
13
+ it('emits a source-hash header line', () => {
14
+ expect(kotlinSourceHashHeader('abc123')).toBe('// Source hash: abc123')
15
+ })
16
+
17
+ it('dedupes and sorts imports', () => {
18
+ expect(kotlinImports(['kotlinx.serialization.Serializable', 'kotlinx.serialization.SerialName', 'kotlinx.serialization.Serializable'])).toBe(
19
+ 'import kotlinx.serialization.SerialName\nimport kotlinx.serialization.Serializable',
20
+ )
21
+ })
22
+
23
+ it('returns empty string when no imports', () => {
24
+ expect(kotlinImports([])).toBe('')
25
+ })
26
+ })
@@ -0,0 +1,13 @@
1
+ export function kotlinPackageDecl(pkg: string): string {
2
+ return `package ${pkg}`
3
+ }
4
+
5
+ export function kotlinSourceHashHeader(hash: string): string {
6
+ return `// Source hash: ${hash}`
7
+ }
8
+
9
+ export function kotlinImports(imports: string[]): string {
10
+ if (imports.length === 0) return ''
11
+ const unique = Array.from(new Set(imports)).sort()
12
+ return unique.map((i) => `import ${i}`).join('\n')
13
+ }