swallowkit 1.0.0-beta.2 → 1.0.0-beta.21

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 (191) hide show
  1. package/LICENSE +21 -21
  2. package/README.ja.md +312 -215
  3. package/README.md +369 -216
  4. package/dist/__tests__/fixtures.d.ts +22 -0
  5. package/dist/__tests__/fixtures.d.ts.map +1 -0
  6. package/dist/__tests__/fixtures.js +146 -0
  7. package/dist/__tests__/fixtures.js.map +1 -0
  8. package/dist/cli/commands/add-auth.d.ts +10 -0
  9. package/dist/cli/commands/add-auth.d.ts.map +1 -0
  10. package/dist/cli/commands/add-auth.js +444 -0
  11. package/dist/cli/commands/add-auth.js.map +1 -0
  12. package/dist/cli/commands/add-connector.d.ts +20 -0
  13. package/dist/cli/commands/add-connector.d.ts.map +1 -0
  14. package/dist/cli/commands/add-connector.js +163 -0
  15. package/dist/cli/commands/add-connector.js.map +1 -0
  16. package/dist/cli/commands/create-model.d.ts +1 -4
  17. package/dist/cli/commands/create-model.d.ts.map +1 -1
  18. package/dist/cli/commands/create-model.js +21 -82
  19. package/dist/cli/commands/create-model.js.map +1 -1
  20. package/dist/cli/commands/dev-seeds.d.ts +35 -0
  21. package/dist/cli/commands/dev-seeds.d.ts.map +1 -0
  22. package/dist/cli/commands/dev-seeds.js +292 -0
  23. package/dist/cli/commands/dev-seeds.js.map +1 -0
  24. package/dist/cli/commands/dev.d.ts +19 -0
  25. package/dist/cli/commands/dev.d.ts.map +1 -1
  26. package/dist/cli/commands/dev.js +476 -117
  27. package/dist/cli/commands/dev.js.map +1 -1
  28. package/dist/cli/commands/index.d.ts +1 -0
  29. package/dist/cli/commands/index.d.ts.map +1 -1
  30. package/dist/cli/commands/index.js +3 -1
  31. package/dist/cli/commands/index.js.map +1 -1
  32. package/dist/cli/commands/init.d.ts +13 -0
  33. package/dist/cli/commands/init.d.ts.map +1 -1
  34. package/dist/cli/commands/init.js +2627 -1708
  35. package/dist/cli/commands/init.js.map +1 -1
  36. package/dist/cli/commands/scaffold.d.ts +3 -0
  37. package/dist/cli/commands/scaffold.d.ts.map +1 -1
  38. package/dist/cli/commands/scaffold.js +617 -129
  39. package/dist/cli/commands/scaffold.js.map +1 -1
  40. package/dist/cli/index.d.ts +5 -1
  41. package/dist/cli/index.d.ts.map +1 -1
  42. package/dist/cli/index.js +164 -42
  43. package/dist/cli/index.js.map +1 -1
  44. package/dist/core/config.d.ts +8 -2
  45. package/dist/core/config.d.ts.map +1 -1
  46. package/dist/core/config.js +90 -4
  47. package/dist/core/config.js.map +1 -1
  48. package/dist/core/mock/connector-mock-server.d.ts +101 -0
  49. package/dist/core/mock/connector-mock-server.d.ts.map +1 -0
  50. package/dist/core/mock/connector-mock-server.js +480 -0
  51. package/dist/core/mock/connector-mock-server.js.map +1 -0
  52. package/dist/core/mock/zod-mock-generator.d.ts +14 -0
  53. package/dist/core/mock/zod-mock-generator.d.ts.map +1 -0
  54. package/dist/core/mock/zod-mock-generator.js +163 -0
  55. package/dist/core/mock/zod-mock-generator.js.map +1 -0
  56. package/dist/core/operations/create-model.d.ts +15 -0
  57. package/dist/core/operations/create-model.d.ts.map +1 -0
  58. package/dist/core/operations/create-model.js +171 -0
  59. package/dist/core/operations/create-model.js.map +1 -0
  60. package/dist/core/operations/runtime.d.ts +32 -0
  61. package/dist/core/operations/runtime.d.ts.map +1 -0
  62. package/dist/core/operations/runtime.js +225 -0
  63. package/dist/core/operations/runtime.js.map +1 -0
  64. package/dist/core/operations/scaffold-machine.d.ts +16 -0
  65. package/dist/core/operations/scaffold-machine.d.ts.map +1 -0
  66. package/dist/core/operations/scaffold-machine.js +63 -0
  67. package/dist/core/operations/scaffold-machine.js.map +1 -0
  68. package/dist/core/project/manifest.d.ts +92 -0
  69. package/dist/core/project/manifest.d.ts.map +1 -0
  70. package/dist/core/project/manifest.js +321 -0
  71. package/dist/core/project/manifest.js.map +1 -0
  72. package/dist/core/project/validation.d.ts +20 -0
  73. package/dist/core/project/validation.d.ts.map +1 -0
  74. package/dist/core/project/validation.js +204 -0
  75. package/dist/core/project/validation.js.map +1 -0
  76. package/dist/core/scaffold/auth-generator.d.ts +38 -0
  77. package/dist/core/scaffold/auth-generator.d.ts.map +1 -0
  78. package/dist/core/scaffold/auth-generator.js +1244 -0
  79. package/dist/core/scaffold/auth-generator.js.map +1 -0
  80. package/dist/core/scaffold/connector-functions-generator.d.ts +41 -0
  81. package/dist/core/scaffold/connector-functions-generator.d.ts.map +1 -0
  82. package/dist/core/scaffold/connector-functions-generator.js +1027 -0
  83. package/dist/core/scaffold/connector-functions-generator.js.map +1 -0
  84. package/dist/core/scaffold/functions-generator.d.ts +7 -1
  85. package/dist/core/scaffold/functions-generator.d.ts.map +1 -1
  86. package/dist/core/scaffold/functions-generator.js +920 -213
  87. package/dist/core/scaffold/functions-generator.js.map +1 -1
  88. package/dist/core/scaffold/model-parser.d.ts +20 -1
  89. package/dist/core/scaffold/model-parser.d.ts.map +1 -1
  90. package/dist/core/scaffold/model-parser.js +329 -135
  91. package/dist/core/scaffold/model-parser.js.map +1 -1
  92. package/dist/core/scaffold/nextjs-generator.d.ts +8 -0
  93. package/dist/core/scaffold/nextjs-generator.d.ts.map +1 -1
  94. package/dist/core/scaffold/nextjs-generator.js +314 -182
  95. package/dist/core/scaffold/nextjs-generator.js.map +1 -1
  96. package/dist/core/scaffold/openapi-generator.d.ts +3 -0
  97. package/dist/core/scaffold/openapi-generator.d.ts.map +1 -0
  98. package/dist/core/scaffold/openapi-generator.js +190 -0
  99. package/dist/core/scaffold/openapi-generator.js.map +1 -0
  100. package/dist/core/scaffold/ui-generator.d.ts +10 -4
  101. package/dist/core/scaffold/ui-generator.d.ts.map +1 -1
  102. package/dist/core/scaffold/ui-generator.js +768 -663
  103. package/dist/core/scaffold/ui-generator.js.map +1 -1
  104. package/dist/database/base-model.d.ts +3 -3
  105. package/dist/database/base-model.js +3 -3
  106. package/dist/index.d.ts +2 -2
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.js +2 -1
  109. package/dist/index.js.map +1 -1
  110. package/dist/machine/contracts.d.ts +16 -0
  111. package/dist/machine/contracts.d.ts.map +1 -0
  112. package/dist/machine/contracts.js +3 -0
  113. package/dist/machine/contracts.js.map +1 -0
  114. package/dist/machine/errors.d.ts +11 -0
  115. package/dist/machine/errors.d.ts.map +1 -0
  116. package/dist/machine/errors.js +34 -0
  117. package/dist/machine/errors.js.map +1 -0
  118. package/dist/machine/index.d.ts +3 -0
  119. package/dist/machine/index.d.ts.map +1 -0
  120. package/dist/machine/index.js +156 -0
  121. package/dist/machine/index.js.map +1 -0
  122. package/dist/mcp/index.d.ts +25 -0
  123. package/dist/mcp/index.d.ts.map +1 -0
  124. package/dist/mcp/index.js +184 -0
  125. package/dist/mcp/index.js.map +1 -0
  126. package/dist/types/index.d.ts +65 -0
  127. package/dist/types/index.d.ts.map +1 -1
  128. package/dist/utils/package-manager.d.ts +109 -0
  129. package/dist/utils/package-manager.d.ts.map +1 -0
  130. package/dist/utils/package-manager.js +215 -0
  131. package/dist/utils/package-manager.js.map +1 -0
  132. package/package.json +85 -73
  133. package/src/__tests__/__snapshots__/functions-generator.test.ts.snap +1139 -0
  134. package/src/__tests__/__snapshots__/nextjs-generator.test.ts.snap +194 -0
  135. package/src/__tests__/__snapshots__/ui-generator.test.ts.snap +532 -0
  136. package/src/__tests__/auth.test.ts +654 -0
  137. package/src/__tests__/config.test.ts +263 -0
  138. package/src/__tests__/connector-functions-generator.test.ts +288 -0
  139. package/src/__tests__/connector-mock-server.test.ts +439 -0
  140. package/src/__tests__/connector-model-bff.test.ts +162 -0
  141. package/src/__tests__/dev-seeds.test.ts +112 -0
  142. package/src/__tests__/dev.test.ts +154 -0
  143. package/src/__tests__/fixtures.ts +144 -0
  144. package/src/__tests__/functions-generator.test.ts +237 -0
  145. package/src/__tests__/init.test.ts +80 -0
  146. package/src/__tests__/machine.test.ts +212 -0
  147. package/src/__tests__/mcp.test.ts +56 -0
  148. package/src/__tests__/model-parser.test.ts +72 -0
  149. package/src/__tests__/nextjs-generator.test.ts +97 -0
  150. package/src/__tests__/openapi-generator.test.ts +43 -0
  151. package/src/__tests__/package-manager.test.ts +189 -0
  152. package/src/__tests__/scaffold.test.ts +39 -0
  153. package/src/__tests__/string-utils.test.ts +75 -0
  154. package/src/__tests__/ui-generator.test.ts +144 -0
  155. package/src/__tests__/zod-mock-generator.test.ts +132 -0
  156. package/src/cli/commands/add-auth.ts +500 -0
  157. package/src/cli/commands/add-connector.ts +158 -0
  158. package/src/cli/commands/create-model.ts +62 -0
  159. package/src/cli/commands/dev-seeds.ts +358 -0
  160. package/src/cli/commands/dev.ts +962 -0
  161. package/src/cli/commands/index.ts +9 -0
  162. package/src/cli/commands/init.ts +3371 -0
  163. package/src/cli/commands/provision.ts +193 -0
  164. package/src/cli/commands/scaffold.ts +1211 -0
  165. package/src/cli/index.ts +193 -0
  166. package/src/core/config.ts +308 -0
  167. package/src/core/mock/connector-mock-server.ts +555 -0
  168. package/src/core/mock/zod-mock-generator.ts +205 -0
  169. package/src/core/operations/create-model.ts +174 -0
  170. package/src/core/operations/runtime.ts +235 -0
  171. package/src/core/operations/scaffold-machine.ts +91 -0
  172. package/src/core/project/manifest.ts +402 -0
  173. package/src/core/project/validation.ts +221 -0
  174. package/src/core/scaffold/auth-generator.ts +1284 -0
  175. package/src/core/scaffold/connector-functions-generator.ts +1128 -0
  176. package/src/core/scaffold/functions-generator.ts +970 -0
  177. package/src/core/scaffold/model-parser.ts +841 -0
  178. package/src/core/scaffold/nextjs-generator.ts +370 -0
  179. package/src/core/scaffold/openapi-generator.ts +212 -0
  180. package/src/core/scaffold/ui-generator.ts +1061 -0
  181. package/src/database/base-model.ts +184 -0
  182. package/src/database/client.ts +140 -0
  183. package/src/database/repository.ts +104 -0
  184. package/src/database/runtime-check.ts +25 -0
  185. package/src/index.ts +27 -0
  186. package/src/machine/contracts.ts +17 -0
  187. package/src/machine/errors.ts +34 -0
  188. package/src/machine/index.ts +173 -0
  189. package/src/mcp/index.ts +185 -0
  190. package/src/types/index.ts +134 -0
  191. package/src/utils/package-manager.ts +229 -0
