swallowkit 1.0.0-beta.6 → 1.0.0-beta.60

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 (296) hide show
  1. package/README.ja.md +86 -177
  2. package/README.md +86 -178
  3. package/dist/__tests__/fixtures.d.ts +12 -0
  4. package/dist/__tests__/fixtures.d.ts.map +1 -1
  5. package/dist/__tests__/fixtures.js +101 -0
  6. package/dist/__tests__/fixtures.js.map +1 -1
  7. package/dist/cli/commands/add-auth.d.ts +15 -0
  8. package/dist/cli/commands/add-auth.d.ts.map +1 -0
  9. package/dist/cli/commands/add-auth.js +790 -0
  10. package/dist/cli/commands/add-auth.js.map +1 -0
  11. package/dist/cli/commands/add-connector.d.ts +20 -0
  12. package/dist/cli/commands/add-connector.d.ts.map +1 -0
  13. package/dist/cli/commands/add-connector.js +163 -0
  14. package/dist/cli/commands/add-connector.js.map +1 -0
  15. package/dist/cli/commands/cosmos-worktree-isolation.d.ts +25 -0
  16. package/dist/cli/commands/cosmos-worktree-isolation.d.ts.map +1 -0
  17. package/dist/cli/commands/cosmos-worktree-isolation.js +124 -0
  18. package/dist/cli/commands/cosmos-worktree-isolation.js.map +1 -0
  19. package/dist/cli/commands/create-model.d.ts +1 -4
  20. package/dist/cli/commands/create-model.d.ts.map +1 -1
  21. package/dist/cli/commands/create-model.js +19 -81
  22. package/dist/cli/commands/create-model.js.map +1 -1
  23. package/dist/cli/commands/dev-seeds.d.ts +62 -0
  24. package/dist/cli/commands/dev-seeds.d.ts.map +1 -0
  25. package/dist/cli/commands/dev-seeds.js +474 -0
  26. package/dist/cli/commands/dev-seeds.js.map +1 -0
  27. package/dist/cli/commands/dev.d.ts +38 -0
  28. package/dist/cli/commands/dev.d.ts.map +1 -1
  29. package/dist/cli/commands/dev.js +733 -155
  30. package/dist/cli/commands/dev.js.map +1 -1
  31. package/dist/cli/commands/index.d.ts +1 -0
  32. package/dist/cli/commands/index.d.ts.map +1 -1
  33. package/dist/cli/commands/index.js +3 -1
  34. package/dist/cli/commands/index.js.map +1 -1
  35. package/dist/cli/commands/init.d.ts +78 -0
  36. package/dist/cli/commands/init.d.ts.map +1 -1
  37. package/dist/cli/commands/init.js +1453 -898
  38. package/dist/cli/commands/init.js.map +1 -1
  39. package/dist/cli/commands/scaffold.d.ts +24 -0
  40. package/dist/cli/commands/scaffold.d.ts.map +1 -1
  41. package/dist/cli/commands/scaffold.js +473 -90
  42. package/dist/cli/commands/scaffold.js.map +1 -1
  43. package/dist/cli/index.d.ts +5 -1
  44. package/dist/cli/index.d.ts.map +1 -1
  45. package/dist/cli/index.js +333 -55
  46. package/dist/cli/index.js.map +1 -1
  47. package/dist/core/config.d.ts +14 -3
  48. package/dist/core/config.d.ts.map +1 -1
  49. package/dist/core/config.js +179 -8
  50. package/dist/core/config.js.map +1 -1
  51. package/dist/core/mock/connector-mock-server.d.ts +101 -0
  52. package/dist/core/mock/connector-mock-server.d.ts.map +1 -0
  53. package/dist/core/mock/connector-mock-server.js +480 -0
  54. package/dist/core/mock/connector-mock-server.js.map +1 -0
  55. package/dist/core/mock/zod-mock-generator.d.ts +14 -0
  56. package/dist/core/mock/zod-mock-generator.d.ts.map +1 -0
  57. package/dist/core/mock/zod-mock-generator.js +163 -0
  58. package/dist/core/mock/zod-mock-generator.js.map +1 -0
  59. package/dist/core/operations/auth-operations.d.ts +61 -0
  60. package/dist/core/operations/auth-operations.d.ts.map +1 -0
  61. package/dist/core/operations/auth-operations.js +272 -0
  62. package/dist/core/operations/auth-operations.js.map +1 -0
  63. package/dist/core/operations/create-model.d.ts +15 -0
  64. package/dist/core/operations/create-model.d.ts.map +1 -0
  65. package/dist/core/operations/create-model.js +185 -0
  66. package/dist/core/operations/create-model.js.map +1 -0
  67. package/dist/core/operations/file-session.d.ts +56 -0
  68. package/dist/core/operations/file-session.d.ts.map +1 -0
  69. package/dist/core/operations/file-session.js +203 -0
  70. package/dist/core/operations/file-session.js.map +1 -0
  71. package/dist/core/operations/provision-operations.d.ts +52 -0
  72. package/dist/core/operations/provision-operations.d.ts.map +1 -0
  73. package/dist/core/operations/provision-operations.js +211 -0
  74. package/dist/core/operations/provision-operations.js.map +1 -0
  75. package/dist/core/operations/runtime.d.ts +37 -0
  76. package/dist/core/operations/runtime.d.ts.map +1 -0
  77. package/dist/core/operations/runtime.js +248 -0
  78. package/dist/core/operations/runtime.js.map +1 -0
  79. package/dist/core/operations/scaffold-apply.d.ts +21 -0
  80. package/dist/core/operations/scaffold-apply.d.ts.map +1 -0
  81. package/dist/core/operations/scaffold-apply.js +57 -0
  82. package/dist/core/operations/scaffold-apply.js.map +1 -0
  83. package/dist/core/operations/scaffold-machine.d.ts +16 -0
  84. package/dist/core/operations/scaffold-machine.d.ts.map +1 -0
  85. package/dist/core/operations/scaffold-machine.js +51 -0
  86. package/dist/core/operations/scaffold-machine.js.map +1 -0
  87. package/dist/core/operations/scaffold-plan.d.ts +43 -0
  88. package/dist/core/operations/scaffold-plan.d.ts.map +1 -0
  89. package/dist/core/operations/scaffold-plan.js +187 -0
  90. package/dist/core/operations/scaffold-plan.js.map +1 -0
  91. package/dist/core/project/agent-instructions.d.ts +29 -0
  92. package/dist/core/project/agent-instructions.d.ts.map +1 -0
  93. package/dist/core/project/agent-instructions.js +159 -0
  94. package/dist/core/project/agent-instructions.js.map +1 -0
  95. package/dist/core/project/artifacts.d.ts +58 -0
  96. package/dist/core/project/artifacts.d.ts.map +1 -0
  97. package/dist/core/project/artifacts.js +179 -0
  98. package/dist/core/project/artifacts.js.map +1 -0
  99. package/dist/core/project/boundaries.d.ts +50 -0
  100. package/dist/core/project/boundaries.d.ts.map +1 -0
  101. package/dist/core/project/boundaries.js +117 -0
  102. package/dist/core/project/boundaries.js.map +1 -0
  103. package/dist/core/project/capabilities.d.ts +58 -0
  104. package/dist/core/project/capabilities.d.ts.map +1 -0
  105. package/dist/core/project/capabilities.js +135 -0
  106. package/dist/core/project/capabilities.js.map +1 -0
  107. package/dist/core/project/drift.d.ts +29 -0
  108. package/dist/core/project/drift.d.ts.map +1 -0
  109. package/dist/core/project/drift.js +188 -0
  110. package/dist/core/project/drift.js.map +1 -0
  111. package/dist/core/project/infra.d.ts +49 -0
  112. package/dist/core/project/infra.d.ts.map +1 -0
  113. package/dist/core/project/infra.js +167 -0
  114. package/dist/core/project/infra.js.map +1 -0
  115. package/dist/core/project/manifest.d.ts +92 -0
  116. package/dist/core/project/manifest.d.ts.map +1 -0
  117. package/dist/core/project/manifest.js +321 -0
  118. package/dist/core/project/manifest.js.map +1 -0
  119. package/dist/core/project/state.d.ts +15 -0
  120. package/dist/core/project/state.d.ts.map +1 -0
  121. package/dist/core/project/state.js +106 -0
  122. package/dist/core/project/state.js.map +1 -0
  123. package/dist/core/project/validation.d.ts +20 -0
  124. package/dist/core/project/validation.d.ts.map +1 -0
  125. package/dist/core/project/validation.js +274 -0
  126. package/dist/core/project/validation.js.map +1 -0
  127. package/dist/core/project/workflows.d.ts +43 -0
  128. package/dist/core/project/workflows.d.ts.map +1 -0
  129. package/dist/core/project/workflows.js +299 -0
  130. package/dist/core/project/workflows.js.map +1 -0
  131. package/dist/core/scaffold/auth-generator.d.ts +63 -0
  132. package/dist/core/scaffold/auth-generator.d.ts.map +1 -0
  133. package/dist/core/scaffold/auth-generator.js +1774 -0
  134. package/dist/core/scaffold/auth-generator.js.map +1 -0
  135. package/dist/core/scaffold/connector-functions-generator.d.ts +41 -0
  136. package/dist/core/scaffold/connector-functions-generator.d.ts.map +1 -0
  137. package/dist/core/scaffold/connector-functions-generator.js +1029 -0
  138. package/dist/core/scaffold/connector-functions-generator.js.map +1 -0
  139. package/dist/core/scaffold/functions-generator.d.ts +7 -1
  140. package/dist/core/scaffold/functions-generator.d.ts.map +1 -1
  141. package/dist/core/scaffold/functions-generator.js +771 -69
  142. package/dist/core/scaffold/functions-generator.js.map +1 -1
  143. package/dist/core/scaffold/model-parser.d.ts +21 -1
  144. package/dist/core/scaffold/model-parser.d.ts.map +1 -1
  145. package/dist/core/scaffold/model-parser.js +243 -43
  146. package/dist/core/scaffold/model-parser.js.map +1 -1
  147. package/dist/core/scaffold/native-schema-generator.d.ts +19 -0
  148. package/dist/core/scaffold/native-schema-generator.d.ts.map +1 -0
  149. package/dist/core/scaffold/native-schema-generator.js +753 -0
  150. package/dist/core/scaffold/native-schema-generator.js.map +1 -0
  151. package/dist/core/scaffold/nextjs-generator.d.ts +8 -0
  152. package/dist/core/scaffold/nextjs-generator.d.ts.map +1 -1
  153. package/dist/core/scaffold/nextjs-generator.js +153 -9
  154. package/dist/core/scaffold/nextjs-generator.js.map +1 -1
  155. package/dist/core/scaffold/openapi-generator.d.ts +3 -0
  156. package/dist/core/scaffold/openapi-generator.d.ts.map +1 -0
  157. package/dist/core/scaffold/openapi-generator.js +190 -0
  158. package/dist/core/scaffold/openapi-generator.js.map +1 -0
  159. package/dist/core/scaffold/ui-generator.d.ts +17 -4
  160. package/dist/core/scaffold/ui-generator.d.ts.map +1 -1
  161. package/dist/core/scaffold/ui-generator.js +174 -34
  162. package/dist/core/scaffold/ui-generator.js.map +1 -1
  163. package/dist/core/verify/index.d.ts +69 -0
  164. package/dist/core/verify/index.d.ts.map +1 -0
  165. package/dist/core/verify/index.js +412 -0
  166. package/dist/core/verify/index.js.map +1 -0
  167. package/dist/database/base-model.d.ts +3 -3
  168. package/dist/database/base-model.js +3 -3
  169. package/dist/index.d.ts +2 -2
  170. package/dist/index.d.ts.map +1 -1
  171. package/dist/index.js +2 -1
  172. package/dist/index.js.map +1 -1
  173. package/dist/machine/contracts.d.ts +24 -0
  174. package/dist/machine/contracts.d.ts.map +1 -0
  175. package/dist/machine/contracts.js +3 -0
  176. package/dist/machine/contracts.js.map +1 -0
  177. package/dist/machine/errors.d.ts +14 -0
  178. package/dist/machine/errors.d.ts.map +1 -0
  179. package/dist/machine/errors.js +42 -0
  180. package/dist/machine/errors.js.map +1 -0
  181. package/dist/machine/index.d.ts +3 -0
  182. package/dist/machine/index.d.ts.map +1 -0
  183. package/dist/machine/index.js +566 -0
  184. package/dist/machine/index.js.map +1 -0
  185. package/dist/mcp/index.d.ts +25 -0
  186. package/dist/mcp/index.d.ts.map +1 -0
  187. package/dist/mcp/index.js +425 -0
  188. package/dist/mcp/index.js.map +1 -0
  189. package/dist/types/index.d.ts +109 -0
  190. package/dist/types/index.d.ts.map +1 -1
  191. package/dist/utils/package-manager.d.ts +5 -2
  192. package/dist/utils/package-manager.d.ts.map +1 -1
  193. package/dist/utils/package-manager.js +30 -9
  194. package/dist/utils/package-manager.js.map +1 -1
  195. package/dist/utils/python-uv.d.ts +21 -0
  196. package/dist/utils/python-uv.d.ts.map +1 -0
  197. package/dist/utils/python-uv.js +111 -0
  198. package/dist/utils/python-uv.js.map +1 -0
  199. package/dist/version.d.ts +2 -0
  200. package/dist/version.d.ts.map +1 -0
  201. package/dist/version.js +49 -0
  202. package/dist/version.js.map +1 -0
  203. package/package.json +9 -5
  204. package/src/__tests__/__snapshots__/functions-generator.test.ts.snap +1139 -0
  205. package/src/__tests__/__snapshots__/nextjs-generator.test.ts.snap +206 -0
  206. package/src/__tests__/__snapshots__/ui-generator.test.ts.snap +532 -0
  207. package/src/__tests__/agent-instructions.test.ts +237 -0
  208. package/src/__tests__/agent-loop-phase34.test.ts +513 -0
  209. package/src/__tests__/auth.test.ts +770 -0
  210. package/src/__tests__/bff-swa-auth.test.ts +275 -0
  211. package/src/__tests__/config.test.ts +295 -0
  212. package/src/__tests__/connector-functions-generator.test.ts +288 -0
  213. package/src/__tests__/connector-mock-server.test.ts +439 -0
  214. package/src/__tests__/connector-model-bff.test.ts +162 -0
  215. package/src/__tests__/cosmos-worktree-isolation.test.ts +149 -0
  216. package/src/__tests__/dev-seeds.test.ts +236 -0
  217. package/src/__tests__/dev.test.ts +296 -0
  218. package/src/__tests__/file-session.test.ts +98 -0
  219. package/src/__tests__/fixtures.ts +184 -0
  220. package/src/__tests__/functions-generator.test.ts +237 -0
  221. package/src/__tests__/init.test.ts +411 -0
  222. package/src/__tests__/jest-globals.d.ts +8 -0
  223. package/src/__tests__/machine.test.ts +371 -0
  224. package/src/__tests__/mcp.test.ts +253 -0
  225. package/src/__tests__/model-parser.test.ts +81 -0
  226. package/src/__tests__/multi-auth.test.ts +160 -0
  227. package/src/__tests__/nextjs-generator.test.ts +105 -0
  228. package/src/__tests__/openapi-generator.test.ts +43 -0
  229. package/src/__tests__/package-manager.test.ts +227 -0
  230. package/src/__tests__/plan-apply.test.ts +499 -0
  231. package/src/__tests__/python-uv.test.ts +48 -0
  232. package/src/__tests__/scaffold.test.ts +302 -0
  233. package/src/__tests__/string-utils.test.ts +75 -0
  234. package/src/__tests__/tsconfig.json +15 -0
  235. package/src/__tests__/ui-generator.test.ts +248 -0
  236. package/src/__tests__/zod-mock-generator.test.ts +132 -0
  237. package/src/cli/commands/add-auth.ts +853 -0
  238. package/src/cli/commands/add-connector.ts +158 -0
  239. package/src/cli/commands/cosmos-worktree-isolation.ts +130 -0
  240. package/src/cli/commands/create-model.ts +62 -0
  241. package/src/cli/commands/dev-seeds.ts +629 -0
  242. package/src/cli/commands/dev.ts +1252 -0
  243. package/src/cli/commands/index.ts +9 -0
  244. package/src/cli/commands/init.ts +3541 -0
  245. package/src/cli/commands/provision.ts +193 -0
  246. package/src/cli/commands/scaffold.ts +1081 -0
  247. package/src/cli/index.ts +350 -0
  248. package/src/core/config.ts +380 -0
  249. package/src/core/mock/connector-mock-server.ts +555 -0
  250. package/src/core/mock/zod-mock-generator.ts +205 -0
  251. package/src/core/operations/auth-operations.ts +360 -0
  252. package/src/core/operations/create-model.ts +191 -0
  253. package/src/core/operations/file-session.ts +222 -0
  254. package/src/core/operations/provision-operations.ts +297 -0
  255. package/src/core/operations/runtime.ts +258 -0
  256. package/src/core/operations/scaffold-apply.ts +106 -0
  257. package/src/core/operations/scaffold-machine.ts +77 -0
  258. package/src/core/operations/scaffold-plan.ts +215 -0
  259. package/src/core/project/agent-instructions.ts +167 -0
  260. package/src/core/project/agent-templates/AGENTS.md +502 -0
  261. package/src/core/project/agent-templates/CLAUDE.md +31 -0
  262. package/src/core/project/agent-templates/azure-functions.instructions.md +22 -0
  263. package/src/core/project/agent-templates/bff-routes.instructions.md +18 -0
  264. package/src/core/project/agent-templates/copilot-instructions.md +27 -0
  265. package/src/core/project/agent-templates/shared-models.instructions.md +72 -0
  266. package/src/core/project/artifacts.ts +205 -0
  267. package/src/core/project/boundaries.ts +170 -0
  268. package/src/core/project/capabilities.ts +193 -0
  269. package/src/core/project/drift.ts +202 -0
  270. package/src/core/project/infra.ts +196 -0
  271. package/src/core/project/manifest.ts +402 -0
  272. package/src/core/project/state.ts +77 -0
  273. package/src/core/project/validation.ts +295 -0
  274. package/src/core/project/workflows.ts +295 -0
  275. package/src/core/scaffold/auth-generator.ts +1824 -0
  276. package/src/core/scaffold/connector-functions-generator.ts +1133 -0
  277. package/src/core/scaffold/functions-generator.ts +972 -0
  278. package/src/core/scaffold/model-parser.ts +854 -0
  279. package/src/core/scaffold/native-schema-generator.ts +904 -0
  280. package/src/core/scaffold/nextjs-generator.ts +382 -0
  281. package/src/core/scaffold/openapi-generator.ts +212 -0
  282. package/src/core/scaffold/ui-generator.ts +1100 -0
  283. package/src/core/verify/index.ts +468 -0
  284. package/src/database/base-model.ts +184 -0
  285. package/src/database/client.ts +140 -0
  286. package/src/database/repository.ts +104 -0
  287. package/src/database/runtime-check.ts +25 -0
  288. package/src/index.ts +27 -0
  289. package/src/machine/contracts.ts +33 -0
  290. package/src/machine/errors.ts +45 -0
  291. package/src/machine/index.ts +690 -0
  292. package/src/mcp/index.ts +423 -0
  293. package/src/types/index.ts +182 -0
  294. package/src/utils/package-manager.ts +246 -0
  295. package/src/utils/python-uv.ts +96 -0
  296. package/src/version.ts +13 -0
