swallowkit 1.0.0-beta.3 → 1.0.0-beta.31

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