@@ -0,0 +1,962 @@
1
+ import { Command } from 'commander';
2
+ import { spawn, ChildProcess } from 'child_process';
3
+ import * as path from 'path';
4
+ import * as fs from 'fs';
5
+ import * as os from 'os';
6
+ import * as net from 'net';
7
+ import { CosmosClient, PartitionKeyKind } from '@azure/cosmos';
8
+ import { ensureSwallowKitProject, getBackendLanguage, getAuthConfig } from '../../core/config';
9
+ import { ModelInfo } from '../../core/scaffold/model-parser';
10
+ import { applyDevSeedEnvironment, getContainerNameForModel, loadProjectModels } from './dev-seeds';
11
+ import { BackendLanguage } from '../../types';
12
+ import { detectFromProject, getCommands } from '../../utils/package-manager';
13
+ import { ConnectorMockServer } from '../../core/mock/connector-mock-server';
14
+
15
+ export interface DevOptions {
16
+ port?: string;
17
+ functionsPort?: string;
18
+ host?: string;
19
+ open?: boolean;
20
+ verbose?: boolean;
21
+ noFunctions?: boolean;
22
+ seedEnv?: string;
23
+ mockConnectors?: boolean;
24
+ }
25
+
26
+ type ParsedDevActionOptions = DevOptions & {
27
+ functions?: boolean;
28
+ };
29
+
30
+ function normalizeParsedDevOptions(options: ParsedDevActionOptions): DevOptions {
31
+ return {
32
+ ...options,
33
+ noFunctions: options.noFunctions ?? options.functions === false,
34
+ };
35
+ }
36
+
37
+ export function buildFunctionsStartArgs(functionsPort: string): string[] {
38
+ return ['start', '--port', functionsPort];
39
+ }
40
+
41
+ export function buildNextDevArgs(pm: string, port: string): string[] {
42
+ const baseArgs = ['next', 'dev', '--port', port, '--webpack'];
43
+ return pm === 'pnpm' ? ['exec', ...baseArgs] : baseArgs;
44
+ }
45
+
46
+ export function getPythonVirtualEnvPaths(functionsDir: string): {
47
+ venvDir: string;
48
+ binDir: string;
49
+ pythonExecutable: string;
50
+ } {
51
+ const venvDir = path.join(functionsDir, '.venv');
52
+ const binDir = process.platform === 'win32'
53
+ ? path.join(venvDir, 'Scripts')
54
+ : path.join(venvDir, 'bin');
55
+ const pythonExecutable = process.platform === 'win32'
56
+ ? path.join(binDir, 'python.exe')
57
+ : path.join(binDir, 'python');
58
+
59
+ return { venvDir, binDir, pythonExecutable };
60
+ }
61
+
62
+ export function buildPythonFunctionsEnv(baseEnv: NodeJS.ProcessEnv, functionsDir: string): NodeJS.ProcessEnv {
63
+ const { venvDir, binDir, pythonExecutable } = getPythonVirtualEnvPaths(functionsDir);
64
+ const pathKey = getPathEnvKey(baseEnv);
65
+ const currentPath = baseEnv[pathKey] || '';
66
+
67
+ return {
68
+ ...baseEnv,
69
+ [pathKey]: currentPath ? `${binDir}${path.delimiter}${currentPath}` : binDir,
70
+ VIRTUAL_ENV: venvDir,
71
+ languageWorkers__python__defaultExecutablePath: pythonExecutable,
72
+ };
73
+ }
74
+
75
+ function getPathEnvKey(env: NodeJS.ProcessEnv): string {
76
+ return Object.keys(env).find((key) => key.toUpperCase() === 'PATH') || 'PATH';
77
+ }
78
+
79
+ function prependToPathEnv(env: NodeJS.ProcessEnv, entry: string): NodeJS.ProcessEnv {
80
+ const pathKey = getPathEnvKey(env);
81
+ const currentPath = env[pathKey] || '';
82
+
83
+ return {
84
+ ...env,
85
+ [pathKey]: currentPath ? `${entry}${path.delimiter}${currentPath}` : entry,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Check if Azure Functions Core Tools is installed
91
+ */
92
+ async function checkCoreTools(): Promise<boolean> {
93
+ return checkCommand('func', ['--version']);
94
+ }
95
+
96
+ async function checkCommand(command: string, args: string[] = ['--version']): Promise<boolean> {
97
+ return new Promise((resolve) => {
98
+ const checkProcess = spawn(command, args, {
99
+ shell: true,
100
+ stdio: 'pipe',
101
+ });
102
+
103
+ checkProcess.on('close', (code) => {
104
+ resolve(code === 0);
105
+ });
106
+
107
+ checkProcess.on('error', () => {
108
+ resolve(false);
109
+ });
110
+ });
111
+ }
112
+
113
+ async function resolvePythonBootstrapCommand(): Promise<{ command: string; argsPrefix: string[]; label: string }> {
114
+ const candidates = process.platform === 'win32'
115
+ ? [
116
+ { command: 'py', argsPrefix: ['-3.11'], label: 'py -3.11' },
117
+ { command: 'python', argsPrefix: [], label: 'python' },
118
+ ]
119
+ : [
120
+ { command: 'python3', argsPrefix: [], label: 'python3' },
121
+ { command: 'python', argsPrefix: [], label: 'python' },
122
+ ];
123
+
124
+ for (const candidate of candidates) {
125
+ if (await checkCommand(candidate.command, [...candidate.argsPrefix, '--version'])) {
126
+ return candidate;
127
+ }
128
+ }
129
+
130
+ throw new Error(
131
+ 'Python 3.11 was not found. Install Python 3.11 and make sure `python`, `python3`, or `py -3.11` is available.'
132
+ );
133
+ }
134
+
135
+ async function getCommandPath(command: string): Promise<string | null> {
136
+ const locator = process.platform === 'win32' ? 'where' : 'which';
137
+ const result = await captureCommandOutput(locator, [command]);
138
+ const firstLine = result
139
+ .split(/\r?\n/)
140
+ .map((line) => line.trim())
141
+ .find(Boolean);
142
+
143
+ return firstLine || null;
144
+ }
145
+
146
+ async function captureCommandOutput(
147
+ command: string,
148
+ args: string[],
149
+ cwd?: string,
150
+ env?: NodeJS.ProcessEnv
151
+ ): Promise<string> {
152
+ return new Promise((resolve, reject) => {
153
+ const child = spawn(command, args, {
154
+ cwd,
155
+ env,
156
+ shell: false,
157
+ stdio: ['ignore', 'pipe', 'pipe'],
158
+ });
159
+
160
+ let stdout = '';
161
+ let stderr = '';
162
+
163
+ child.stdout?.on('data', (data) => {
164
+ stdout += data.toString();
165
+ });
166
+
167
+ child.stderr?.on('data', (data) => {
168
+ stderr += data.toString();
169
+ });
170
+
171
+ child.on('close', (code) => {
172
+ if (code === 0) {
173
+ resolve(stdout);
174
+ } else {
175
+ reject(new Error(stderr || stdout || `${command} exited with code ${code}`));
176
+ }
177
+ });
178
+
179
+ child.on('error', reject);
180
+ });
181
+ }
182
+
183
+ async function resolvePythonRuntimeDetails(
184
+ functionsDir: string,
185
+ env: NodeJS.ProcessEnv
186
+ ): Promise<{ version: string; architecture: string }> {
187
+ const { pythonExecutable } = getPythonVirtualEnvPaths(functionsDir);
188
+ const output = await captureCommandOutput(
189
+ pythonExecutable,
190
+ [
191
+ '-c',
192
+ 'import platform; import sys; print(str(sys.version_info.major) + "." + str(sys.version_info.minor)); print(platform.machine())',
193
+ ],
194
+ functionsDir,
195
+ env
196
+ );
197
+ const [version, architecture] = output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
198
+
199
+ if (!version || !architecture) {
200
+ throw new Error('Failed to determine Python runtime details.');
201
+ }
202
+
203
+ return { version, architecture };
204
+ }
205
+
206
+ async function bridgePythonCoreToolsForWindowsArm64(
207
+ functionsDir: string,
208
+ env: NodeJS.ProcessEnv
209
+ ): Promise<NodeJS.ProcessEnv> {
210
+ if (process.platform !== 'win32' || process.arch !== 'arm64') {
211
+ return env;
212
+ }
213
+
214
+ const funcPath = await getCommandPath('func');
215
+ if (!funcPath) {
216
+ return env;
217
+ }
218
+
219
+ const { version, architecture } = await resolvePythonRuntimeDetails(functionsDir, env);
220
+ if (architecture.toUpperCase() !== 'AMD64') {
221
+ return env;
222
+ }
223
+
224
+ const coreToolsRoot = path.dirname(funcPath);
225
+ const armWorkerDir = path.join(coreToolsRoot, 'workers', 'python', version, 'WINDOWS', 'Arm64');
226
+ if (fs.existsSync(armWorkerDir)) {
227
+ return env;
228
+ }
229
+
230
+ const x64WorkerDir = path.join(coreToolsRoot, 'workers', 'python', version, 'WINDOWS', 'X64');
231
+ if (!fs.existsSync(x64WorkerDir)) {
232
+ return env;
233
+ }
234
+
235
+ const patchedRoot = path.join(
236
+ process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'),
237
+ 'SwallowKit',
238
+ 'azure-functions-core-tools-python-bridge'
239
+ );
240
+
241
+ if (!fs.existsSync(path.join(patchedRoot, 'func.exe'))) {
242
+ console.log('🩹 Creating a local Azure Functions Core Tools bridge for Windows Arm64 Python...');
243
+ fs.mkdirSync(path.dirname(patchedRoot), { recursive: true });
244
+ fs.cpSync(coreToolsRoot, patchedRoot, { recursive: true });
245
+ }
246
+
247
+ const patchedArmWorkerDir = path.join(patchedRoot, 'workers', 'python', version, 'WINDOWS', 'Arm64');
248
+ const patchedX64WorkerDir = path.join(patchedRoot, 'workers', 'python', version, 'WINDOWS', 'X64');
249
+ if (!fs.existsSync(patchedArmWorkerDir) && fs.existsSync(patchedX64WorkerDir)) {
250
+ fs.cpSync(patchedX64WorkerDir, patchedArmWorkerDir, { recursive: true });
251
+ }
252
+
253
+ console.log(`🩹 Using bridged Azure Functions Core Tools from ${patchedRoot}`);
254
+ return prependToPathEnv(env, patchedRoot);
255
+ }
256
+
257
+ async function preparePythonFunctionsEnvironment(functionsDir: string): Promise<NodeJS.ProcessEnv> {
258
+ const { pythonExecutable } = getPythonVirtualEnvPaths(functionsDir);
259
+ const hasUv = await checkCommand('uv', ['--version']);
260
+
261
+ if (!fs.existsSync(pythonExecutable)) {
262
+ if (hasUv) {
263
+ console.log('📦 Creating Python virtual environment with uv...');
264
+ await runCommand('uv', ['venv', '.venv', '--python', '3.11'], functionsDir, 'python virtual environment setup');
265
+ } else {
266
+ const bootstrap = await resolvePythonBootstrapCommand();
267
+ console.log(`📦 Creating Python virtual environment with ${bootstrap.label}...`);
268
+ await runCommand(
269
+ bootstrap.command,
270
+ [...bootstrap.argsPrefix, '-m', 'venv', '.venv'],
271
+ functionsDir,
272
+ 'python virtual environment setup'
273
+ );
274
+ }
275
+ }
276
+
277
+ const pythonEnv = buildPythonFunctionsEnv(process.env, functionsDir);
278
+ console.log(`📦 Installing Python Azure Functions dependencies${hasUv ? ' with uv' : ''}...`);
279
+
280
+ if (hasUv) {
281
+ await runCommand(
282
+ 'uv',
283
+ ['pip', 'install', '--python', pythonExecutable, '-r', 'requirements.txt'],
284
+ functionsDir,
285
+ 'python dependency installation',
286
+ pythonEnv
287
+ );
288
+ } else {
289
+ await runCommand('python', ['-m', 'pip', 'install', '--upgrade', 'pip'], functionsDir, 'python pip upgrade', pythonEnv);
290
+ await runCommand(
291
+ 'python',
292
+ ['-m', 'pip', 'install', '-r', 'requirements.txt'],
293
+ functionsDir,
294
+ 'python dependency installation',
295
+ pythonEnv
296
+ );
297
+ }
298
+
299
+ return bridgePythonCoreToolsForWindowsArm64(functionsDir, pythonEnv);
300
+ }
301
+
302
+ /**
303
+ * Check if Cosmos DB Emulator is running by checking if port 8081 is open
304
+ */
305
+ async function checkCosmosDBEmulator(): Promise<boolean> {
306
+ return new Promise((resolve) => {
307
+ const socket = new net.Socket();
308
+
309
+ const timeout = setTimeout(() => {
310
+ socket.destroy();
311
+ resolve(false);
312
+ }, 2000);
313
+
314
+ socket.on('connect', () => {
315
+ clearTimeout(timeout);
316
+ socket.destroy();
317
+ resolve(true);
318
+ });
319
+
320
+ socket.on('error', () => {
321
+ clearTimeout(timeout);
322
+ resolve(false);
323
+ });
324
+
325
+ socket.connect(8081, 'localhost');
326
+ });
327
+ }
328
+
329
+ export function buildDevCommand(
330
+ runDevEnvironment: (options: DevOptions) => Promise<void> = startDevEnvironment,
331
+ verifyProject: (commandName: string, projectRoot?: string) => void = ensureSwallowKitProject
332
+ ): Command {
333
+ return new Command()
334
+ .name('dev')
335
+ .description('Start SwallowKit development server (Cosmos DB + Next.js + Azure Functions)')
336
+ .option('-p, --port <port>', 'Next.js port', '3000')
337
+ .option('-f, --functions-port <port>', 'Azure Functions port', '7071')
338
+ .option('--host <host>', 'Host name', 'localhost')
339
+ .option('--open', 'Open browser automatically', false)
340
+ .option('--verbose', 'Show verbose logs', false)
341
+ .option('--no-functions', 'Skip Azure Functions startup', false)
342
+ .option('--seed-env <environment>', 'Replace Cosmos DB Emulator data from dev-seeds/<environment> before startup')
343
+ .option('--mock-connectors', 'Start mock server for connector models (serves Zod-generated data)', false)
344
+ .action(async (options: ParsedDevActionOptions) => {
345
+ const normalizedOptions = normalizeParsedDevOptions(options);
346
+
347
+ // SwallowKit プロジェクトディレクトリかどうかを検証
348
+ verifyProject("dev");
349
+
350
+ console.log('🚀 Starting SwallowKit development environment...');
351
+ if (normalizedOptions.verbose) {
352
+ console.log('⚙️ Options:', normalizedOptions);
353
+ }
354
+
355
+ await runDevEnvironment(normalizedOptions);
356
+ });
357
+ }
358
+
359
+ export const devCommand = buildDevCommand();
360
+
361
+ interface CosmosInitializationResult {
362
+ endpoint: string;
363
+ key: string;
364
+ databaseName: string;
365
+ models: ModelInfo[];
366
+ }
367
+
368
+ async function initializeCosmosDB(databaseName: string): Promise<CosmosInitializationResult | null> {
369
+ try {
370
+ // Read local.settings.json from functions directory
371
+ const functionsDir = path.join(process.cwd(), 'functions');
372
+ const localSettingsPath = path.join(functionsDir, 'local.settings.json');
373
+
374
+ if (!fs.existsSync(localSettingsPath)) {
375
+ console.log('⚠️ local.settings.json not found. Skipping Cosmos DB initialization.');
376
+ return null;
377
+ }
378
+
379
+ const localSettings = JSON.parse(fs.readFileSync(localSettingsPath, 'utf-8'));
380
+ const connectionString = localSettings.Values?.CosmosDBConnection;
381
+ const dbName = localSettings.Values?.COSMOS_DB_DATABASE_NAME || databaseName;
382
+
383
+ if (!connectionString) {
384
+ console.log('⚠️ CosmosDBConnection not found in local.settings.json. Skipping Cosmos DB initialization.');
385
+ return null;
386
+ }
387
+
388
+ console.log('🗄️ Initializing Cosmos DB...');
389
+
390
+ // Parse connection string
391
+ const endpointMatch = connectionString.match(/AccountEndpoint=([^;]+)/);
392
+ const keyMatch = connectionString.match(/AccountKey=([^;]+)/);
393
+
394
+ if (!endpointMatch || !keyMatch) {
395
+ console.log('⚠️ Invalid CosmosDB connection string format.');
396
+ return null;
397
+ }
398
+
399
+ const endpoint = endpointMatch[1];
400
+
401
+ const client = new CosmosClient({
402
+ endpoint: endpoint,
403
+ key: keyMatch[1]
404
+ });
405
+
406
+ // Create database if not exists
407
+ const { database } = await client.databases.createIfNotExists({ id: dbName });
408
+ console.log(`✅ Database "${dbName}" ready`);
409
+
410
+ const models = await loadProjectModels();
411
+ for (const model of models) {
412
+ const containerName = getContainerNameForModel(model);
413
+
414
+ // Try creating container with full partition key definition first
415
+ let containerCreated = false;
416
+
417
+ try {
418
+ console.log(`🔧 Creating container "${containerName}" with partition key ${model.partitionKey}...`);
419
+ const containerResponse = await database.containers.createIfNotExists({
420
+ id: containerName,
421
+ partitionKey: {
422
+ paths: [model.partitionKey],
423
+ kind: PartitionKeyKind.Hash,
424
+ version: 2
425
+ }
426
+ });
427
+ console.log(`✅ Container "${containerName}" ready (status: ${containerResponse.statusCode})`);
428
+ containerCreated = true;
429
+ } catch (error: unknown) {
430
+ const message = error instanceof Error ? error.message : String(error);
431
+ console.log(`⚠️ Failed with full partition key definition: ${message}`);
432
+ console.log(`🔄 Retrying with simple partition key...`);
433
+ }
434
+
435
+ // If first attempt failed, try with simple partition key definition
436
+ if (!containerCreated) {
437
+ try {
438
+ const containerResponse = await database.containers.createIfNotExists({
439
+ id: containerName,
440
+ partitionKey: {
441
+ paths: [model.partitionKey]
442
+ }
443
+ });
444
+ console.log(`✅ Container "${containerName}" ready (status: ${containerResponse.statusCode})`);
445
+ } catch (containerError: any) {
446
+ console.error(`❌ Failed to create container "${containerName}":`, containerError.message);
447
+ console.error(`Error code: ${containerError.code}`);
448
+ if (containerError.body) {
449
+ console.error(`Response body:`, JSON.stringify(containerError.body, null, 2));
450
+ }
451
+ // Continue with other containers
452
+ }
453
+ }
454
+ }
455
+
456
+ console.log('✅ Cosmos DB initialization complete\n');
457
+ return { endpoint, key: keyMatch[1], databaseName: dbName, models };
458
+ } catch (error: any) {
459
+ console.error('⚠️ Cosmos DB initialization failed:', error.message);
460
+ if (error.stack) {
461
+ console.error('Stack trace:', error.stack);
462
+ }
463
+ console.log('💡 Make sure Cosmos DB Emulator is running');
464
+ return null;
465
+ }
466
+ }
467
+
468
+ async function startDevEnvironment(options: DevOptions) {
469
+ const port = options.port || '3000';
470
+ const functionsPort = options.functionsPort || '7071';
471
+
472
+ // Detect package manager from project lockfile
473
+ const pm = detectFromProject();
474
+ const pmCmd = getCommands(pm);
475
+ const backendLanguage = getBackendLanguage();
476
+
477
+ // プロセスを管理する配列
478
+ const processes: ChildProcess[] = [];
479
+ let functionsEnv: NodeJS.ProcessEnv = process.env;
480
+ let mockServer: ConnectorMockServer | null = null;
481
+ let envLocalPath = '';
482
+ let envLocalDefaultUrl = ''; // default Functions URL to restore on shutdown
483
+
484
+ // Cleanup processes on Ctrl+C
485
+ process.on('SIGINT', async () => {
486
+ console.log('\n🛑 Stopping development servers...');
487
+ // Restore .env.local to default Functions port on shutdown
488
+ if (envLocalPath && envLocalDefaultUrl) {
489
+ try {
490
+ if (fs.existsSync(envLocalPath)) {
491
+ const content = fs.readFileSync(envLocalPath, 'utf-8');
492
+ if (content.includes('BACKEND_FUNCTIONS_BASE_URL=') &&
493
+ !content.includes(`BACKEND_FUNCTIONS_BASE_URL=${envLocalDefaultUrl}`)) {
494
+ const restored = content.replace(
495
+ /^BACKEND_FUNCTIONS_BASE_URL=.*/m,
496
+ `BACKEND_FUNCTIONS_BASE_URL=${envLocalDefaultUrl}`
497
+ );
498
+ fs.writeFileSync(envLocalPath, restored, 'utf-8');
499
+ }
500
+ }
501
+ } catch { /* ignore */ }
502
+ }
503
+ if (mockServer) {
504
+ await mockServer.stop();
505
+ }
506
+ processes.forEach((proc) => {
507
+ if (proc && !proc.killed) {
508
+ proc.kill();
509
+ }
510
+ });
511
+ process.exit(0);
512
+ });
513
+
514
+ try {
515
+ // 1. Check for Next.js project
516
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
517
+ const nextConfigPathJs = path.join(process.cwd(), 'next.config.js');
518
+ const nextConfigPathTs = path.join(process.cwd(), 'next.config.ts');
519
+ const nextConfigPathMjs = path.join(process.cwd(), 'next.config.mjs');
520
+
521
+ if (!fs.existsSync(packageJsonPath)) {
522
+ console.log('❌ package.json not found.');
523
+ console.log('💡 Please run this command in the root directory of a Next.js project.');
524
+ process.exit(1);
525
+ }
526
+
527
+ if (!fs.existsSync(nextConfigPathJs) && !fs.existsSync(nextConfigPathTs) && !fs.existsSync(nextConfigPathMjs)) {
528
+ console.log('⚠️ next.config file not found. Is this a Next.js project?');
529
+ }
530
+
531
+ // 2. Check if Azure Functions exists
532
+ const functionsDir = path.join(process.cwd(), 'functions');
533
+ const hasFunctions = fs.existsSync(functionsDir) && hasFunctionsProject(functionsDir, backendLanguage);
534
+
535
+ if (hasFunctions && !options.noFunctions) {
536
+ // Check if Azure Functions Core Tools is installed
537
+ const coreToolsInstalled = await checkCoreTools();
538
+
539
+ if (!coreToolsInstalled) {
540
+ console.log('');
541
+ console.log('⚠️ Azure Functions Core Tools not found.');
542
+ console.log('');
543
+
544
+ // Prompt user for installation
545
+ const readline = await import('readline');
546
+ const rl = readline.createInterface({
547
+ input: process.stdin,
548
+ output: process.stdout
549
+ });
550
+
551
+ const answer = await new Promise<string>((resolve) => {
552
+ rl.question('Would you like to install Azure Functions Core Tools? (y/n): ', resolve);
553
+ });
554
+ rl.close();
555
+
556
+ if (answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes') {
557
+ console.log('📦 Installing Azure Functions Core Tools...');
558
+ console.log(' This may take a few minutes.');
559
+
560
+ const installProcess = spawn(pm, pm === 'pnpm' ? ['add', '-g', 'azure-functions-core-tools@4'] : ['install', '-g', 'azure-functions-core-tools@4'], {
561
+ shell: true,
562
+ stdio: 'inherit',
563
+ });
564
+
565
+ await new Promise<void>((resolve, reject) => {
566
+ installProcess.on('close', (code) => {
567
+ if (code === 0) {
568
+ console.log('✅ Azure Functions Core Tools installed successfully.');
569
+ resolve();
570
+ } else {
571
+ console.error('❌ Installation failed.');
572
+ console.log('💡 Please install manually:');
573
+ console.log(` ${pmCmd.addGlobal} azure-functions-core-tools@4`);
574
+ reject(new Error(`Installation failed with code ${code}`));
575
+ }
576
+ });
577
+ installProcess.on('error', reject);
578
+ });
579
+ } else {
580
+ console.log('');
581
+ console.log('ℹ️ Skipping Azure Functions startup.');
582
+ console.log('💡 To install later:');
583
+ console.log(` ${pmCmd.addGlobal} azure-functions-core-tools@4`);
584
+ console.log('');
585
+ // Skip Azure Functions startup
586
+ options.noFunctions = true;
587
+ }
588
+ }
589
+
590
+ if (!options.noFunctions) {
591
+ // Check if Cosmos DB Emulator is running
592
+ const cosmosRunning = await checkCosmosDBEmulator();
593
+
594
+ if (!cosmosRunning) {
595
+ console.log('');
596
+ console.log('❌ Cosmos DB Emulator is not running.');
597
+ console.log('');
598
+ console.log('💡 Please start Cosmos DB Emulator manually:');
599
+ console.log(' C:\\Program Files\\Azure Cosmos DB Emulator\\CosmosDB.Emulator.exe');
600
+ console.log('');
601
+ console.log(' Or search for "Azure Cosmos DB Emulator" in the Start menu.');
602
+ console.log('');
603
+ process.exit(1);
604
+ }
605
+
606
+ // Initialize Cosmos DB before starting Functions
607
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
608
+ const appName = packageJson.name || 'App';
609
+ const databaseName = `${appName.charAt(0).toUpperCase() + appName.slice(1)}Database`;
610
+
611
+ const cosmosInitialization = await initializeCosmosDB(databaseName);
612
+ if (options.seedEnv && cosmosInitialization) {
613
+ await applyDevSeedEnvironment({
614
+ client: new CosmosClient({
615
+ endpoint: cosmosInitialization.endpoint,
616
+ key: cosmosInitialization.key,
617
+ }),
618
+ databaseName: cosmosInitialization.databaseName,
619
+ environment: options.seedEnv,
620
+ models: cosmosInitialization.models,
621
+ });
622
+ }
623
+
624
+ console.log('');
625
+ console.log('🚀 Starting Azure Functions...');
626
+
627
+ if (backendLanguage === 'typescript') {
628
+ const functionsNodeModules = path.join(functionsDir, 'node_modules');
629
+ if (!fs.existsSync(functionsNodeModules)) {
630
+ console.log('📦 Installing Azure Functions dependencies...');
631
+ await runCommand(pm, ['install'], functionsDir, `${pm} install`);
632
+ }
633
+ } else if (backendLanguage === 'csharp') {
634
+ console.log('📦 Building C# Azure Functions project...');
635
+ await runCommand('dotnet', ['build'], functionsDir, 'dotnet build');
636
+ } else {
637
+ functionsEnv = await preparePythonFunctionsEnvironment(functionsDir);
638
+ }
639
+ }
640
+ }
641
+
642
+ if (hasFunctions && !options.noFunctions) {
643
+ // Build shared package before starting Functions
644
+ const sharedDir = path.join(process.cwd(), 'shared');
645
+ const sharedPkgPath = path.join(sharedDir, 'package.json');
646
+ if (fs.existsSync(sharedDir) && fs.existsSync(sharedPkgPath)) {
647
+ const sharedPkg = JSON.parse(fs.readFileSync(sharedPkgPath, 'utf-8'));
648
+ if (sharedPkg.scripts?.build) {
649
+ console.log('📦 Building shared package...');
650
+ const filterArgs = pm === 'pnpm'
651
+ ? ['run', '--filter', 'shared', 'build']
652
+ : ['run', '--workspace=shared', 'build'];
653
+ const sharedBuild = spawn(pm, filterArgs, {
654
+ cwd: process.cwd(),
655
+ shell: true,
656
+ stdio: 'inherit',
657
+ });
658
+
659
+ await new Promise<void>((resolve, reject) => {
660
+ sharedBuild.on('close', (code) => {
661
+ if (code === 0) {
662
+ console.log('✅ Shared package built successfully');
663
+ resolve();
664
+ } else {
665
+ reject(new Error(`Shared package build failed with code ${code}`));
666
+ }
667
+ });
668
+ sharedBuild.on('error', reject);
669
+ });
670
+ } else {
671
+ console.log('⚠️ Shared package has no build script — skipping build. Run "swallowkit add-auth" to fix.');
672
+ }
673
+ }
674
+
675
+ // Build TypeScript functions after shared package (functions import from shared)
676
+ if (backendLanguage === 'typescript') {
677
+ const functionsPkgPath = path.join(functionsDir, 'package.json');
678
+ if (fs.existsSync(functionsPkgPath)) {
679
+ const functionsPkg = JSON.parse(fs.readFileSync(functionsPkgPath, 'utf-8'));
680
+ if (functionsPkg.scripts?.build) {
681
+ console.log('📦 Building TypeScript Azure Functions...');
682
+ await runCommand(pm, ['run', 'build'], functionsDir, `${pm} run build`);
683
+ }
684
+ }
685
+ }
686
+
687
+ // Azure Functions を起動
688
+ const funcProcess = spawn('func', buildFunctionsStartArgs(functionsPort), {
689
+ cwd: functionsDir,
690
+ shell: true,
691
+ stdio: 'pipe', // Always pipe to capture output
692
+ env: functionsEnv
693
+ });
694
+ let pythonWorkerMissing = false;
695
+
696
+ // Functions の出力をそのまま表示(プレフィックス付き)
697
+ if (funcProcess.stdout) {
698
+ funcProcess.stdout.on('data', (data) => {
699
+ const output = data.toString();
700
+ // 各行にプレフィックスを付けて出力
701
+ const lines = output.split('\n').filter((line: string) => line.trim());
702
+ lines.forEach((line: string) => {
703
+ if (
704
+ backendLanguage === 'python' &&
705
+ (line.includes('WorkerConfig for runtime: python not found') || line.includes('DefaultWorkerPath:'))
706
+ ) {
707
+ pythonWorkerMissing = true;
708
+ }
709
+ console.log(`[Functions] ${line}`);
710
+ });
711
+ });
712
+ }
713
+
714
+ if (funcProcess.stderr) {
715
+ funcProcess.stderr.on('data', (data) => {
716
+ const output = data.toString();
717
+ const lines = output.split('\n').filter((line: string) => line.trim());
718
+ lines.forEach((line: string) => {
719
+ if (
720
+ backendLanguage === 'python' &&
721
+ (line.includes('WorkerConfig for runtime: python not found') || line.includes('DefaultWorkerPath:'))
722
+ ) {
723
+ pythonWorkerMissing = true;
724
+ }
725
+ console.error(`[Functions Error] ${line}`);
726
+ });
727
+ });
728
+ }
729
+
730
+ processes.push(funcProcess);
731
+
732
+ funcProcess.on('error', (error) => {
733
+ console.error('⚠️ Azure Functions startup error:', error.message);
734
+ console.log('💡 Please ensure Azure Functions Core Tools is installed');
735
+ console.log(` ${pmCmd.addGlobal} azure-functions-core-tools@4`);
736
+ });
737
+
738
+ funcProcess.on('close', (code) => {
739
+ if (code !== 0) {
740
+ console.log(`\n⏹️ Azure Functions exited (exit code: ${code})`);
741
+ if (backendLanguage === 'python' && pythonWorkerMissing) {
742
+ console.log('💡 Your Azure Functions Core Tools installation is missing the Python worker for this OS/architecture.');
743
+ console.log(' Reinstall a matching Core Tools v4 package (Windows users should prefer the official x64/x86 MSI for their machine).');
744
+ console.log(' SwallowKit local Python dev uses functions/.venv and requirements.txt, but Core Tools still needs its own bundled Python worker.');
745
+ }
746
+ }
747
+ });
748
+
749
+ console.log(`✅ Azure Functions started (port: ${functionsPort})`);
750
+ } else if (!hasFunctions) {
751
+ console.log('');
752
+ console.log('ℹ️ functions/ directory not found. Starting Next.js only.');
753
+ } else if (options.noFunctions) {
754
+ console.log('');
755
+ console.log('ℹ️ --no-functions specified. Skipping Azure Functions.');
756
+ }
757
+
758
+ console.log('');
759
+ console.log('🚀 Starting Next.js development server...');
760
+
761
+ // Mock connector server — start proxy if --mock-connectors is enabled
762
+ let bffTargetPort = functionsPort;
763
+
764
+ if (options.mockConnectors) {
765
+ const allModels = await loadProjectModels();
766
+ const connectorModels = allModels.filter((m) => m.connectorConfig);
767
+
768
+ // Resolve auth config — auth functions use RDB connectors, mocked alongside other models
769
+ const authConfig = getAuthConfig();
770
+ let mockAuthConfig: { jwtSecret: string; tokenExpiry?: string; customJwt?: { userTable: string; loginIdColumn: string; passwordHashColumn: string; rolesColumn: string }; defaultPolicy?: "authenticated" | "anonymous" } | undefined;
771
+ if (authConfig?.provider === 'custom-jwt' && authConfig.customJwt) {
772
+ // Read JWT_SECRET from functions/local.settings.json if available
773
+ let jwtSecret = 'dev-jwt-secret-change-in-production-min-32-chars!!';
774
+ try {
775
+ const localSettingsPath = path.join(process.cwd(), 'functions', 'local.settings.json');
776
+ if (fs.existsSync(localSettingsPath)) {
777
+ const localSettings = JSON.parse(fs.readFileSync(localSettingsPath, 'utf-8'));
778
+ jwtSecret = localSettings.Values?.[authConfig.customJwt.jwtSecretEnv || 'JWT_SECRET'] || jwtSecret;
779
+ }
780
+ } catch { /* ignore */ }
781
+ mockAuthConfig = {
782
+ jwtSecret,
783
+ tokenExpiry: authConfig.customJwt.tokenExpiry,
784
+ customJwt: {
785
+ userTable: authConfig.customJwt.userTable,
786
+ loginIdColumn: authConfig.customJwt.loginIdColumn,
787
+ passwordHashColumn: authConfig.customJwt.passwordHashColumn,
788
+ rolesColumn: authConfig.customJwt.rolesColumn,
789
+ },
790
+ defaultPolicy: authConfig.authorization?.defaultPolicy,
791
+ };
792
+ }
793
+
794
+ if (connectorModels.length > 0 || mockAuthConfig) {
795
+ const mockPort = parseInt(functionsPort, 10) + 1;
796
+ mockServer = new ConnectorMockServer({
797
+ port: mockPort,
798
+ functionsTarget: `${options.host || 'localhost'}:${functionsPort}`,
799
+ connectorModels,
800
+ allModels,
801
+ seedEnv: options.seedEnv,
802
+ host: options.host || 'localhost',
803
+ authConfig: mockAuthConfig,
804
+ });
805
+
806
+ await mockServer.start();
807
+ bffTargetPort = String(mockPort);
808
+
809
+ const modelCount = connectorModels.length + (mockAuthConfig ? 1 : 0);
810
+ console.log('');
811
+ console.log(`🔌 Mock server started (port: ${mockPort}) — ${modelCount} model(s) mocked via Zod/seed data`);
812
+ for (const m of connectorModels) {
813
+ const ops = m.connectorConfig!.operations.join(', ');
814
+ console.log(` - ${m.name} [${ops}]`);
815
+ }
816
+ if (mockAuthConfig) {
817
+ console.log(` - auth [login, me, logout]`);
818
+ }
819
+ console.log(` Other routes → proxied to Azure Functions (port: ${functionsPort})`);
820
+ } else {
821
+ console.log('');
822
+ console.log('ℹ️ --mock-connectors specified but no connector models found. Skipping mock server.');
823
+ }
824
+ }
825
+
826
+ // 5. Start Next.js development server
827
+ const nextArgs = buildNextDevArgs(pm, port);
828
+
829
+ if (options.open) {
830
+ // Next.js 14+ deprecated --open option, so we open browser manually
831
+ setTimeout(() => {
832
+ const url = `http://${options.host || 'localhost'}:${port}`;
833
+ console.log(`\n🌐 Opening browser: ${url}`);
834
+
835
+ const start = process.platform === 'darwin' ? 'open' :
836
+ process.platform === 'win32' ? 'start' : 'xdg-open';
837
+ spawn(start, [url], { shell: true });
838
+ }, 3000);
839
+ }
840
+
841
+ // Ensure .env.local points to bffTargetPort so Next.js reads the correct backend URL.
842
+ // When --mock-connectors is active, bffTargetPort = mock port (7072); otherwise = Functions port (7071).
843
+ // Next.js may load .env.local values that override spawn env vars, so we must keep them in sync.
844
+ envLocalPath = path.join(process.cwd(), '.env.local');
845
+ envLocalDefaultUrl = `http://${options.host || 'localhost'}:${functionsPort}`;
846
+ const bffTargetUrl = `http://${options.host || 'localhost'}:${bffTargetPort}`;
847
+ try {
848
+ if (fs.existsSync(envLocalPath)) {
849
+ const envContent = fs.readFileSync(envLocalPath, 'utf-8');
850
+ if (envContent.includes('BACKEND_FUNCTIONS_BASE_URL=') &&
851
+ !envContent.includes(`BACKEND_FUNCTIONS_BASE_URL=${bffTargetUrl}`)) {
852
+ const updated = envContent.replace(
853
+ /^BACKEND_FUNCTIONS_BASE_URL=.*/m,
854
+ `BACKEND_FUNCTIONS_BASE_URL=${bffTargetUrl}`
855
+ );
856
+ fs.writeFileSync(envLocalPath, updated, 'utf-8');
857
+ }
858
+ }
859
+ } catch { /* ignore */ }
860
+
861
+ const nextEnv: NodeJS.ProcessEnv = {
862
+ ...process.env,
863
+ BACKEND_FUNCTIONS_BASE_URL: `http://${options.host || 'localhost'}:${bffTargetPort}`,
864
+ FUNCTIONS_BASE_URL: `http://${options.host || 'localhost'}:${bffTargetPort}`,
865
+ };
866
+
867
+ const nextProcess = spawn(pm === 'pnpm' ? 'pnpm' : 'npx', nextArgs, {
868
+ cwd: process.cwd(),
869
+ shell: true,
870
+ stdio: options.verbose ? 'inherit' : 'inherit',
871
+ env: nextEnv,
872
+ });
873
+
874
+ processes.push(nextProcess);
875
+
876
+ nextProcess.on('error', (error) => {
877
+ console.error('❌ Next.js startup error:', error.message);
878
+ process.exit(1);
879
+ });
880
+
881
+ nextProcess.on('close', (code) => {
882
+ if (code !== 0) {
883
+ console.log(`\n⏹️ Next.js exited (exit code: ${code})`);
884
+ }
885
+ // Exit all processes when Next.js exits
886
+ if (mockServer) {
887
+ mockServer.stop().catch(() => {});
888
+ }
889
+ processes.forEach((proc) => {
890
+ if (proc && !proc.killed) {
891
+ proc.kill();
892
+ }
893
+ });
894
+ process.exit(code || 0);
895
+ });
896
+
897
+ console.log('');
898
+ console.log('✅ SwallowKit development environment is running!');
899
+ console.log('');
900
+ console.log(`📱 Next.js: http://${options.host || 'localhost'}:${port}`);
901
+ if (hasFunctions && !options.noFunctions) {
902
+ console.log(`⚡ Azure Functions: http://${options.host || 'localhost'}:${functionsPort}`);
903
+ }
904
+ if (mockServer) {
905
+ console.log(`🔌 Mock Proxy: http://${options.host || 'localhost'}:${bffTargetPort} (BFF → here)`);
906
+ }
907
+ console.log('');
908
+ if (hasFunctions && !options.noFunctions) {
909
+ console.log('💡 Azure Functions and Next.js BFF are connected');
910
+ }
911
+ if (mockServer) {
912
+ console.log('💡 Connector models served from mock server (Zod-generated data)');
913
+ }
914
+ console.log('');
915
+ console.log('🛑 Press Ctrl+C to stop');
916
+ console.log('');
917
+
918
+ } catch (error) {
919
+ console.error('❌ Failed to start development environment:', error instanceof Error ? error.message : error);
920
+ processes.forEach((proc) => {
921
+ if (proc && !proc.killed) {
922
+ proc.kill();
923
+ }
924
+ });
925
+ process.exit(1);
926
+ }
927
+ }
928
+
929
+ async function runCommand(
930
+ command: string,
931
+ args: string[],
932
+ cwd: string,
933
+ label: string,
934
+ env?: NodeJS.ProcessEnv
935
+ ): Promise<void> {
936
+ await new Promise<void>((resolve, reject) => {
937
+ const child = spawn(command, args, {
938
+ cwd,
939
+ shell: true,
940
+ stdio: 'inherit',
941
+ env,
942
+ });
943
+
944
+ child.on('close', (code) => {
945
+ if (code === 0) {
946
+ resolve();
947
+ } else {
948
+ reject(new Error(`${label} failed with code ${code}`));
949
+ }
950
+ });
951
+
952
+ child.on('error', reject);
953
+ });
954
+ }
955
+
956
+ function hasFunctionsProject(functionsDir: string, backendLanguage: BackendLanguage): boolean {
957
+ if (backendLanguage === 'typescript') {
958
+ return fs.existsSync(path.join(functionsDir, 'package.json'));
959
+ }
960
+
961
+ return fs.existsSync(path.join(functionsDir, 'host.json'));
962
+ }