@@ -0,0 +1,1252 @@
1
+ import { Command } from 'commander';
2
+ import { spawn, ChildProcess } from 'child_process';
3
+ import * as http from 'http';
4
+ import * as https from 'https';
5
+ import * as path from 'path';
6
+ import * as fs from 'fs';
7
+ import * as os from 'os';
8
+ import * as net from 'net';
9
+ import { CosmosClient, PartitionKeyKind } from '@azure/cosmos';
10
+ import { ensureSwallowKitProject, getBackendLanguage, getAuthConfig, normalizeAuthConfig } from '../../core/config';
11
+ import { ModelInfo } from '../../core/scaffold/model-parser';
12
+ import {
13
+ applyDevSeedEnvironment,
14
+ getContainerNameForModel,
15
+ getDefaultCosmosDatabaseName,
16
+ loadProjectModels,
17
+ resolveLocalCosmosConnectionInfo,
18
+ } from './dev-seeds';
19
+ import { BackendLanguage } from '../../types';
20
+ import { detectFromProject, getCommands } from '../../utils/package-manager';
21
+ import {
22
+ buildProjectLocalUvEnv,
23
+ buildProjectLocalUvInstallerEnv,
24
+ buildUvPipInstallArgs,
25
+ buildUvVenvArgs,
26
+ getProjectLocalUvInstallerCommand,
27
+ getProjectLocalUvPaths,
28
+ getPythonProjectRoot,
29
+ } from '../../utils/python-uv';
30
+ import { ConnectorMockServer } from '../../core/mock/connector-mock-server';
31
+
32
+ export interface DevOptions {
33
+ port?: string;
34
+ functionsPort?: string;
35
+ host?: string;
36
+ open?: boolean;
37
+ verbose?: boolean;
38
+ noFunctions?: boolean;
39
+ seedEnv?: string;
40
+ mockConnectors?: boolean;
41
+ swaPort?: string;
42
+ noSwa?: boolean;
43
+ }
44
+
45
+ type ParsedDevActionOptions = DevOptions & {
46
+ functions?: boolean;
47
+ swa?: boolean;
48
+ };
49
+
50
+ interface FunctionsCoreToolsCommand {
51
+ command: string;
52
+ argsPrefix: string[];
53
+ label: string;
54
+ }
55
+
56
+ const MINIMUM_CSHARP_CORE_TOOLS_VERSION = '4.6.0';
57
+ const NPM_CORE_TOOLS_PACKAGE = 'azure-functions-core-tools@4';
58
+
59
+ function normalizeParsedDevOptions(options: ParsedDevActionOptions): DevOptions {
60
+ return {
61
+ ...options,
62
+ noFunctions: options.noFunctions ?? options.functions === false,
63
+ noSwa: options.noSwa ?? options.swa === false,
64
+ };
65
+ }
66
+
67
+ export function buildFunctionsStartArgs(functionsPort: string): string[] {
68
+ return ['start', '--port', functionsPort];
69
+ }
70
+
71
+ export function parseCoreToolsVersion(output: string): string | null {
72
+ const match = output.match(/\d+\.\d+\.\d+/);
73
+ return match ? match[0] : null;
74
+ }
75
+
76
+ export function compareVersionNumbers(left: string, right: string): number {
77
+ const leftParts = left.split('.').map((value) => Number.parseInt(value, 10));
78
+ const rightParts = right.split('.').map((value) => Number.parseInt(value, 10));
79
+ const length = Math.max(leftParts.length, rightParts.length);
80
+
81
+ for (let index = 0; index < length; index += 1) {
82
+ const leftPart = leftParts[index] ?? 0;
83
+ const rightPart = rightParts[index] ?? 0;
84
+
85
+ if (leftPart !== rightPart) {
86
+ return leftPart - rightPart;
87
+ }
88
+ }
89
+
90
+ return 0;
91
+ }
92
+
93
+ export function buildFunctionsCoreToolsCommand(
94
+ backendLanguage: BackendLanguage,
95
+ installedVersion: string | null
96
+ ): FunctionsCoreToolsCommand {
97
+ if (
98
+ backendLanguage === 'csharp' &&
99
+ (!installedVersion || compareVersionNumbers(installedVersion, MINIMUM_CSHARP_CORE_TOOLS_VERSION) < 0)
100
+ ) {
101
+ const reason = installedVersion
102
+ ? `installed func ${installedVersion} is too old for C# isolated`
103
+ : 'func is not installed';
104
+
105
+ return {
106
+ command: 'npm',
107
+ argsPrefix: ['exec', '--yes', NPM_CORE_TOOLS_PACKAGE, '--'],
108
+ label: `npm exec ${NPM_CORE_TOOLS_PACKAGE} (${reason})`,
109
+ };
110
+ }
111
+
112
+ return {
113
+ command: 'func',
114
+ argsPrefix: [],
115
+ label: installedVersion ? `func ${installedVersion}` : 'func',
116
+ };
117
+ }
118
+
119
+ export function buildNextDevArgs(pm: string, port: string): string[] {
120
+ const baseArgs = ['next', 'dev', '--port', port, '--webpack'];
121
+ return pm === 'pnpm' ? ['exec', ...baseArgs] : baseArgs;
122
+ }
123
+
124
+ export function buildFunctionsBaseUrl(host: string | undefined, functionsPort: string): string {
125
+ return `http://${host || 'localhost'}:${functionsPort}`;
126
+ }
127
+
128
+ export function buildSwaStartArgs(host: string | undefined, nextPort: string, swaPort: string): string[] {
129
+ return [
130
+ 'start',
131
+ `http://${host || 'localhost'}:${nextPort}`,
132
+ '--swa-config-location',
133
+ '.',
134
+ '--port',
135
+ swaPort,
136
+ ];
137
+ }
138
+
139
+ export function getSwaCliInstallCommand(pm: string): string {
140
+ return pm === 'pnpm'
141
+ ? 'pnpm add -Dw @azure/static-web-apps-cli'
142
+ : 'npm install -D @azure/static-web-apps-cli';
143
+ }
144
+
145
+ export function getFunctionsReadinessTimeoutMs(backendLanguage: BackendLanguage): number {
146
+ return backendLanguage === 'csharp' ? 90_000 : 30_000;
147
+ }
148
+
149
+ export async function waitForHttpServerReady(
150
+ url: string,
151
+ timeoutMs = 30_000,
152
+ intervalMs = 500
153
+ ): Promise<boolean> {
154
+ const deadline = Date.now() + timeoutMs;
155
+
156
+ while (Date.now() <= deadline) {
157
+ if (await probeHttpServer(url)) {
158
+ return true;
159
+ }
160
+
161
+ if (Date.now() + intervalMs > deadline) {
162
+ break;
163
+ }
164
+
165
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
166
+ }
167
+
168
+ return probeHttpServer(url);
169
+ }
170
+
171
+ export function getPythonVirtualEnvPaths(functionsDir: string): {
172
+ venvDir: string;
173
+ binDir: string;
174
+ pythonExecutable: string;
175
+ } {
176
+ const venvDir = path.join(functionsDir, '.venv');
177
+ const binDir = process.platform === 'win32'
178
+ ? path.join(venvDir, 'Scripts')
179
+ : path.join(venvDir, 'bin');
180
+ const pythonExecutable = process.platform === 'win32'
181
+ ? path.join(binDir, 'python.exe')
182
+ : path.join(binDir, 'python');
183
+
184
+ return { venvDir, binDir, pythonExecutable };
185
+ }
186
+
187
+ export function getCSharpFunctionsBuildArtifactPaths(functionsDir: string): string[] {
188
+ return [
189
+ path.join(functionsDir, 'bin'),
190
+ path.join(functionsDir, 'obj'),
191
+ ];
192
+ }
193
+
194
+ export function buildPythonFunctionsEnv(baseEnv: NodeJS.ProcessEnv, functionsDir: string): NodeJS.ProcessEnv {
195
+ const { venvDir, binDir, pythonExecutable } = getPythonVirtualEnvPaths(functionsDir);
196
+ const pathKey = getPathEnvKey(baseEnv);
197
+ const currentPath = baseEnv[pathKey] || '';
198
+
199
+ return {
200
+ ...baseEnv,
201
+ [pathKey]: currentPath ? `${binDir}${path.delimiter}${currentPath}` : binDir,
202
+ VIRTUAL_ENV: venvDir,
203
+ languageWorkers__python__defaultExecutablePath: pythonExecutable,
204
+ };
205
+ }
206
+
207
+ export function buildFunctionsCosmosEnvironment(
208
+ baseEnv: NodeJS.ProcessEnv,
209
+ databaseName: string
210
+ ): NodeJS.ProcessEnv {
211
+ return {
212
+ ...baseEnv,
213
+ COSMOS_DB_DATABASE_NAME: databaseName,
214
+ };
215
+ }
216
+
217
+ function getPathEnvKey(env: NodeJS.ProcessEnv): string {
218
+ return Object.keys(env).find((key) => key.toUpperCase() === 'PATH') || 'PATH';
219
+ }
220
+
221
+ function prependToPathEnv(env: NodeJS.ProcessEnv, entry: string): NodeJS.ProcessEnv {
222
+ const pathKey = getPathEnvKey(env);
223
+ const currentPath = env[pathKey] || '';
224
+
225
+ return {
226
+ ...env,
227
+ [pathKey]: currentPath ? `${entry}${path.delimiter}${currentPath}` : entry,
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Check if Azure Functions Core Tools is installed
233
+ */
234
+ async function checkCoreTools(): Promise<boolean> {
235
+ return checkCommand('func', ['--version']);
236
+ }
237
+
238
+ async function checkCommand(
239
+ command: string,
240
+ args: string[] = ['--version'],
241
+ options?: {
242
+ cwd?: string;
243
+ env?: NodeJS.ProcessEnv;
244
+ shell?: boolean;
245
+ }
246
+ ): Promise<boolean> {
247
+ return new Promise((resolve) => {
248
+ const checkProcess = spawn(command, args, {
249
+ cwd: options?.cwd,
250
+ env: options?.env ?? process.env,
251
+ shell: options?.shell ?? true,
252
+ stdio: 'pipe',
253
+ });
254
+
255
+ checkProcess.on('close', (code) => {
256
+ resolve(code === 0);
257
+ });
258
+
259
+ checkProcess.on('error', () => {
260
+ resolve(false);
261
+ });
262
+ });
263
+ }
264
+
265
+ async function resolveProjectLocalUvCommand(projectRoot: string): Promise<{ command: string; env: NodeJS.ProcessEnv }> {
266
+ const uvEnv = buildProjectLocalUvEnv(process.env, projectRoot);
267
+ const { localUvExecutable } = getProjectLocalUvPaths(projectRoot);
268
+
269
+ if (await checkCommand('uv', ['--version'], { shell: false })) {
270
+ return { command: 'uv', env: uvEnv };
271
+ }
272
+
273
+ if (fs.existsSync(localUvExecutable) && await checkCommand(localUvExecutable, ['--version'], { shell: false })) {
274
+ return { command: localUvExecutable, env: uvEnv };
275
+ }
276
+
277
+ console.log('📦 Installing project-local uv...');
278
+ const installer = getProjectLocalUvInstallerCommand();
279
+ await runCommand(
280
+ installer.command,
281
+ installer.args,
282
+ projectRoot,
283
+ 'uv installation',
284
+ buildProjectLocalUvInstallerEnv(process.env, projectRoot),
285
+ false
286
+ );
287
+
288
+ if (!(fs.existsSync(localUvExecutable) && await checkCommand(localUvExecutable, ['--version'], { shell: false }))) {
289
+ throw new Error('Failed to install project-local uv.');
290
+ }
291
+
292
+ return { command: localUvExecutable, env: uvEnv };
293
+ }
294
+
295
+ async function getCommandPath(command: string): Promise<string | null> {
296
+ const locator = process.platform === 'win32' ? 'where' : 'which';
297
+ const result = await captureCommandOutput(locator, [command]);
298
+ const firstLine = result
299
+ .split(/\r?\n/)
300
+ .map((line) => line.trim())
301
+ .find(Boolean);
302
+
303
+ return firstLine || null;
304
+ }
305
+
306
+ async function resolveInstalledCoreToolsVersion(): Promise<string | null> {
307
+ if (!(await checkCoreTools())) {
308
+ return null;
309
+ }
310
+
311
+ try {
312
+ return parseCoreToolsVersion(await captureCommandOutput('func', ['--version']));
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+
318
+ async function captureCommandOutput(
319
+ command: string,
320
+ args: string[],
321
+ cwd?: string,
322
+ env?: NodeJS.ProcessEnv
323
+ ): Promise<string> {
324
+ return new Promise((resolve, reject) => {
325
+ const child = spawn(command, args, {
326
+ cwd,
327
+ env,
328
+ shell: false,
329
+ stdio: ['ignore', 'pipe', 'pipe'],
330
+ });
331
+
332
+ let stdout = '';
333
+ let stderr = '';
334
+
335
+ child.stdout?.on('data', (data) => {
336
+ stdout += data.toString();
337
+ });
338
+
339
+ child.stderr?.on('data', (data) => {
340
+ stderr += data.toString();
341
+ });
342
+
343
+ child.on('close', (code) => {
344
+ if (code === 0) {
345
+ resolve(stdout);
346
+ } else {
347
+ reject(new Error(stderr || stdout || `${command} exited with code ${code}`));
348
+ }
349
+ });
350
+
351
+ child.on('error', reject);
352
+ });
353
+ }
354
+
355
+ async function probeHttpServer(url: string): Promise<boolean> {
356
+ return new Promise((resolve) => {
357
+ const target = new URL(url);
358
+ const requestFactory = target.protocol === 'https:' ? https.request : http.request;
359
+ let settled = false;
360
+ const finish = (value: boolean) => {
361
+ if (!settled) {
362
+ settled = true;
363
+ resolve(value);
364
+ }
365
+ };
366
+
367
+ const request = requestFactory(
368
+ {
369
+ hostname: target.hostname,
370
+ port: target.port,
371
+ path: target.pathname || '/',
372
+ method: 'GET',
373
+ timeout: 1000,
374
+ },
375
+ (response) => {
376
+ response.resume();
377
+ finish(true);
378
+ }
379
+ );
380
+
381
+ request.on('timeout', () => {
382
+ request.destroy();
383
+ finish(false);
384
+ });
385
+ request.on('error', () => finish(false));
386
+ request.end();
387
+ });
388
+ }
389
+
390
+ async function resolvePythonRuntimeDetails(
391
+ functionsDir: string,
392
+ env: NodeJS.ProcessEnv
393
+ ): Promise<{ version: string; architecture: string }> {
394
+ const { pythonExecutable } = getPythonVirtualEnvPaths(functionsDir);
395
+ const output = await captureCommandOutput(
396
+ pythonExecutable,
397
+ [
398
+ '-c',
399
+ 'import platform; import sys; print(str(sys.version_info.major) + "." + str(sys.version_info.minor)); print(platform.machine())',
400
+ ],
401
+ functionsDir,
402
+ env
403
+ );
404
+ const [version, architecture] = output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
405
+
406
+ if (!version || !architecture) {
407
+ throw new Error('Failed to determine Python runtime details.');
408
+ }
409
+
410
+ return { version, architecture };
411
+ }
412
+
413
+ async function bridgePythonCoreToolsForWindowsArm64(
414
+ functionsDir: string,
415
+ env: NodeJS.ProcessEnv
416
+ ): Promise<NodeJS.ProcessEnv> {
417
+ if (process.platform !== 'win32' || process.arch !== 'arm64') {
418
+ return env;
419
+ }
420
+
421
+ const funcPath = await getCommandPath('func');
422
+ if (!funcPath) {
423
+ return env;
424
+ }
425
+
426
+ const { version, architecture } = await resolvePythonRuntimeDetails(functionsDir, env);
427
+ if (architecture.toUpperCase() !== 'AMD64') {
428
+ return env;
429
+ }
430
+
431
+ const coreToolsRoot = path.dirname(funcPath);
432
+ const armWorkerDir = path.join(coreToolsRoot, 'workers', 'python', version, 'WINDOWS', 'Arm64');
433
+ if (fs.existsSync(armWorkerDir)) {
434
+ return env;
435
+ }
436
+
437
+ const x64WorkerDir = path.join(coreToolsRoot, 'workers', 'python', version, 'WINDOWS', 'X64');
438
+ if (!fs.existsSync(x64WorkerDir)) {
439
+ return env;
440
+ }
441
+
442
+ const patchedRoot = path.join(
443
+ process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'),
444
+ 'SwallowKit',
445
+ 'azure-functions-core-tools-python-bridge'
446
+ );
447
+
448
+ if (!fs.existsSync(path.join(patchedRoot, 'func.exe'))) {
449
+ console.log('🩹 Creating a local Azure Functions Core Tools bridge for Windows Arm64 Python...');
450
+ fs.mkdirSync(path.dirname(patchedRoot), { recursive: true });
451
+ fs.cpSync(coreToolsRoot, patchedRoot, { recursive: true });
452
+ }
453
+
454
+ const patchedArmWorkerDir = path.join(patchedRoot, 'workers', 'python', version, 'WINDOWS', 'Arm64');
455
+ const patchedX64WorkerDir = path.join(patchedRoot, 'workers', 'python', version, 'WINDOWS', 'X64');
456
+ if (!fs.existsSync(patchedArmWorkerDir) && fs.existsSync(patchedX64WorkerDir)) {
457
+ fs.cpSync(patchedX64WorkerDir, patchedArmWorkerDir, { recursive: true });
458
+ }
459
+
460
+ console.log(`🩹 Using bridged Azure Functions Core Tools from ${patchedRoot}`);
461
+ return prependToPathEnv(env, patchedRoot);
462
+ }
463
+
464
+ async function preparePythonFunctionsEnvironment(functionsDir: string): Promise<NodeJS.ProcessEnv> {
465
+ const projectRoot = getPythonProjectRoot(functionsDir);
466
+ const { command: uvCommand, env: uvEnv } = await resolveProjectLocalUvCommand(projectRoot);
467
+ const { venvDir, pythonExecutable } = getPythonVirtualEnvPaths(functionsDir);
468
+ const hasUsableVirtualEnv = fs.existsSync(pythonExecutable) && await checkCommand(pythonExecutable, ['--version'], {
469
+ cwd: functionsDir,
470
+ env: uvEnv,
471
+ shell: false,
472
+ });
473
+
474
+ if (!hasUsableVirtualEnv) {
475
+ const venvArgs = buildUvVenvArgs('.venv');
476
+ if (fs.existsSync(venvDir)) {
477
+ venvArgs.push('--clear');
478
+ }
479
+
480
+ console.log('📦 Creating Python virtual environment with uv...');
481
+ await runCommand(uvCommand, venvArgs, functionsDir, 'python virtual environment setup', uvEnv, false);
482
+ }
483
+
484
+ console.log('📦 Installing Python Azure Functions dependencies with uv...');
485
+ await runCommand(
486
+ uvCommand,
487
+ buildUvPipInstallArgs(pythonExecutable, 'requirements.txt'),
488
+ functionsDir,
489
+ 'python dependency installation',
490
+ uvEnv,
491
+ false
492
+ );
493
+
494
+ const pythonEnv = buildPythonFunctionsEnv(uvEnv, functionsDir);
495
+ return bridgePythonCoreToolsForWindowsArm64(functionsDir, pythonEnv);
496
+ }
497
+
498
+ /**
499
+ * Check if Cosmos DB Emulator is running by checking if port 8081 is open
500
+ */
501
+ async function checkCosmosDBEmulator(): Promise<boolean> {
502
+ return new Promise((resolve) => {
503
+ const socket = new net.Socket();
504
+
505
+ const timeout = setTimeout(() => {
506
+ socket.destroy();
507
+ resolve(false);
508
+ }, 2000);
509
+
510
+ socket.on('connect', () => {
511
+ clearTimeout(timeout);
512
+ socket.destroy();
513
+ resolve(true);
514
+ });
515
+
516
+ socket.on('error', () => {
517
+ clearTimeout(timeout);
518
+ resolve(false);
519
+ });
520
+
521
+ socket.connect(8081, 'localhost');
522
+ });
523
+ }
524
+
525
+ export function buildDevCommand(
526
+ runDevEnvironment: (options: DevOptions) => Promise<void> = startDevEnvironment,
527
+ verifyProject: (commandName: string, projectRoot?: string) => void = ensureSwallowKitProject
528
+ ): Command {
529
+ return new Command()
530
+ .name('dev')
531
+ .description('Start SwallowKit development server (Cosmos DB + Next.js + Azure Functions)')
532
+ .option('-p, --port <port>', 'Next.js port', '3000')
533
+ .option('-f, --functions-port <port>', 'Azure Functions port', '7071')
534
+ .option('--host <host>', 'Host name', 'localhost')
535
+ .option('--open', 'Open browser automatically', false)
536
+ .option('--verbose', 'Show verbose logs', false)
537
+ .option('--no-functions', 'Skip Azure Functions startup')
538
+ .option('--seed-env <environment>', 'Replace Cosmos DB Emulator data from dev-seeds/<environment> before startup')
539
+ .option('--mock-connectors', 'Start mock server for connector models (serves Zod-generated data)', false)
540
+ .option('--swa-port <port>', 'SWA authentication emulator port', '4280')
541
+ .option('--no-swa', 'Skip the SWA authentication emulator')
542
+ .action(async (options: ParsedDevActionOptions) => {
543
+ const normalizedOptions = normalizeParsedDevOptions(options);
544
+
545
+ // SwallowKit プロジェクトディレクトリかどうかを検証
546
+ verifyProject("dev");
547
+
548
+ console.log('🚀 Starting SwallowKit development environment...');
549
+ if (normalizedOptions.verbose) {
550
+ console.log('⚙️ Options:', normalizedOptions);
551
+ }
552
+
553
+ await runDevEnvironment(normalizedOptions);
554
+ });
555
+ }
556
+
557
+ export const devCommand = buildDevCommand();
558
+
559
+ interface CosmosInitializationResult {
560
+ endpoint: string;
561
+ key: string;
562
+ databaseName: string;
563
+ models: ModelInfo[];
564
+ }
565
+
566
+ async function initializeCosmosDB(databaseName: string): Promise<CosmosInitializationResult | null> {
567
+ try {
568
+ const connectionInfoResult = resolveLocalCosmosConnectionInfo(databaseName);
569
+ if (!connectionInfoResult.ok) {
570
+ if (connectionInfoResult.reason === 'missing-local-settings') {
571
+ console.log('⚠️ local.settings.json not found. Skipping Cosmos DB initialization.');
572
+ } else if (connectionInfoResult.reason === 'missing-connection-string') {
573
+ console.log('⚠️ CosmosDBConnection not found in local.settings.json. Skipping Cosmos DB initialization.');
574
+ } else {
575
+ console.log('⚠️ Invalid CosmosDB connection string format.');
576
+ }
577
+
578
+ return null;
579
+ }
580
+
581
+ console.log('🗄️ Initializing Cosmos DB...');
582
+ const { endpoint, key, databaseName: dbName, worktreeIsolationEnabled } = connectionInfoResult.value;
583
+ console.log(`📦 Cosmos DB database: ${dbName}`);
584
+ if (worktreeIsolationEnabled) {
585
+ console.log('🌳 Worktree isolation: enabled');
586
+ }
587
+
588
+ const client = new CosmosClient({
589
+ endpoint: endpoint,
590
+ key,
591
+ });
592
+
593
+ // Create database if not exists
594
+ const { database } = await client.databases.createIfNotExists({ id: dbName });
595
+ console.log(`✅ Database "${dbName}" ready`);
596
+
597
+ const models = await loadProjectModels();
598
+ for (const model of models) {
599
+ const containerName = getContainerNameForModel(model);
600
+
601
+ // Try creating container with full partition key definition first
602
+ let containerCreated = false;
603
+
604
+ try {
605
+ console.log(`🔧 Creating container "${containerName}" with partition key ${model.partitionKey}...`);
606
+ const containerResponse = await database.containers.createIfNotExists({
607
+ id: containerName,
608
+ partitionKey: {
609
+ paths: [model.partitionKey],
610
+ kind: PartitionKeyKind.Hash,
611
+ version: 2
612
+ }
613
+ });
614
+ console.log(`✅ Container "${containerName}" ready (status: ${containerResponse.statusCode})`);
615
+ containerCreated = true;
616
+ } catch (error: unknown) {
617
+ const message = error instanceof Error ? error.message : String(error);
618
+ console.log(`⚠️ Failed with full partition key definition: ${message}`);
619
+ console.log(`🔄 Retrying with simple partition key...`);
620
+ }
621
+
622
+ // If first attempt failed, try with simple partition key definition
623
+ if (!containerCreated) {
624
+ try {
625
+ const containerResponse = await database.containers.createIfNotExists({
626
+ id: containerName,
627
+ partitionKey: {
628
+ paths: [model.partitionKey]
629
+ }
630
+ });
631
+ console.log(`✅ Container "${containerName}" ready (status: ${containerResponse.statusCode})`);
632
+ } catch (containerError: any) {
633
+ console.error(`❌ Failed to create container "${containerName}":`, containerError.message);
634
+ console.error(`Error code: ${containerError.code}`);
635
+ if (containerError.body) {
636
+ console.error(`Response body:`, JSON.stringify(containerError.body, null, 2));
637
+ }
638
+ // Continue with other containers
639
+ }
640
+ }
641
+ }
642
+
643
+ console.log('✅ Cosmos DB initialization complete\n');
644
+ return { endpoint, key, databaseName: dbName, models };
645
+ } catch (error: any) {
646
+ console.error('⚠️ Cosmos DB initialization failed:', error.message);
647
+ if (error.stack) {
648
+ console.error('Stack trace:', error.stack);
649
+ }
650
+ console.log('💡 Make sure Cosmos DB Emulator is running');
651
+ return null;
652
+ }
653
+ }
654
+
655
+ async function startDevEnvironment(options: DevOptions) {
656
+ const port = options.port || '3000';
657
+ const functionsPort = options.functionsPort || '7071';
658
+ const swaPort = options.swaPort || '4280';
659
+
660
+ // Detect package manager from project lockfile
661
+ const pm = detectFromProject();
662
+ const pmCmd = getCommands(pm);
663
+ const backendLanguage = getBackendLanguage();
664
+ const authConfig = getAuthConfig();
665
+ const normalizedAuth = normalizeAuthConfig(authConfig);
666
+ const useSwaEmulator = Boolean(normalizedAuth && Object.values(normalizedAuth.schemes).some(scheme => scheme.provider === 'swa')) && !options.noSwa;
667
+ const swaCommand = useSwaEmulator ? await resolveSwaCliCommand(process.cwd()) : null;
668
+
669
+ if (useSwaEmulator && !swaCommand) {
670
+ const installCommand = getSwaCliInstallCommand(pm);
671
+ console.error('❌ SWA authentication requires Azure Static Web Apps CLI for local development.');
672
+ console.error(' Install it in this project and retry:');
673
+ console.error(`\n ${installCommand}\n`);
674
+ process.exitCode = 1;
675
+ return;
676
+ }
677
+
678
+ // プロセスを管理する配列
679
+ const processes: ChildProcess[] = [];
680
+ let functionsEnv: NodeJS.ProcessEnv = process.env;
681
+ let mockServer: ConnectorMockServer | null = null;
682
+ let envLocalPath = '';
683
+ let envLocalDefaultUrl = ''; // default Functions URL to restore on shutdown
684
+ const functionsBaseUrl = buildFunctionsBaseUrl(options.host, functionsPort);
685
+ let functionsReadinessPromise: Promise<boolean> | null = null;
686
+ let functionsReady = !!options.noFunctions;
687
+
688
+ // Cleanup processes on Ctrl+C
689
+ process.on('SIGINT', async () => {
690
+ console.log('\n🛑 Stopping development servers...');
691
+ // Restore .env.local to default Functions port on shutdown
692
+ if (envLocalPath && envLocalDefaultUrl) {
693
+ try {
694
+ if (fs.existsSync(envLocalPath)) {
695
+ const content = fs.readFileSync(envLocalPath, 'utf-8');
696
+ if (content.includes('BACKEND_FUNCTIONS_BASE_URL=') &&
697
+ !content.includes(`BACKEND_FUNCTIONS_BASE_URL=${envLocalDefaultUrl}`)) {
698
+ const restored = content.replace(
699
+ /^BACKEND_FUNCTIONS_BASE_URL=.*/m,
700
+ `BACKEND_FUNCTIONS_BASE_URL=${envLocalDefaultUrl}`
701
+ );
702
+ fs.writeFileSync(envLocalPath, restored, 'utf-8');
703
+ }
704
+ }
705
+ } catch { /* ignore */ }
706
+ }
707
+ if (mockServer) {
708
+ await mockServer.stop();
709
+ }
710
+ processes.forEach((proc) => {
711
+ if (proc && !proc.killed) {
712
+ proc.kill();
713
+ }
714
+ });
715
+ process.exit(0);
716
+ });
717
+
718
+ try {
719
+ // 1. Check for Next.js project
720
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
721
+ const nextConfigPathJs = path.join(process.cwd(), 'next.config.js');
722
+ const nextConfigPathTs = path.join(process.cwd(), 'next.config.ts');
723
+ const nextConfigPathMjs = path.join(process.cwd(), 'next.config.mjs');
724
+
725
+ if (!fs.existsSync(packageJsonPath)) {
726
+ console.log('❌ package.json not found.');
727
+ console.log('💡 Please run this command in the root directory of a Next.js project.');
728
+ process.exit(1);
729
+ }
730
+
731
+ if (!fs.existsSync(nextConfigPathJs) && !fs.existsSync(nextConfigPathTs) && !fs.existsSync(nextConfigPathMjs)) {
732
+ console.log('⚠️ next.config file not found. Is this a Next.js project?');
733
+ }
734
+
735
+ // 2. Check if Azure Functions exists
736
+ const functionsDir = path.join(process.cwd(), 'functions');
737
+ const hasFunctions = fs.existsSync(functionsDir) && hasFunctionsProject(functionsDir, backendLanguage);
738
+
739
+ let functionsCoreToolsCommand: FunctionsCoreToolsCommand | null = null;
740
+ let installedCoreToolsVersion: string | null = null;
741
+
742
+ if (hasFunctions && !options.noFunctions) {
743
+ installedCoreToolsVersion = await resolveInstalledCoreToolsVersion();
744
+ functionsCoreToolsCommand = buildFunctionsCoreToolsCommand(backendLanguage, installedCoreToolsVersion);
745
+
746
+ if (functionsCoreToolsCommand.command === 'func' && !installedCoreToolsVersion) {
747
+ console.log('');
748
+ console.log('⚠️ Azure Functions Core Tools not found.');
749
+ console.log('');
750
+
751
+ // Prompt user for installation
752
+ const readline = await import('readline');
753
+ const rl = readline.createInterface({
754
+ input: process.stdin,
755
+ output: process.stdout
756
+ });
757
+
758
+ const answer = await new Promise<string>((resolve) => {
759
+ rl.question('Would you like to install Azure Functions Core Tools? (y/n): ', resolve);
760
+ });
761
+ rl.close();
762
+
763
+ if (answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes') {
764
+ console.log('📦 Installing Azure Functions Core Tools...');
765
+ console.log(' This may take a few minutes.');
766
+
767
+ const installProcess = spawn(pm, pm === 'pnpm' ? ['add', '-g', 'azure-functions-core-tools@4'] : ['install', '-g', 'azure-functions-core-tools@4'], {
768
+ shell: true,
769
+ stdio: 'inherit',
770
+ });
771
+
772
+ await new Promise<void>((resolve, reject) => {
773
+ installProcess.on('close', (code) => {
774
+ if (code === 0) {
775
+ console.log('✅ Azure Functions Core Tools installed successfully.');
776
+ resolve();
777
+ } else {
778
+ console.error('❌ Installation failed.');
779
+ console.log('💡 Please install manually:');
780
+ console.log(` ${pmCmd.addGlobal} azure-functions-core-tools@4`);
781
+ reject(new Error(`Installation failed with code ${code}`));
782
+ }
783
+ });
784
+ installProcess.on('error', reject);
785
+ });
786
+ } else {
787
+ console.log('');
788
+ console.log('ℹ️ Skipping Azure Functions startup.');
789
+ console.log('💡 To install later:');
790
+ console.log(` ${pmCmd.addGlobal} azure-functions-core-tools@4`);
791
+ console.log('');
792
+ // Skip Azure Functions startup
793
+ options.noFunctions = true;
794
+ }
795
+ } else if (functionsCoreToolsCommand.command !== 'func') {
796
+ console.log(`ℹ️ Using ${functionsCoreToolsCommand.label}.`);
797
+ }
798
+
799
+ if (!options.noFunctions) {
800
+ // Check if Cosmos DB Emulator is running
801
+ const cosmosRunning = await checkCosmosDBEmulator();
802
+
803
+ if (!cosmosRunning) {
804
+ console.log('');
805
+ console.log('❌ Cosmos DB Emulator is not running.');
806
+ console.log('');
807
+ console.log('💡 Please start Cosmos DB Emulator manually:');
808
+ console.log(' C:\\Program Files\\Azure Cosmos DB Emulator\\CosmosDB.Emulator.exe');
809
+ console.log('');
810
+ console.log(' Or search for "Azure Cosmos DB Emulator" in the Start menu.');
811
+ console.log('');
812
+ process.exit(1);
813
+ }
814
+
815
+ // Initialize Cosmos DB before starting Functions
816
+ const databaseName = getDefaultCosmosDatabaseName();
817
+ const cosmosInitialization = await initializeCosmosDB(databaseName);
818
+ if (options.seedEnv && cosmosInitialization) {
819
+ await applyDevSeedEnvironment({
820
+ client: new CosmosClient({
821
+ endpoint: cosmosInitialization.endpoint,
822
+ key: cosmosInitialization.key,
823
+ }),
824
+ databaseName: cosmosInitialization.databaseName,
825
+ environment: options.seedEnv,
826
+ models: cosmosInitialization.models,
827
+ });
828
+ }
829
+
830
+ console.log('');
831
+ console.log('🚀 Starting Azure Functions...');
832
+
833
+ if (backendLanguage === 'typescript') {
834
+ const functionsNodeModules = path.join(functionsDir, 'node_modules');
835
+ if (!fs.existsSync(functionsNodeModules)) {
836
+ console.log('📦 Installing Azure Functions dependencies...');
837
+ await runCommand(pm, ['install'], functionsDir, `${pm} install`);
838
+ }
839
+ } else if (backendLanguage === 'csharp') {
840
+ console.log('ℹ️ C# Azure Functions can take longer on cold start while the worker builds.');
841
+ } else {
842
+ functionsEnv = await preparePythonFunctionsEnvironment(functionsDir);
843
+ }
844
+
845
+ if (cosmosInitialization) {
846
+ functionsEnv = buildFunctionsCosmosEnvironment(functionsEnv, cosmosInitialization.databaseName);
847
+ }
848
+ }
849
+ }
850
+
851
+ if (hasFunctions && !options.noFunctions) {
852
+ // Build shared package before starting Functions
853
+ const sharedDir = path.join(process.cwd(), 'shared');
854
+ const sharedPkgPath = path.join(sharedDir, 'package.json');
855
+ if (fs.existsSync(sharedDir) && fs.existsSync(sharedPkgPath)) {
856
+ const sharedPkg = JSON.parse(fs.readFileSync(sharedPkgPath, 'utf-8'));
857
+ if (sharedPkg.scripts?.build) {
858
+ console.log('📦 Building shared package...');
859
+ const filterArgs = pm === 'pnpm'
860
+ ? ['run', '--filter', 'shared', 'build']
861
+ : ['run', '--workspace=shared', 'build'];
862
+ const sharedBuild = spawn(pm, filterArgs, {
863
+ cwd: process.cwd(),
864
+ shell: true,
865
+ stdio: 'inherit',
866
+ });
867
+
868
+ await new Promise<void>((resolve, reject) => {
869
+ sharedBuild.on('close', (code) => {
870
+ if (code === 0) {
871
+ console.log('✅ Shared package built successfully');
872
+ resolve();
873
+ } else {
874
+ reject(new Error(`Shared package build failed with code ${code}`));
875
+ }
876
+ });
877
+ sharedBuild.on('error', reject);
878
+ });
879
+ } else {
880
+ console.log('⚠️ Shared package has no build script — skipping build. Run "swallowkit add-auth" to fix.');
881
+ }
882
+ }
883
+
884
+ // Build TypeScript functions after shared package (functions import from shared)
885
+ if (backendLanguage === 'typescript') {
886
+ const functionsPkgPath = path.join(functionsDir, 'package.json');
887
+ if (fs.existsSync(functionsPkgPath)) {
888
+ const functionsPkg = JSON.parse(fs.readFileSync(functionsPkgPath, 'utf-8'));
889
+ if (functionsPkg.scripts?.build) {
890
+ console.log('📦 Building TypeScript Azure Functions...');
891
+ await runCommand(pm, ['run', 'build'], functionsDir, `${pm} run build`);
892
+ }
893
+ }
894
+ }
895
+
896
+ // Azure Functions を起動
897
+ const functionsCommand = functionsCoreToolsCommand ?? buildFunctionsCoreToolsCommand(backendLanguage, installedCoreToolsVersion);
898
+ const funcProcess = spawn(functionsCommand.command, [...functionsCommand.argsPrefix, ...buildFunctionsStartArgs(functionsPort)], {
899
+ cwd: functionsDir,
900
+ shell: true,
901
+ stdio: 'pipe', // Always pipe to capture output
902
+ env: functionsEnv
903
+ });
904
+ let pythonWorkerMissing = false;
905
+
906
+ // Functions の出力をそのまま表示(プレフィックス付き)
907
+ if (funcProcess.stdout) {
908
+ funcProcess.stdout.on('data', (data) => {
909
+ const output = data.toString();
910
+ // 各行にプレフィックスを付けて出力
911
+ const lines = output.split('\n').filter((line: string) => line.trim());
912
+ lines.forEach((line: string) => {
913
+ if (
914
+ backendLanguage === 'python' &&
915
+ (line.includes('WorkerConfig for runtime: python not found') || line.includes('DefaultWorkerPath:'))
916
+ ) {
917
+ pythonWorkerMissing = true;
918
+ }
919
+ console.log(`[Functions] ${line}`);
920
+ });
921
+ });
922
+ }
923
+
924
+ if (funcProcess.stderr) {
925
+ funcProcess.stderr.on('data', (data) => {
926
+ const output = data.toString();
927
+ const lines = output.split('\n').filter((line: string) => line.trim());
928
+ lines.forEach((line: string) => {
929
+ if (
930
+ backendLanguage === 'python' &&
931
+ (line.includes('WorkerConfig for runtime: python not found') || line.includes('DefaultWorkerPath:'))
932
+ ) {
933
+ pythonWorkerMissing = true;
934
+ }
935
+ console.error(`[Functions Error] ${line}`);
936
+ });
937
+ });
938
+ }
939
+
940
+ processes.push(funcProcess);
941
+
942
+ funcProcess.on('error', (error) => {
943
+ console.error('⚠️ Azure Functions startup error:', error.message);
944
+ console.log('💡 Please ensure Azure Functions Core Tools is installed');
945
+ console.log(` ${pmCmd.addGlobal} azure-functions-core-tools@4`);
946
+ });
947
+
948
+ funcProcess.on('close', (code) => {
949
+ if (code !== 0) {
950
+ console.log(`\n⏹️ Azure Functions exited (exit code: ${code})`);
951
+ if (backendLanguage === 'python' && pythonWorkerMissing) {
952
+ console.log('💡 Your Azure Functions Core Tools installation is missing the Python worker for this OS/architecture.');
953
+ console.log(' Reinstall a matching Core Tools v4 package (Windows users should prefer the official x64/x86 MSI for their machine).');
954
+ console.log(' SwallowKit local Python dev uses functions/.venv and requirements.txt, but Core Tools still needs its own bundled Python worker.');
955
+ }
956
+ }
957
+ });
958
+
959
+ console.log(`⏳ Waiting for Azure Functions to accept requests at ${functionsBaseUrl}...`);
960
+ functionsReadinessPromise = waitForHttpServerReady(
961
+ functionsBaseUrl,
962
+ getFunctionsReadinessTimeoutMs(backendLanguage)
963
+ );
964
+ } else if (!hasFunctions) {
965
+ console.log('');
966
+ console.log('ℹ️ functions/ directory not found. Starting Next.js only.');
967
+ } else if (options.noFunctions) {
968
+ console.log('');
969
+ console.log('ℹ️ --no-functions specified. Skipping Azure Functions.');
970
+ }
971
+
972
+ console.log('');
973
+ console.log('🚀 Starting Next.js development server...');
974
+
975
+ // Mock connector server — start proxy if --mock-connectors is enabled
976
+ let bffTargetPort = functionsPort;
977
+
978
+ if (options.mockConnectors) {
979
+ const allModels = await loadProjectModels();
980
+ const connectorModels = allModels.filter((m) => m.connectorConfig);
981
+
982
+ // Resolve auth config — auth functions use RDB connectors, mocked alongside other models
983
+ let mockAuthConfig: { jwtSecret: string; tokenExpiry?: string; customJwt?: { userTable: string; loginIdColumn: string; passwordHashColumn: string; rolesColumn: string }; defaultPolicy?: "authenticated" | "anonymous" } | undefined;
984
+ if (authConfig?.provider === 'custom-jwt' && authConfig.customJwt) {
985
+ // Read JWT_SECRET from functions/local.settings.json if available
986
+ let jwtSecret = 'dev-jwt-secret-change-in-production-min-32-chars!!';
987
+ try {
988
+ const localSettingsPath = path.join(process.cwd(), 'functions', 'local.settings.json');
989
+ if (fs.existsSync(localSettingsPath)) {
990
+ const localSettings = JSON.parse(fs.readFileSync(localSettingsPath, 'utf-8'));
991
+ jwtSecret = localSettings.Values?.[authConfig.customJwt.jwtSecretEnv || 'JWT_SECRET'] || jwtSecret;
992
+ }
993
+ } catch { /* ignore */ }
994
+ mockAuthConfig = {
995
+ jwtSecret,
996
+ tokenExpiry: authConfig.customJwt.tokenExpiry,
997
+ customJwt: {
998
+ userTable: authConfig.customJwt.userTable,
999
+ loginIdColumn: authConfig.customJwt.loginIdColumn,
1000
+ passwordHashColumn: authConfig.customJwt.passwordHashColumn,
1001
+ rolesColumn: authConfig.customJwt.rolesColumn,
1002
+ },
1003
+ defaultPolicy: authConfig.authorization?.defaultPolicy === "public" ? "anonymous" :
1004
+ authConfig.authorization?.defaultPolicy === "authenticated" || authConfig.authorization?.defaultPolicy === "anonymous"
1005
+ ? authConfig.authorization.defaultPolicy : undefined,
1006
+ };
1007
+ }
1008
+
1009
+ if (connectorModels.length > 0 || mockAuthConfig) {
1010
+ const mockPort = parseInt(functionsPort, 10) + 1;
1011
+ mockServer = new ConnectorMockServer({
1012
+ port: mockPort,
1013
+ functionsTarget: `${options.host || 'localhost'}:${functionsPort}`,
1014
+ connectorModels,
1015
+ allModels,
1016
+ seedEnv: options.seedEnv,
1017
+ host: options.host || 'localhost',
1018
+ authConfig: mockAuthConfig,
1019
+ });
1020
+
1021
+ await mockServer.start();
1022
+ bffTargetPort = String(mockPort);
1023
+
1024
+ const modelCount = connectorModels.length + (mockAuthConfig ? 1 : 0);
1025
+ console.log('');
1026
+ console.log(`🔌 Mock server started (port: ${mockPort}) — ${modelCount} model(s) mocked via Zod/seed data`);
1027
+ for (const m of connectorModels) {
1028
+ const ops = m.connectorConfig!.operations.join(', ');
1029
+ console.log(` - ${m.name} [${ops}]`);
1030
+ }
1031
+ if (mockAuthConfig) {
1032
+ console.log(` - auth [login, me, logout]`);
1033
+ }
1034
+ console.log(` Other routes → proxied to Azure Functions (port: ${functionsPort})`);
1035
+ } else {
1036
+ console.log('');
1037
+ console.log('ℹ️ --mock-connectors specified but no connector models found. Skipping mock server.');
1038
+ }
1039
+ }
1040
+
1041
+ // 5. Start Next.js development server
1042
+ const nextArgs = buildNextDevArgs(pm, port);
1043
+
1044
+ // Ensure .env.local points to bffTargetPort so Next.js reads the correct backend URL.
1045
+ // When --mock-connectors is active, bffTargetPort = mock port (7072); otherwise = Functions port (7071).
1046
+ // Next.js may load .env.local values that override spawn env vars, so we must keep them in sync.
1047
+ envLocalPath = path.join(process.cwd(), '.env.local');
1048
+ envLocalDefaultUrl = functionsBaseUrl;
1049
+ const bffTargetUrl = buildFunctionsBaseUrl(options.host, bffTargetPort);
1050
+ try {
1051
+ if (fs.existsSync(envLocalPath)) {
1052
+ const envContent = fs.readFileSync(envLocalPath, 'utf-8');
1053
+ if (envContent.includes('BACKEND_FUNCTIONS_BASE_URL=') &&
1054
+ !envContent.includes(`BACKEND_FUNCTIONS_BASE_URL=${bffTargetUrl}`)) {
1055
+ const updated = envContent.replace(
1056
+ /^BACKEND_FUNCTIONS_BASE_URL=.*/m,
1057
+ `BACKEND_FUNCTIONS_BASE_URL=${bffTargetUrl}`
1058
+ );
1059
+ fs.writeFileSync(envLocalPath, updated, 'utf-8');
1060
+ }
1061
+ }
1062
+ } catch { /* ignore */ }
1063
+
1064
+ const nextEnv: NodeJS.ProcessEnv = {
1065
+ ...process.env,
1066
+ BACKEND_FUNCTIONS_BASE_URL: bffTargetUrl,
1067
+ FUNCTIONS_BASE_URL: bffTargetUrl,
1068
+ };
1069
+
1070
+ const nextProcess = spawn(pm === 'pnpm' ? 'pnpm' : 'npx', nextArgs, {
1071
+ cwd: process.cwd(),
1072
+ shell: true,
1073
+ stdio: options.verbose ? 'inherit' : 'inherit',
1074
+ env: nextEnv,
1075
+ });
1076
+
1077
+ processes.push(nextProcess);
1078
+
1079
+ nextProcess.on('error', (error) => {
1080
+ console.error('❌ Next.js startup error:', error.message);
1081
+ process.exit(1);
1082
+ });
1083
+
1084
+ nextProcess.on('close', (code) => {
1085
+ if (code !== 0) {
1086
+ console.log(`\n⏹️ Next.js exited (exit code: ${code})`);
1087
+ }
1088
+ // Exit all processes when Next.js exits
1089
+ if (mockServer) {
1090
+ mockServer.stop().catch(() => {});
1091
+ }
1092
+ processes.forEach((proc) => {
1093
+ if (proc && !proc.killed) {
1094
+ proc.kill();
1095
+ }
1096
+ });
1097
+ process.exit(code || 0);
1098
+ });
1099
+
1100
+ if (functionsReadinessPromise) {
1101
+ functionsReady = await functionsReadinessPromise;
1102
+ console.log('');
1103
+ if (functionsReady) {
1104
+ console.log(`✅ Azure Functions ready (port: ${functionsPort})`);
1105
+ } else {
1106
+ console.log(`⚠️ Azure Functions is still starting: ${functionsBaseUrl}`);
1107
+ }
1108
+ }
1109
+
1110
+ let swaReady = false;
1111
+ if (useSwaEmulator && swaCommand) {
1112
+ const nextUrl = `http://${options.host || 'localhost'}:${port}`;
1113
+ console.log(`⏳ Waiting for Next.js before starting the SWA emulator at ${nextUrl}...`);
1114
+ const nextReady = await waitForHttpServerReady(nextUrl);
1115
+ if (!nextReady) {
1116
+ throw new Error(`Next.js did not become ready at ${nextUrl}`);
1117
+ }
1118
+
1119
+ console.log(`🔐 Starting SWA authentication emulator (port: ${swaPort})...`);
1120
+ const swaProcess = spawn(swaCommand, buildSwaStartArgs(options.host, port, swaPort), {
1121
+ cwd: process.cwd(),
1122
+ shell: true,
1123
+ stdio: 'inherit',
1124
+ env: process.env,
1125
+ });
1126
+ processes.push(swaProcess);
1127
+ swaProcess.on('error', (error) => {
1128
+ console.error('❌ SWA CLI startup error:', error.message);
1129
+ });
1130
+
1131
+ const swaUrl = `http://${options.host || 'localhost'}:${swaPort}`;
1132
+ swaReady = await waitForHttpServerReady(swaUrl);
1133
+ if (!swaReady) {
1134
+ throw new Error(`SWA authentication emulator did not become ready at ${swaUrl}`);
1135
+ }
1136
+ }
1137
+
1138
+ console.log('');
1139
+ console.log('✅ SwallowKit development environment is running!');
1140
+ console.log('');
1141
+ if (useSwaEmulator) {
1142
+ const swaUrl = `http://${options.host || 'localhost'}:${swaPort}`;
1143
+ console.log('🔐 SWA authenticated app:');
1144
+ console.log(` ${swaUrl}`);
1145
+ console.log('');
1146
+ console.log('🔑 Local sign-in:');
1147
+ console.log(` ${swaUrl}/.auth/login/aad`);
1148
+ console.log(' Enter any username and select Login.');
1149
+ console.log(' The "authenticated" role is added automatically.');
1150
+ console.log('');
1151
+ console.log('📱 Next.js direct access (authentication is not emulated):');
1152
+ console.log(` http://${options.host || 'localhost'}:${port}`);
1153
+ } else {
1154
+ console.log(`📱 Next.js: http://${options.host || 'localhost'}:${port}`);
1155
+ }
1156
+ if (hasFunctions && !options.noFunctions) {
1157
+ console.log(`${functionsReady ? '⚡ Azure Functions' : '⏳ Azure Functions (starting)'}: ${functionsBaseUrl}`);
1158
+ }
1159
+ if (mockServer) {
1160
+ console.log(`🔌 Mock Proxy: ${bffTargetUrl} (BFF → here)`);
1161
+ }
1162
+ console.log('');
1163
+ if (hasFunctions && !options.noFunctions && functionsReady) {
1164
+ console.log('💡 Azure Functions and Next.js BFF are connected');
1165
+ } else if (hasFunctions && !options.noFunctions) {
1166
+ console.log('💡 Azure Functions is still warming up; BFF routes can fail until the backend responds.');
1167
+ }
1168
+ if (mockServer) {
1169
+ console.log('💡 Connector models served from mock server (Zod-generated data)');
1170
+ }
1171
+ if (swaReady) {
1172
+ console.log('💡 Open the app through the SWA port when testing authenticated pages and CRUD APIs.');
1173
+ }
1174
+ console.log('');
1175
+
1176
+ if (options.open) {
1177
+ const url = useSwaEmulator
1178
+ ? `http://${options.host || 'localhost'}:${swaPort}`
1179
+ : `http://${options.host || 'localhost'}:${port}`;
1180
+ console.log(`🌐 Opening browser: ${url}`);
1181
+ const start = process.platform === 'darwin' ? 'open' :
1182
+ process.platform === 'win32' ? 'start' : 'xdg-open';
1183
+ spawn(start, [url], { shell: true });
1184
+ console.log('');
1185
+ }
1186
+
1187
+ console.log('🛑 Press Ctrl+C to stop');
1188
+ console.log('');
1189
+
1190
+ } catch (error) {
1191
+ console.error('❌ Failed to start development environment:', error instanceof Error ? error.message : error);
1192
+ processes.forEach((proc) => {
1193
+ if (proc && !proc.killed) {
1194
+ proc.kill();
1195
+ }
1196
+ });
1197
+ process.exit(1);
1198
+ }
1199
+ }
1200
+
1201
+ async function resolveSwaCliCommand(projectRoot: string): Promise<string | null> {
1202
+ const binaryName = process.platform === 'win32' ? 'swa.cmd' : 'swa';
1203
+ const localCommand = path.join(projectRoot, 'node_modules', '.bin', binaryName);
1204
+ if (fs.existsSync(localCommand) && await checkCommand(localCommand, ['--version'], {
1205
+ cwd: projectRoot,
1206
+ shell: process.platform === 'win32',
1207
+ })) {
1208
+ return localCommand;
1209
+ }
1210
+
1211
+ if (await checkCommand('swa', ['--version'], { cwd: projectRoot })) {
1212
+ return 'swa';
1213
+ }
1214
+
1215
+ return null;
1216
+ }
1217
+
1218
+ async function runCommand(
1219
+ command: string,
1220
+ args: string[],
1221
+ cwd: string,
1222
+ label: string,
1223
+ env?: NodeJS.ProcessEnv,
1224
+ shell = true
1225
+ ): Promise<void> {
1226
+ await new Promise<void>((resolve, reject) => {
1227
+ const child = spawn(command, args, {
1228
+ cwd,
1229
+ shell,
1230
+ stdio: 'inherit',
1231
+ env,
1232
+ });
1233
+
1234
+ child.on('close', (code) => {
1235
+ if (code === 0) {
1236
+ resolve();
1237
+ } else {
1238
+ reject(new Error(`${label} failed with code ${code}`));
1239
+ }
1240
+ });
1241
+
1242
+ child.on('error', reject);
1243
+ });
1244
+ }
1245
+
1246
+ function hasFunctionsProject(functionsDir: string, backendLanguage: BackendLanguage): boolean {
1247
+ if (backendLanguage === 'typescript') {
1248
+ return fs.existsSync(path.join(functionsDir, 'package.json'));
1249
+ }
1250
+
1251
+ return fs.existsSync(path.join(functionsDir, 'host.json'));
1252
+ }