swallowkit 1.0.0-beta.4 → 1.0.0-beta.40

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 (204) hide show
  1. package/LICENSE +21 -21
  2. package/README.ja.md +153 -215
  3. package/README.md +153 -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 +426 -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 +45 -0
  33. package/dist/cli/commands/init.d.ts.map +1 -1
  34. package/dist/cli/commands/init.js +2851 -1754
  35. package/dist/cli/commands/init.js.map +1 -1
  36. package/dist/cli/commands/scaffold.d.ts +4 -0
  37. package/dist/cli/commands/scaffold.d.ts.map +1 -1
  38. package/dist/cli/commands/scaffold.js +439 -130
  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 +200 -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 +94 -5
  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 +209 -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 -220
  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 +328 -135
  91. package/dist/core/scaffold/model-parser.js.map +1 -1
  92. package/dist/core/scaffold/native-schema-generator.d.ts +13 -0
  93. package/dist/core/scaffold/native-schema-generator.d.ts.map +1 -0
  94. package/dist/core/scaffold/native-schema-generator.js +696 -0
  95. package/dist/core/scaffold/native-schema-generator.js.map +1 -0
  96. package/dist/core/scaffold/nextjs-generator.d.ts +8 -0
  97. package/dist/core/scaffold/nextjs-generator.d.ts.map +1 -1
  98. package/dist/core/scaffold/nextjs-generator.js +314 -182
  99. package/dist/core/scaffold/nextjs-generator.js.map +1 -1
  100. package/dist/core/scaffold/openapi-generator.d.ts +3 -0
  101. package/dist/core/scaffold/openapi-generator.d.ts.map +1 -0
  102. package/dist/core/scaffold/openapi-generator.js +190 -0
  103. package/dist/core/scaffold/openapi-generator.js.map +1 -0
  104. package/dist/core/scaffold/ui-generator.d.ts +10 -4
  105. package/dist/core/scaffold/ui-generator.d.ts.map +1 -1
  106. package/dist/core/scaffold/ui-generator.js +768 -663
  107. package/dist/core/scaffold/ui-generator.js.map +1 -1
  108. package/dist/database/base-model.d.ts +3 -3
  109. package/dist/database/base-model.js +3 -3
  110. package/dist/index.d.ts +2 -2
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +2 -1
  113. package/dist/index.js.map +1 -1
  114. package/dist/machine/contracts.d.ts +16 -0
  115. package/dist/machine/contracts.d.ts.map +1 -0
  116. package/dist/machine/contracts.js +3 -0
  117. package/dist/machine/contracts.js.map +1 -0
  118. package/dist/machine/errors.d.ts +11 -0
  119. package/dist/machine/errors.d.ts.map +1 -0
  120. package/dist/machine/errors.js +34 -0
  121. package/dist/machine/errors.js.map +1 -0
  122. package/dist/machine/index.d.ts +3 -0
  123. package/dist/machine/index.d.ts.map +1 -0
  124. package/dist/machine/index.js +156 -0
  125. package/dist/machine/index.js.map +1 -0
  126. package/dist/mcp/index.d.ts +25 -0
  127. package/dist/mcp/index.d.ts.map +1 -0
  128. package/dist/mcp/index.js +186 -0
  129. package/dist/mcp/index.js.map +1 -0
  130. package/dist/types/index.d.ts +65 -0
  131. package/dist/types/index.d.ts.map +1 -1
  132. package/dist/utils/package-manager.d.ts +110 -0
  133. package/dist/utils/package-manager.d.ts.map +1 -0
  134. package/dist/utils/package-manager.js +224 -0
  135. package/dist/utils/package-manager.js.map +1 -0
  136. package/dist/utils/python-uv.d.ts +21 -0
  137. package/dist/utils/python-uv.d.ts.map +1 -0
  138. package/dist/utils/python-uv.js +111 -0
  139. package/dist/utils/python-uv.js.map +1 -0
  140. package/package.json +84 -73
  141. package/src/__tests__/__snapshots__/functions-generator.test.ts.snap +1139 -0
  142. package/src/__tests__/__snapshots__/nextjs-generator.test.ts.snap +194 -0
  143. package/src/__tests__/__snapshots__/ui-generator.test.ts.snap +532 -0
  144. package/src/__tests__/auth.test.ts +654 -0
  145. package/src/__tests__/config.test.ts +274 -0
  146. package/src/__tests__/connector-functions-generator.test.ts +288 -0
  147. package/src/__tests__/connector-mock-server.test.ts +439 -0
  148. package/src/__tests__/connector-model-bff.test.ts +162 -0
  149. package/src/__tests__/dev-seeds.test.ts +173 -0
  150. package/src/__tests__/dev.test.ts +252 -0
  151. package/src/__tests__/fixtures.ts +144 -0
  152. package/src/__tests__/functions-generator.test.ts +237 -0
  153. package/src/__tests__/init.test.ts +197 -0
  154. package/src/__tests__/jest-globals.d.ts +8 -0
  155. package/src/__tests__/machine.test.ts +356 -0
  156. package/src/__tests__/mcp.test.ts +124 -0
  157. package/src/__tests__/model-parser.test.ts +52 -0
  158. package/src/__tests__/nextjs-generator.test.ts +97 -0
  159. package/src/__tests__/openapi-generator.test.ts +43 -0
  160. package/src/__tests__/package-manager.test.ts +201 -0
  161. package/src/__tests__/python-uv.test.ts +48 -0
  162. package/src/__tests__/scaffold.test.ts +191 -0
  163. package/src/__tests__/string-utils.test.ts +75 -0
  164. package/src/__tests__/tsconfig.json +15 -0
  165. package/src/__tests__/ui-generator.test.ts +144 -0
  166. package/src/__tests__/zod-mock-generator.test.ts +132 -0
  167. package/src/cli/commands/add-auth.ts +482 -0
  168. package/src/cli/commands/add-connector.ts +158 -0
  169. package/src/cli/commands/create-model.ts +62 -0
  170. package/src/cli/commands/dev-seeds.ts +614 -0
  171. package/src/cli/commands/dev.ts +1134 -0
  172. package/src/cli/commands/index.ts +9 -0
  173. package/src/cli/commands/init.ts +3600 -0
  174. package/src/cli/commands/provision.ts +193 -0
  175. package/src/cli/commands/scaffold.ts +991 -0
  176. package/src/cli/index.ts +196 -0
  177. package/src/core/config.ts +312 -0
  178. package/src/core/mock/connector-mock-server.ts +555 -0
  179. package/src/core/mock/zod-mock-generator.ts +205 -0
  180. package/src/core/operations/create-model.ts +174 -0
  181. package/src/core/operations/runtime.ts +235 -0
  182. package/src/core/operations/scaffold-machine.ts +91 -0
  183. package/src/core/project/manifest.ts +402 -0
  184. package/src/core/project/validation.ts +229 -0
  185. package/src/core/scaffold/auth-generator.ts +1284 -0
  186. package/src/core/scaffold/connector-functions-generator.ts +1128 -0
  187. package/src/core/scaffold/functions-generator.ts +970 -0
  188. package/src/core/scaffold/model-parser.ts +841 -0
  189. package/src/core/scaffold/native-schema-generator.ts +822 -0
  190. package/src/core/scaffold/nextjs-generator.ts +370 -0
  191. package/src/core/scaffold/openapi-generator.ts +212 -0
  192. package/src/core/scaffold/ui-generator.ts +1061 -0
  193. package/src/database/base-model.ts +184 -0
  194. package/src/database/client.ts +140 -0
  195. package/src/database/repository.ts +104 -0
  196. package/src/database/runtime-check.ts +25 -0
  197. package/src/index.ts +27 -0
  198. package/src/machine/contracts.ts +17 -0
  199. package/src/machine/errors.ts +34 -0
  200. package/src/machine/index.ts +173 -0
  201. package/src/mcp/index.ts +191 -0
  202. package/src/types/index.ts +134 -0
  203. package/src/utils/package-manager.ts +238 -0
  204. package/src/utils/python-uv.ts +96 -0
@@ -0,0 +1,3600 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { spawn, execSync } from "child_process";
4
+ import prompts from "prompts";
5
+ import { BackendLanguage } from "../../types";
6
+ import {
7
+ type PackageManager,
8
+ detectFromUserAgent,
9
+ getCommands,
10
+ getWorkspaceConfig,
11
+ getCiSetupStep,
12
+ getAzurePipelinesSetup,
13
+ getBuildScript,
14
+ getFunctionsPrestart,
15
+ getFunctionsStartScript,
16
+ getSwaAppBuildCommand,
17
+ } from "../../utils/package-manager";
18
+ import { syncProjectManifest } from "../../core/project/manifest";
19
+ import {
20
+ buildCSharpCodegenToolManifestSource,
21
+ buildPythonCodegenRequirementsSource,
22
+ } from "../../core/scaffold/native-schema-generator";
23
+ import { getProjectLocalUvPaths } from "../../utils/python-uv";
24
+
25
+ interface InitOptions {
26
+ name: string;
27
+ template: string;
28
+ nextVersion?: string;
29
+ cicd?: CiCdProvider;
30
+ backendLanguage?: BackendLanguage;
31
+ cosmosDbMode?: CosmosDbMode;
32
+ vnet?: VNetOption;
33
+ }
34
+
35
+ type CiCdProvider = 'github' | 'azure' | 'skip';
36
+ type CosmosDbMode = 'freetier' | 'serverless';
37
+ type VNetOption = 'none' | 'outbound';
38
+
39
+ interface AzureConfig {
40
+ cosmosDbMode: CosmosDbMode;
41
+ vnetOption: VNetOption;
42
+ }
43
+
44
+ const BACKEND_LANGUAGE_CHOICES: Array<{ title: string; value: BackendLanguage }> = [
45
+ { title: "TypeScript", value: "typescript" },
46
+ { title: "C#", value: "csharp" },
47
+ { title: "Python", value: "python" },
48
+ ];
49
+
50
+ function usesNodeFunctionsProject(backendLanguage: BackendLanguage): boolean {
51
+ return backendLanguage === "typescript";
52
+ }
53
+
54
+ function getBackendLanguageLabel(backendLanguage: BackendLanguage): string {
55
+ return BACKEND_LANGUAGE_CHOICES.find((choice) => choice.value === backendLanguage)?.title || backendLanguage;
56
+ }
57
+
58
+ export function buildCosmosDbFreeTierBicepSource(): string {
59
+ return `@description('Cosmos DB account name')
60
+ param accountName string
61
+
62
+ @description('Database name')
63
+ param databaseName string
64
+
65
+ @description('Location for Cosmos DB')
66
+ param location string
67
+
68
+ @description('Public network access')
69
+ @allowed(['Enabled', 'Disabled'])
70
+ param publicNetworkAccess string = 'Enabled'
71
+
72
+ // Cosmos DB Account (Free Tier)
73
+ resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {
74
+ name: accountName
75
+ location: location
76
+ kind: 'GlobalDocumentDB'
77
+ properties: {
78
+ databaseAccountOfferType: 'Standard'
79
+ enableAutomaticFailover: false
80
+ enableFreeTier: true
81
+ publicNetworkAccess: publicNetworkAccess
82
+ disableLocalAuth: true
83
+ consistencyPolicy: {
84
+ defaultConsistencyLevel: 'Session'
85
+ }
86
+ locations: [
87
+ {
88
+ locationName: location
89
+ failoverPriority: 0
90
+ isZoneRedundant: false
91
+ }
92
+ ]
93
+ disableKeyBasedMetadataWriteAccess: true
94
+ }
95
+ }
96
+
97
+ // Cosmos DB Database
98
+ resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15' = {
99
+ parent: cosmosAccount
100
+ name: databaseName
101
+ properties: {
102
+ resource: {
103
+ id: databaseName
104
+ }
105
+ options: {
106
+ throughput: 1000
107
+ }
108
+ }
109
+ }
110
+
111
+ output id string = cosmosAccount.id
112
+ output accountName string = cosmosAccount.name
113
+ output endpoint string = cosmosAccount.properties.documentEndpoint
114
+ output databaseName string = database.name
115
+ `;
116
+ }
117
+
118
+ function getFunctionsWorkerRuntime(backendLanguage: BackendLanguage): string {
119
+ if (backendLanguage === "csharp") {
120
+ return "dotnet-isolated";
121
+ }
122
+ if (backendLanguage === "python") {
123
+ return "python";
124
+ }
125
+ return "node";
126
+ }
127
+
128
+ function getFunctionsRuntimeConfig(backendLanguage: BackendLanguage): { name: string; version: string } {
129
+ if (backendLanguage === "csharp") {
130
+ return { name: "dotnet-isolated", version: "10.0" };
131
+ }
132
+ if (backendLanguage === "python") {
133
+ return { name: "python", version: "3.11" };
134
+ }
135
+ return { name: "node", version: "22" };
136
+ }
137
+
138
+ export function buildSharedTsConfig() {
139
+ return {
140
+ compilerOptions: {
141
+ target: "ES2020",
142
+ module: "Node16",
143
+ moduleResolution: "node16",
144
+ lib: ["ES2020"],
145
+ outDir: "dist",
146
+ rootDir: ".",
147
+ declaration: true,
148
+ declarationMap: true,
149
+ sourceMap: true,
150
+ strict: true,
151
+ esModuleInterop: true,
152
+ skipLibCheck: true,
153
+ forceConsistentCasingInFileNames: true,
154
+ },
155
+ include: ["index.ts", "models/**/*"],
156
+ exclude: ["node_modules", "dist"],
157
+ };
158
+ }
159
+
160
+ async function promptBackendLanguage(): Promise<BackendLanguage> {
161
+ const response = await prompts({
162
+ type: "select",
163
+ name: "backendLanguage",
164
+ message: "Azure Functions backend language:",
165
+ choices: BACKEND_LANGUAGE_CHOICES,
166
+ initial: 0,
167
+ });
168
+
169
+ return response.backendLanguage || "typescript";
170
+ }
171
+
172
+ async function promptCiCd(): Promise<CiCdProvider> {
173
+ const response = await prompts({
174
+ type: 'select',
175
+ name: 'cicd',
176
+ message: 'CI/CD Setup (choose deployment automation):',
177
+ choices: [
178
+ { title: 'GitHub Actions', value: 'github' },
179
+ { title: 'Azure Pipelines', value: 'azure' },
180
+ { title: 'Skip (manual deployment)', value: 'skip' }
181
+ ],
182
+ initial: 0
183
+ });
184
+
185
+ return response.cicd || 'skip';
186
+ }
187
+
188
+ async function promptAzureConfig(): Promise<AzureConfig> {
189
+ const cosmosResponse = await prompts({
190
+ type: 'select',
191
+ name: 'mode',
192
+ message: 'Cosmos DB mode (affects cost):',
193
+ choices: [
194
+ { title: 'Free Tier (1000 RU/s free, best for first project)', value: 'freetier' },
195
+ { title: 'Serverless (pay-per-use, flexible)', value: 'serverless' }
196
+ ],
197
+ initial: 0
198
+ });
199
+
200
+ const vnetResponse = await prompts({
201
+ type: 'select',
202
+ name: 'vnet',
203
+ message: 'Network security:',
204
+ choices: [
205
+ { title: 'VNet Integration (recommended) - Cosmos DB via Private Endpoint', value: 'outbound' },
206
+ { title: 'None - Public endpoints, simplest but least secure', value: 'none' }
207
+ ],
208
+ initial: 0
209
+ });
210
+
211
+ return {
212
+ cosmosDbMode: cosmosResponse.mode || 'freetier',
213
+ vnetOption: vnetResponse.vnet || 'outbound'
214
+ };
215
+ }
216
+
217
+ const VALID_CICD: CiCdProvider[] = ['github', 'azure', 'skip'];
218
+ const VALID_BACKEND_LANGUAGE: BackendLanguage[] = ['typescript', 'csharp', 'python'];
219
+ const VALID_COSMOS_DB_MODE: CosmosDbMode[] = ['freetier', 'serverless'];
220
+ const VALID_VNET: VNetOption[] = ['none', 'outbound'];
221
+
222
+ function validateInitFlags(options: InitOptions): void {
223
+ if (options.cicd && !VALID_CICD.includes(options.cicd)) {
224
+ console.error(`❌ Invalid --cicd value: "${options.cicd}". Must be: ${VALID_CICD.join(', ')}`);
225
+ process.exit(1);
226
+ }
227
+ if (options.backendLanguage && !VALID_BACKEND_LANGUAGE.includes(options.backendLanguage)) {
228
+ console.error(`❌ Invalid --backend-language value: "${options.backendLanguage}". Must be: ${VALID_BACKEND_LANGUAGE.join(', ')}`);
229
+ process.exit(1);
230
+ }
231
+ if (options.cosmosDbMode && !VALID_COSMOS_DB_MODE.includes(options.cosmosDbMode)) {
232
+ console.error(`❌ Invalid --cosmos-db-mode value: "${options.cosmosDbMode}". Must be: ${VALID_COSMOS_DB_MODE.join(', ')}`);
233
+ process.exit(1);
234
+ }
235
+ if (options.vnet && !VALID_VNET.includes(options.vnet)) {
236
+ console.error(`❌ Invalid --vnet value: "${options.vnet}". Must be: ${VALID_VNET.join(', ')}`);
237
+ process.exit(1);
238
+ }
239
+ }
240
+
241
+ export async function initCommand(options: InitOptions) {
242
+ // Validate flag values before doing anything
243
+ validateInitFlags(options);
244
+
245
+ console.log(`🚀 Initializing SwallowKit project: ${options.name}`);
246
+ console.log(`📋 Template: ${options.template}`);
247
+
248
+ // Detect package manager from invocation context (npx → npm, pnpm dlx → pnpm)
249
+ const pm: PackageManager = detectFromUserAgent();
250
+ const pmCmd = getCommands(pm);
251
+ console.log(`📦 Package manager: ${pm}`);
252
+
253
+ const projectDir = path.join(process.cwd(), options.name);
254
+
255
+ try {
256
+ // Check if directory already exists
257
+ if (fs.existsSync(projectDir)) {
258
+ console.error(`❌ Directory "${options.name}" already exists.`);
259
+ process.exit(1);
260
+ }
261
+
262
+ // Use flag values if provided, otherwise prompt interactively
263
+ const cicdProvider: CiCdProvider = options.cicd || await promptCiCd();
264
+ const backendLanguage: BackendLanguage = options.backendLanguage || await promptBackendLanguage();
265
+
266
+ const azureConfig: AzureConfig = (options.cosmosDbMode && options.vnet)
267
+ ? { cosmosDbMode: options.cosmosDbMode, vnetOption: options.vnet }
268
+ : await promptAzureConfig();
269
+
270
+ // Create Next.js project with create-next-app
271
+ await createNextJsProject(options.name, pm);
272
+
273
+ // Upgrade Next.js to specified version (or latest) to avoid cached old versions
274
+ await upgradeNextJs(projectDir, options.nextVersion || 'latest', pm);
275
+
276
+ // Add SwallowKit specific files
277
+ await addSwallowKitFiles(projectDir, options, cicdProvider, azureConfig, pm, backendLanguage);
278
+
279
+ // Create infrastructure files (Bicep)
280
+ await createInfrastructure(projectDir, options.name, azureConfig, backendLanguage);
281
+
282
+ // Create CI/CD files based on choice
283
+ if (cicdProvider === 'github') {
284
+ await createGitHubActionsWorkflows(projectDir, azureConfig, pm, backendLanguage);
285
+ } else if (cicdProvider === 'azure') {
286
+ await createAzurePipelines(projectDir, pm, backendLanguage);
287
+ }
288
+
289
+ await syncProjectManifest(projectDir);
290
+
291
+ // Initialize Git repository and create initial commit
292
+ try {
293
+ // Try git init with -b main (Git 2.28+), fallback to git init
294
+ try {
295
+ execSync('git init -b main', { cwd: projectDir, stdio: 'ignore' });
296
+ } catch {
297
+ // Fallback for older Git versions
298
+ execSync('git init', { cwd: projectDir, stdio: 'ignore' });
299
+ }
300
+
301
+ // Configure git user if not set (required for commits)
302
+ try {
303
+ execSync('git config user.name', { cwd: projectDir, stdio: 'pipe' });
304
+ execSync('git config user.email', { cwd: projectDir, stdio: 'pipe' });
305
+ } catch {
306
+ // Not configured globally, set locally for this repository
307
+ execSync('git config user.name "SwallowKit"', { cwd: projectDir, stdio: 'ignore' });
308
+ execSync('git config user.email "swallowkit@example.com"', { cwd: projectDir, stdio: 'ignore' });
309
+ }
310
+
311
+ execSync('git add -A', { cwd: projectDir, stdio: 'ignore' });
312
+ execSync('git commit -m "Initial commit from SwallowKit"', { cwd: projectDir, stdio: 'ignore' });
313
+
314
+ // Rename branch to main if git init -b main didn't work
315
+ try {
316
+ const currentBranch = execSync('git branch --show-current', { cwd: projectDir, encoding: 'utf-8' }).trim();
317
+ if (currentBranch !== 'main') {
318
+ execSync('git branch -M main', { cwd: projectDir, stdio: 'ignore' });
319
+ }
320
+ } catch {
321
+ // Ignore errors - branch renaming is not critical
322
+ }
323
+
324
+ console.log('✅ Git repository initialized with initial commit\n');
325
+ } catch (error) {
326
+ console.warn('⚠️ Could not initialize Git repository (is git installed?)');
327
+ if (error instanceof Error) {
328
+ console.warn(` Error: ${error.message}`);
329
+ }
330
+ }
331
+
332
+ console.log(`\n✅ Project "${options.name}" created successfully!`);
333
+ console.log("\n📝 Next steps:");
334
+ console.log(` cd ${options.name}`);
335
+ console.log(` ${pmCmd.dlx} swallowkit create-model <name> # Create your first model`);
336
+ console.log(` ${pmCmd.dlx} swallowkit scaffold shared/models/<name>.ts # Generate CRUD code`);
337
+ console.log(` ${pmCmd.dlx} swallowkit dev # Start development servers`);
338
+ console.log("\n🚀 Deploy to Azure:");
339
+ console.log(` ${pmCmd.dlx} swallowkit provision --resource-group <name>`);
340
+ if (cicdProvider !== 'skip') {
341
+ console.log(" Configure CI/CD secrets and push to repository");
342
+ }
343
+ } catch (error) {
344
+ console.error("❌ Project creation failed:", error);
345
+ // Clean up on failure
346
+ if (fs.existsSync(projectDir)) {
347
+ fs.rmSync(projectDir, { recursive: true, force: true });
348
+ }
349
+ process.exit(1);
350
+ }
351
+ }
352
+
353
+ async function createNextJsProject(projectName: string, pm: PackageManager): Promise<void> {
354
+ return new Promise((resolve, reject) => {
355
+ console.log('\n📦 Creating Next.js project with create-next-app...\n');
356
+
357
+ const pmCmd = getCommands(pm);
358
+
359
+ // Build args: for pnpm use "pnpm dlx create-next-app@latest ... --use-pnpm"
360
+ // for npm use "npx create-next-app@latest ..."
361
+ const baseArgs = pm === 'pnpm'
362
+ ? ['dlx', 'create-next-app@latest']
363
+ : ['create-next-app@latest'];
364
+
365
+ const args = [
366
+ ...baseArgs,
367
+ projectName,
368
+ '--typescript',
369
+ '--tailwind',
370
+ '--app',
371
+ '--no-src',
372
+ '--disable-git',
373
+ '--import-alias',
374
+ '@/*',
375
+ ...(pmCmd.createNextAppFlag ? [pmCmd.createNextAppFlag] : []),
376
+ '--yes'
377
+ ];
378
+
379
+ // Run create-next-app with recommended options for Azure
380
+ const createNextApp = spawn(
381
+ pm === 'pnpm' ? 'pnpm' : 'npx',
382
+ args,
383
+ {
384
+ stdio: 'inherit',
385
+ shell: true,
386
+ }
387
+ );
388
+
389
+ createNextApp.on('close', (code: number | null) => {
390
+ if (code !== 0) {
391
+ reject(new Error(`create-next-app exited with code ${code}`));
392
+ } else {
393
+ console.log('\n✅ Next.js project created\n');
394
+ resolve();
395
+ }
396
+ });
397
+
398
+ createNextApp.on('error', (error: Error) => {
399
+ reject(error);
400
+ });
401
+ });
402
+ }
403
+
404
+ async function upgradeNextJs(projectDir: string, version: string, pm: PackageManager): Promise<void> {
405
+ console.log(`\n📦 Installing Next.js ${version} (to ensure latest security patches)...\n`);
406
+
407
+ // pnpm: pnpm add next@... ; npm: npm install next@...
408
+ const args = pm === 'pnpm'
409
+ ? ['add', `next@${version}`, `react@latest`, `react-dom@latest`, '--save-exact']
410
+ : ['install', `next@${version}`, `react@latest`, `react-dom@latest`, '--save-exact'];
411
+
412
+ await runPackageManagerCommand(pm, args, projectDir, `${pm} add next@${version}`);
413
+
414
+ console.log(`\n✅ Next.js ${version} installed\n`);
415
+ }
416
+
417
+ async function installDependencies(projectDir: string, pm: PackageManager = 'pnpm'): Promise<void> {
418
+ console.log('\n📦 Installing dependencies...\n');
419
+ await runPackageManagerCommand(pm, ['install'], projectDir, `${pm} install`);
420
+ console.log('\n✅ Dependencies installed\n');
421
+ }
422
+
423
+ /**
424
+ * Run a package-manager command with stdio passed through to the user.
425
+ *
426
+ * For pnpm, additionally tee stdout/stderr to a buffer so that if the command
427
+ * fails due to `ERR_PNPM_IGNORED_BUILDS`, we can:
428
+ * 1. detect which packages were ignored,
429
+ * 2. interactively ask the user whether to approve them, and
430
+ * 3. run `pnpm approve-builds` followed by a retry of the original command.
431
+ */
432
+ async function runPackageManagerCommand(
433
+ pm: PackageManager,
434
+ args: string[],
435
+ projectDir: string,
436
+ label: string,
437
+ ): Promise<void> {
438
+ const { code, output } = await spawnAndCapture(pm, args, projectDir, pm === 'pnpm');
439
+
440
+ if (code === 0) return;
441
+
442
+ if (pm === 'pnpm') {
443
+ const ignoredBuilds = parseIgnoredBuilds(output);
444
+ if (ignoredBuilds.length > 0) {
445
+ const approved = await maybeApproveBuilds(projectDir, ignoredBuilds);
446
+ if (approved) {
447
+ // Retry the original command now that build scripts are approved.
448
+ const retry = await spawnAndCapture(pm, args, projectDir, true);
449
+ if (retry.code === 0) return;
450
+ throw new Error(`${label} exited with code ${retry.code} after approving builds`);
451
+ }
452
+ }
453
+ }
454
+
455
+ throw new Error(`${label} exited with code ${code}`);
456
+ }
457
+
458
+ /**
459
+ * Spawn a child process inheriting stdin (so interactive prompts still work)
460
+ * while either inheriting or capturing+teeing stdout/stderr.
461
+ */
462
+ function spawnAndCapture(
463
+ pm: PackageManager,
464
+ args: string[],
465
+ projectDir: string,
466
+ capture: boolean,
467
+ ): Promise<{ code: number; output: string }> {
468
+ return new Promise((resolve, reject) => {
469
+ const stdio: ('inherit' | 'pipe')[] = capture
470
+ ? ['inherit', 'pipe', 'pipe']
471
+ : ['inherit', 'inherit', 'inherit'];
472
+
473
+ const child = spawn(pm, args, {
474
+ cwd: projectDir,
475
+ stdio,
476
+ shell: true,
477
+ });
478
+
479
+ let combined = '';
480
+ if (capture) {
481
+ child.stdout?.on('data', (chunk: Buffer) => {
482
+ process.stdout.write(chunk);
483
+ combined += chunk.toString('utf8');
484
+ });
485
+ child.stderr?.on('data', (chunk: Buffer) => {
486
+ process.stderr.write(chunk);
487
+ combined += chunk.toString('utf8');
488
+ });
489
+ }
490
+
491
+ child.on('close', (code) => resolve({ code: code ?? 0, output: combined }));
492
+ child.on('error', reject);
493
+ });
494
+ }
495
+
496
+ /**
497
+ * Parse pnpm's `Ignored build scripts: foo@1.0.0, bar@2.0.0` warning/error and
498
+ * return the bare package names (without versions), de-duplicated.
499
+ */
500
+ export function parseIgnoredBuilds(output: string): string[] {
501
+ const match = output.match(/Ignored build scripts:\s*([^\n\r]+)/i);
502
+ if (!match) return [];
503
+ const list = match[1]
504
+ .split(',')
505
+ .map((entry) => entry.trim())
506
+ // strip version suffix: `sharp@0.34.5` -> `sharp`, `@scope/pkg@1.0.0` -> `@scope/pkg`
507
+ .map((entry) => entry.replace(/@[^@]+$/, ''))
508
+ .filter((name) => name.length > 0);
509
+ return Array.from(new Set(list));
510
+ }
511
+
512
+ /**
513
+ * Prompt the user and, if approved, run `pnpm approve-builds` followed by
514
+ * `pnpm rebuild <packages>`. Returns true if the user approved (regardless of
515
+ * which packages they actually selected inside approve-builds).
516
+ */
517
+ async function maybeApproveBuilds(projectDir: string, ignoredBuilds: string[]): Promise<boolean> {
518
+ console.log(
519
+ `\n⚠️ pnpm refused to run build scripts for: ${ignoredBuilds.join(', ')}\n` +
520
+ ' These packages (e.g. sharp) need their build scripts to run correctly.\n',
521
+ );
522
+
523
+ const response = await prompts({
524
+ type: 'confirm',
525
+ name: 'approve',
526
+ message: 'Run `pnpm approve-builds` now to approve these build scripts?',
527
+ initial: true,
528
+ });
529
+
530
+ if (!response.approve) {
531
+ console.log(
532
+ '\nℹ️ Skipped. You can run `pnpm approve-builds` later inside the project directory.\n',
533
+ );
534
+ return false;
535
+ }
536
+
537
+ await runSimple('pnpm', ['approve-builds'], projectDir);
538
+ await runSimple('pnpm', ['rebuild', ...ignoredBuilds], projectDir);
539
+
540
+ console.log('\n✅ Build scripts approved and packages rebuilt\n');
541
+ return true;
542
+ }
543
+
544
+ function runSimple(command: string, args: string[], cwd: string): Promise<void> {
545
+ return new Promise((resolve, reject) => {
546
+ const child = spawn(command, args, { cwd, stdio: 'inherit', shell: true });
547
+ child.on('close', (code) => {
548
+ if (code !== 0) reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`));
549
+ else resolve();
550
+ });
551
+ child.on('error', reject);
552
+ });
553
+ }
554
+
555
+ export function injectSwallowKitNextConfig(nextConfigContent: string, projectName: string): string {
556
+ return nextConfigContent.replace(
557
+ /(const\s+nextConfig[:\s]*(?::\s*NextConfig\s*)?=\s*\{)(\s*\/\*[^*]*\*\/)?/,
558
+ `$1\n output: 'standalone',\n transpilePackages: ['@${projectName}/shared'],\n serverExternalPackages: ['applicationinsights', 'diagnostic-channel-publishers'],$2`
559
+ );
560
+ }
561
+
562
+ export function buildCSharpFunctionsProgramSource(): string {
563
+ return `using Microsoft.Azure.Functions.Worker;
564
+ using Microsoft.Extensions.DependencyInjection;
565
+ using Microsoft.Extensions.Hosting;
566
+ using Microsoft.Azure.Functions.Worker.ApplicationInsights;
567
+
568
+ var host = new HostBuilder()
569
+ .ConfigureFunctionsWorkerDefaults()
570
+ .ConfigureServices(services =>
571
+ {
572
+ services.AddApplicationInsightsTelemetryWorkerService();
573
+ services.ConfigureFunctionsApplicationInsights();
574
+ })
575
+ .Build();
576
+
577
+ host.Run();
578
+ `;
579
+ }
580
+
581
+ export function buildCSharpFunctionsProjectSource(): string {
582
+ return `<Project Sdk="Microsoft.NET.Sdk">
583
+ <PropertyGroup>
584
+ <TargetFramework>net10.0</TargetFramework>
585
+ <AzureFunctionsVersion>v4</AzureFunctionsVersion>
586
+ <OutputType>Exe</OutputType>
587
+ <ImplicitUsings>enable</ImplicitUsings>
588
+ <Nullable>enable</Nullable>
589
+ </PropertyGroup>
590
+ <ItemGroup>
591
+ <Compile Remove="generated\\**\\bin\\**\\*.cs;generated\\**\\obj\\**\\*.cs" />
592
+ <EmbeddedResource Remove="generated\\**\\bin\\**;generated\\**\\obj\\**" />
593
+ <None Remove="generated\\**\\bin\\**;generated\\**\\obj\\**" />
594
+ </ItemGroup>
595
+ <ItemGroup>
596
+ <PackageReference Include="Microsoft.Azure.Cosmos" Version="3.47.0" />
597
+ <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
598
+ <PackageReference Include="Azure.Identity" Version="1.17.0" />
599
+ <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.52.0" />
600
+ <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.3.0" />
601
+ <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.7" OutputItemType="Analyzer" />
602
+ <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
603
+ <PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="2.50.0" />
604
+ </ItemGroup>
605
+ </Project>
606
+ `;
607
+ }
608
+
609
+ export function buildSwallowKitConfigSource(backendLanguage: BackendLanguage): string {
610
+ return `module.exports = {
611
+ backend: {
612
+ language: '${backendLanguage}',
613
+ },
614
+ functions: {
615
+ baseUrl: process.env.BACKEND_FUNCTIONS_BASE_URL || process.env.FUNCTIONS_BASE_URL || 'http://localhost:7071',
616
+ },
617
+ deployment: {
618
+ resourceGroup: process.env.AZURE_RESOURCE_GROUP || '',
619
+ swaName: process.env.AZURE_SWA_NAME || '',
620
+ },
621
+ }
622
+ `;
623
+ }
624
+
625
+ export function buildGeneratedProjectDependencies(projectName: string): Record<string, string> {
626
+ return {
627
+ '@azure/cosmos': '^4.0.0',
628
+ 'applicationinsights': '^3.3.0',
629
+ [`@${projectName}/shared`]: 'workspace:*',
630
+ };
631
+ }
632
+
633
+ function getSwallowKitPackageMetadata(): { name: string; version: string } {
634
+ const packageJsonPath = path.resolve(__dirname, "..", "..", "..", "package.json");
635
+
636
+ try {
637
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
638
+ name?: string;
639
+ version?: string;
640
+ };
641
+
642
+ return {
643
+ name: packageJson.name || "swallowkit",
644
+ version: packageJson.version || "latest",
645
+ };
646
+ } catch {
647
+ // Fall back to the published package name when package metadata is unavailable.
648
+ }
649
+
650
+ return {
651
+ name: "swallowkit",
652
+ version: "latest",
653
+ };
654
+ }
655
+
656
+ export function buildGeneratedProjectDevDependencies(): Record<string, string> {
657
+ const { name, version } = getSwallowKitPackageMetadata();
658
+ return {
659
+ [name]: version,
660
+ };
661
+ }
662
+
663
+ export function buildSwallowKitMcpProjectConfigSource(): string {
664
+ const { name } = getSwallowKitPackageMetadata();
665
+ return JSON.stringify(
666
+ {
667
+ mcpServers: {
668
+ swallowkit: {
669
+ command: "node",
670
+ args: [`./node_modules/${name}/dist/mcp/index.js`],
671
+ cwd: ".",
672
+ },
673
+ },
674
+ },
675
+ null,
676
+ 2
677
+ );
678
+ }
679
+
680
+ async function addSwallowKitFiles(
681
+ projectDir: string,
682
+ options: InitOptions,
683
+ cicdChoice: string,
684
+ azureConfig: AzureConfig,
685
+ pm: PackageManager,
686
+ backendLanguage: BackendLanguage
687
+ ) {
688
+ console.log('📦 Adding SwallowKit files...\n');
689
+
690
+ const projectName = options.name;
691
+
692
+ // 1. Update package.json to add runtime dependencies for generated projects
693
+ const packageJsonPath = path.join(projectDir, 'package.json');
694
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
695
+
696
+ // zod is in the shared workspace package, not here
697
+ packageJson.dependencies = {
698
+ ...packageJson.dependencies,
699
+ ...buildGeneratedProjectDependencies(projectName),
700
+ };
701
+ packageJson.devDependencies = {
702
+ ...packageJson.devDependencies,
703
+ ...buildGeneratedProjectDevDependencies(),
704
+ };
705
+
706
+ packageJson.scripts = {
707
+ ...packageJson.scripts,
708
+ 'build': getBuildScript(pm),
709
+ 'start': 'next start',
710
+ 'functions:start': getFunctionsStartScript(pm, backendLanguage),
711
+ };
712
+
713
+ packageJson.engines = {
714
+ node: '20.x',
715
+ };
716
+
717
+ // Workspace configuration depends on package manager
718
+ const workspacePackages = usesNodeFunctionsProject(backendLanguage) ? ['shared', 'functions'] : ['shared'];
719
+ const wsConfig = getWorkspaceConfig(pm, workspacePackages);
720
+ if (wsConfig.type === 'file') {
721
+ // pnpm: workspaces are defined in pnpm-workspace.yaml
722
+ delete packageJson.workspaces;
723
+ } else {
724
+ // npm: workspaces are defined in package.json
725
+ packageJson.workspaces = wsConfig.value;
726
+ }
727
+
728
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
729
+
730
+ // Create workspace config file if needed (pnpm-workspace.yaml)
731
+ if (wsConfig.type === 'file') {
732
+ fs.writeFileSync(path.join(projectDir, wsConfig.filename), wsConfig.content);
733
+ }
734
+
735
+ // Don't install yet — wait until all workspace packages (shared, functions) are created
736
+
737
+ // 2. Update next.config to add standalone output
738
+ // Check for both .ts and .js variants
739
+ let nextConfigPath = path.join(projectDir, 'next.config.ts');
740
+ if (!fs.existsSync(nextConfigPath)) {
741
+ nextConfigPath = path.join(projectDir, 'next.config.js');
742
+ }
743
+
744
+ if (fs.existsSync(nextConfigPath)) {
745
+ let nextConfigContent = fs.readFileSync(nextConfigPath, 'utf-8');
746
+
747
+ // Add output, transpiled workspace package, and server externals for standalone deployment
748
+ if (!nextConfigContent.includes("output:") && !nextConfigContent.includes('output =')) {
749
+ nextConfigContent = injectSwallowKitNextConfig(nextConfigContent, projectName);
750
+ fs.writeFileSync(nextConfigPath, nextConfigContent);
751
+ }
752
+ }
753
+
754
+ // 3. Update tsconfig.json to exclude functions directory
755
+ const tsconfigPath = path.join(projectDir, 'tsconfig.json');
756
+ if (fs.existsSync(tsconfigPath)) {
757
+ const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf-8'));
758
+ if (!tsconfig.exclude) {
759
+ tsconfig.exclude = [];
760
+ }
761
+ if (!tsconfig.exclude.includes('functions')) {
762
+ tsconfig.exclude.push('functions');
763
+ }
764
+ if (!tsconfig.exclude.includes('shared')) {
765
+ tsconfig.exclude.push('shared');
766
+ }
767
+ fs.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2));
768
+ }
769
+
770
+ // 3. Create SwallowKit config
771
+ const swallowkitConfig = buildSwallowKitConfigSource(backendLanguage);
772
+ fs.writeFileSync(path.join(projectDir, 'swallowkit.config.js'), swallowkitConfig);
773
+
774
+ // 4. Create shared workspace package for Zod models (Single Source of Truth)
775
+ await createSharedPackage(projectDir, projectName);
776
+
777
+ // Create lib directory for Next.js-specific utilities
778
+ const libDir = path.join(projectDir, 'lib');
779
+
780
+ // Create lib/api directory for backend utilities
781
+ const apiLibDir = path.join(libDir, 'api');
782
+ fs.mkdirSync(apiLibDir, { recursive: true });
783
+
784
+ // Create backend utility for calling Azure Functions
785
+ const backendUtilContent = `// Get Functions base URL at runtime (not at build time)
786
+ function getFunctionsBaseUrl(): string {
787
+ return process.env.BACKEND_FUNCTIONS_BASE_URL || process.env.FUNCTIONS_BASE_URL || 'http://localhost:7071';
788
+ }
789
+
790
+ /**
791
+ * Simple HTTP client for calling backend APIs
792
+ * Use this to make requests to BFF API routes (which forward to Azure Functions)
793
+ */
794
+ async function request<T>(
795
+ endpoint: string,
796
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE',
797
+ body?: any,
798
+ queryParams?: Record<string, string>
799
+ ): Promise<T> {
800
+ const functionsBaseUrl = getFunctionsBaseUrl();
801
+ let url = \`\${functionsBaseUrl}\${endpoint}\`;
802
+ if (queryParams) {
803
+ const params = new URLSearchParams(queryParams);
804
+ url += \`?\${params.toString()}\`;
805
+ }
806
+
807
+ try {
808
+ const response = await fetch(url, {
809
+ method,
810
+ headers: {
811
+ 'Content-Type': 'application/json',
812
+ },
813
+ body: body ? JSON.stringify(body) : undefined,
814
+ });
815
+
816
+ if (!response.ok) {
817
+ const text = await response.text();
818
+ let errorMessage = text || 'Failed to call backend function';
819
+ try {
820
+ const error = JSON.parse(text);
821
+ errorMessage = error.error || error.message || text;
822
+ } catch {
823
+ // If not JSON, use text as-is
824
+ }
825
+ throw new Error(errorMessage);
826
+ }
827
+
828
+ const contentType = response.headers.get('content-type');
829
+ if (!contentType?.includes('application/json')) {
830
+ const text = await response.text();
831
+ return text as T;
832
+ }
833
+
834
+ return await response.json();
835
+ } catch (error) {
836
+ console.error('Error calling backend:', error);
837
+ throw error;
838
+ }
839
+ }
840
+
841
+ /**
842
+ * Generic API client for making HTTP requests
843
+ * Simply calls endpoints - no DB dependencies, no schema validation
844
+ * Validation happens on the backend (BFF/Functions)
845
+ *
846
+ * @example
847
+ * // Call custom endpoint
848
+ * await api.get('/api/greet?name=World')
849
+ *
850
+ * // Call scaffolded CRUD endpoints
851
+ * await api.get('/api/todos')
852
+ * await api.post('/api/todos', { title: 'New task' })
853
+ * await api.put('/api/todos/123', { title: 'Updated' })
854
+ * await api.delete('/api/todos/123')
855
+ */
856
+ export const api = {
857
+ /**
858
+ * Make a GET request
859
+ */
860
+ get: <T>(endpoint: string, params?: Record<string, string>): Promise<T> => {
861
+ return request<T>(endpoint, 'GET', undefined, params);
862
+ },
863
+
864
+ /**
865
+ * Make a POST request
866
+ */
867
+ post: <T>(endpoint: string, body?: any): Promise<T> => {
868
+ return request<T>(endpoint, 'POST', body);
869
+ },
870
+
871
+ /**
872
+ * Make a PUT request
873
+ */
874
+ put: <T>(endpoint: string, body?: any): Promise<T> => {
875
+ return request<T>(endpoint, 'PUT', body);
876
+ },
877
+
878
+ /**
879
+ * Make a DELETE request
880
+ */
881
+ delete: <T>(endpoint: string): Promise<T> => {
882
+ return request<T>(endpoint, 'DELETE');
883
+ },
884
+ };
885
+ `;
886
+ fs.writeFileSync(path.join(apiLibDir, 'backend.ts'), backendUtilContent);
887
+
888
+ // 5. Create components directory
889
+ const componentsDir = path.join(projectDir, 'components');
890
+ fs.mkdirSync(componentsDir, { recursive: true });
891
+
892
+ // 6. Create .env.example
893
+ const envExample = `# Azure Functions Backend URL
894
+ BACKEND_FUNCTIONS_BASE_URL=http://localhost:7071
895
+
896
+ # Azure Configuration
897
+ AZURE_RESOURCE_GROUP=your-resource-group
898
+ AZURE_SWA_NAME=your-static-web-app-name
899
+ `;
900
+ fs.writeFileSync(path.join(projectDir, '.env.example'), envExample);
901
+
902
+ // 7. Create instrumentation.ts for Application Insights (Next.js official way)
903
+ const instrumentationContent = `// Application Insights instrumentation for Next.js
904
+ // This file is automatically loaded by Next.js when instrumentationHook is enabled
905
+ export async function register() {
906
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
907
+ // Only run on server-side
908
+ const connectionString = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING;
909
+
910
+ if (connectionString) {
911
+ const appInsights = await import('applicationinsights');
912
+
913
+ appInsights
914
+ .setup(connectionString)
915
+ .setAutoCollectConsole(true)
916
+ .setAutoCollectDependencies(true)
917
+ .setAutoCollectExceptions(true)
918
+ .setAutoCollectHeartbeat(true)
919
+ .setAutoCollectPerformance(true, true)
920
+ .setAutoCollectRequests(true)
921
+ .setAutoDependencyCorrelation(true)
922
+ .setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C)
923
+ .setSendLiveMetrics(true)
924
+ .setUseDiskRetryCaching(true);
925
+
926
+ appInsights.defaultClient.setAutoPopulateAzureProperties();
927
+ appInsights.start();
928
+
929
+ // Override console methods to send to Application Insights
930
+ const originalConsoleLog = console.log;
931
+ const originalConsoleError = console.error;
932
+ const originalConsoleWarn = console.warn;
933
+
934
+ console.log = function(...args: any[]) {
935
+ originalConsoleLog.apply(console, args);
936
+ const message = args.map(arg =>
937
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
938
+ ).join(' ');
939
+ appInsights.defaultClient.trackTrace({
940
+ message: message,
941
+ severity: '1'
942
+ });
943
+ };
944
+
945
+ console.error = function(...args: any[]) {
946
+ originalConsoleError.apply(console, args);
947
+ const message = args.map(arg =>
948
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
949
+ ).join(' ');
950
+ appInsights.defaultClient.trackTrace({
951
+ message: message,
952
+ severity: '3'
953
+ });
954
+ };
955
+
956
+ console.warn = function(...args: any[]) {
957
+ originalConsoleWarn.apply(console, args);
958
+ const message = args.map(arg =>
959
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
960
+ ).join(' ');
961
+ appInsights.defaultClient.trackTrace({
962
+ message: message,
963
+ severity: '2'
964
+ });
965
+ };
966
+
967
+ console.log('[App Insights] Initialized for Next.js server-side telemetry with console override');
968
+ } else {
969
+ console.log('[App Insights] Not configured (skipped in development mode)');
970
+ }
971
+ }
972
+ }
973
+ `;
974
+ fs.writeFileSync(path.join(projectDir, 'instrumentation.ts'), instrumentationContent);
975
+
976
+ // 8. Create .env.local for local development
977
+ const envLocalContent = [
978
+ '# Azure Functions Backend URL (Local)',
979
+ 'BACKEND_FUNCTIONS_BASE_URL=http://localhost:7071',
980
+ ''
981
+ ].join('\n');
982
+ fs.writeFileSync(path.join(projectDir, '.env.local'), envLocalContent);
983
+
984
+ // 8. Create staticwebapp.config.json for Azure Static Web Apps (Next.js Hybrid Rendering)
985
+ const swaConfig = {
986
+ platform: {
987
+ apiRuntime: "node:20"
988
+ },
989
+ routes: [
990
+ {
991
+ route: "/*",
992
+ allowedRoles: ["anonymous"]
993
+ }
994
+ ],
995
+ globalHeaders: {
996
+ "X-Content-Type-Options": "nosniff",
997
+ "X-Frame-Options": "DENY",
998
+ "X-XSS-Protection": "1; mode=block"
999
+ },
1000
+ mimeTypes: {
1001
+ ".json": "application/json"
1002
+ }
1003
+ };
1004
+ fs.writeFileSync(
1005
+ path.join(projectDir, 'staticwebapp.config.json'),
1006
+ JSON.stringify(swaConfig, null, 2)
1007
+ );
1008
+
1009
+ // 14. Create Azure Functions project
1010
+ await createAzureFunctionsProject(projectDir, pm, backendLanguage);
1011
+
1012
+ // 15. Create BFF API route to call Azure Functions
1013
+ await createBffApiRoute(projectDir);
1014
+
1015
+ // 16. Create home page
1016
+ await createHomePage(projectDir, pm);
1017
+
1018
+ // 17. Install all workspace dependencies (root + shared + functions)
1019
+ console.log('📦 Installing workspace dependencies...\n');
1020
+ await installDependencies(projectDir, pm);
1021
+
1022
+ console.log('✅ Project structure created\n');
1023
+
1024
+ // 18. Create README.md
1025
+ createReadme(projectDir, projectName, cicdChoice, azureConfig, pm, backendLanguage);
1026
+
1027
+ // 19. Create AI agent instruction files (AGENTS.md, CLAUDE.md, .github/copilot-instructions.md, etc.)
1028
+ createAiAgentFiles(projectDir, projectName, backendLanguage, pm);
1029
+ }
1030
+
1031
+ async function createSharedPackage(projectDir: string, projectName: string) {
1032
+ console.log('📦 Creating shared workspace package for Zod models...\n');
1033
+
1034
+ const sharedDir = path.join(projectDir, 'shared');
1035
+ const modelsDir = path.join(sharedDir, 'models');
1036
+ fs.mkdirSync(modelsDir, { recursive: true });
1037
+
1038
+ // shared/package.json
1039
+ const sharedPackageJson = {
1040
+ private: true,
1041
+ name: `@${projectName}/shared`,
1042
+ version: '1.0.0',
1043
+ description: 'Shared Zod models — Single Source of Truth for validation schemas',
1044
+ main: 'dist/index.js',
1045
+ types: 'dist/index.d.ts',
1046
+ scripts: {
1047
+ build: 'tsc',
1048
+ watch: 'tsc --watch',
1049
+ },
1050
+ dependencies: {
1051
+ 'zod': '>=3.25.0',
1052
+ },
1053
+ devDependencies: {
1054
+ 'typescript': '^5.0.0',
1055
+ },
1056
+ };
1057
+ fs.writeFileSync(
1058
+ path.join(sharedDir, 'package.json'),
1059
+ JSON.stringify(sharedPackageJson, null, 2)
1060
+ );
1061
+
1062
+ // shared/tsconfig.json
1063
+ fs.writeFileSync(
1064
+ path.join(sharedDir, 'tsconfig.json'),
1065
+ JSON.stringify(buildSharedTsConfig(), null, 2)
1066
+ );
1067
+
1068
+ // shared/index.ts (empty re-export file, scaffold will add entries)
1069
+ fs.writeFileSync(
1070
+ path.join(sharedDir, 'index.ts'),
1071
+ `// Shared Zod models — auto-managed by SwallowKit scaffold command\n// Do not edit the export list below manually\n`
1072
+ );
1073
+
1074
+ // shared/.gitignore
1075
+ fs.writeFileSync(
1076
+ path.join(sharedDir, '.gitignore'),
1077
+ `node_modules\ndist\n`
1078
+ );
1079
+
1080
+ console.log('✅ Shared package created\n');
1081
+ }
1082
+
1083
+ async function createAzureFunctionsProject(
1084
+ projectDir: string,
1085
+ pm: PackageManager = 'pnpm',
1086
+ backendLanguage: BackendLanguage = 'typescript'
1087
+ ) {
1088
+ console.log(`📦 Creating Azure Functions project (${getBackendLanguageLabel(backendLanguage)})...\n`);
1089
+
1090
+ const functionsDir = path.join(projectDir, 'functions');
1091
+ fs.mkdirSync(functionsDir, { recursive: true });
1092
+
1093
+ const projectName = path.basename(projectDir);
1094
+ const databaseName = `${projectName.charAt(0).toUpperCase() + projectName.slice(1)}Database`;
1095
+
1096
+ createFunctionsHostFiles(functionsDir, databaseName, backendLanguage);
1097
+
1098
+ if (backendLanguage === 'typescript') {
1099
+ createTypeScriptFunctionsProject(projectDir, functionsDir, pm);
1100
+ } else if (backendLanguage === 'csharp') {
1101
+ createCSharpFunctionsProject(projectDir, functionsDir);
1102
+ } else {
1103
+ createPythonFunctionsProject(projectDir, functionsDir);
1104
+ }
1105
+
1106
+ console.log('✅ Azure Functions project created\n');
1107
+ }
1108
+
1109
+ function createFunctionsHostFiles(functionsDir: string, databaseName: string, backendLanguage: BackendLanguage): void {
1110
+ const hostJson = {
1111
+ version: '2.0',
1112
+ logging: {
1113
+ applicationInsights: {
1114
+ samplingSettings: {
1115
+ isEnabled: true,
1116
+ maxTelemetryItemsPerSecond: 20,
1117
+ },
1118
+ },
1119
+ },
1120
+ extensionBundle: {
1121
+ id: 'Microsoft.Azure.Functions.ExtensionBundle',
1122
+ version: '[4.0.0, 4.10.0)',
1123
+ },
1124
+ };
1125
+ fs.writeFileSync(path.join(functionsDir, 'host.json'), JSON.stringify(hostJson, null, 2));
1126
+
1127
+ const localSettings = {
1128
+ IsEncrypted: false,
1129
+ Values: {
1130
+ AzureWebJobsStorage: '',
1131
+ FUNCTIONS_WORKER_RUNTIME: getFunctionsWorkerRuntime(backendLanguage),
1132
+ AzureWebJobsFeatureFlags: 'EnableWorkerIndexing',
1133
+ CosmosDBConnection: 'AccountEndpoint=http://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==',
1134
+ COSMOS_DB_DATABASE_NAME: databaseName,
1135
+ NODE_TLS_REJECT_UNAUTHORIZED: '0',
1136
+ },
1137
+ };
1138
+ fs.writeFileSync(path.join(functionsDir, 'local.settings.json'), JSON.stringify(localSettings, null, 2));
1139
+
1140
+ const gitignoreLines = [
1141
+ 'local.settings.json',
1142
+ '*.log',
1143
+ '.vscode',
1144
+ '.DS_Store',
1145
+ ];
1146
+
1147
+ if (backendLanguage === 'typescript') {
1148
+ gitignoreLines.unshift('node_modules', 'dist');
1149
+ fs.writeFileSync(path.join(functionsDir, '.funcignore'), `node_modules
1150
+ .git
1151
+ .vscode
1152
+ local.settings.json
1153
+ test
1154
+ tsconfig.json
1155
+ *.ts
1156
+ !dist/**/*.js
1157
+ `);
1158
+ } else if (backendLanguage === 'python') {
1159
+ gitignoreLines.unshift('.venv', '.codegen-venv', '__pycache__', '.python_packages');
1160
+ fs.writeFileSync(path.join(functionsDir, '.funcignore'), `.venv
1161
+ .codegen-venv
1162
+ __pycache__
1163
+ .pytest_cache
1164
+ .mypy_cache
1165
+ .ruff_cache
1166
+ local.settings.json
1167
+ tests
1168
+ `);
1169
+ } else {
1170
+ gitignoreLines.unshift('bin', 'obj');
1171
+ fs.writeFileSync(path.join(functionsDir, '.funcignore'), `bin
1172
+ obj
1173
+ local.settings.json
1174
+ tests
1175
+ `);
1176
+ }
1177
+
1178
+ fs.writeFileSync(path.join(functionsDir, '.gitignore'), `${gitignoreLines.join('\n')}\n`);
1179
+ }
1180
+
1181
+ function createTypeScriptFunctionsProject(projectDir: string, functionsDir: string, pm: PackageManager): void {
1182
+ const functionsPackageJson = {
1183
+ name: 'functions',
1184
+ version: '1.0.0',
1185
+ description: 'Azure Functions backend',
1186
+ main: 'dist/*.js',
1187
+ scripts: {
1188
+ start: 'func start',
1189
+ build: 'tsc',
1190
+ prestart: getFunctionsPrestart(pm),
1191
+ },
1192
+ dependencies: {
1193
+ '@azure/functions': '~4.5.0',
1194
+ '@azure/cosmos': '^4.0.0',
1195
+ '@azure/identity': '^4.0.0',
1196
+ zod: '>=3.25.0',
1197
+ [`@${path.basename(projectDir)}/shared`]: 'workspace:*',
1198
+ },
1199
+ devDependencies: {
1200
+ '@types/node': '^20.0.0',
1201
+ typescript: '^5.0.0',
1202
+ },
1203
+ };
1204
+ fs.writeFileSync(path.join(functionsDir, 'package.json'), JSON.stringify(functionsPackageJson, null, 2));
1205
+
1206
+ const sharedPkgName = `@${path.basename(projectDir)}/shared`;
1207
+ const functionsTsConfig = {
1208
+ compilerOptions: {
1209
+ target: 'ES2020',
1210
+ module: 'commonjs',
1211
+ moduleResolution: 'node',
1212
+ lib: ['ES2020'],
1213
+ outDir: 'dist',
1214
+ rootDir: 'src',
1215
+ strict: true,
1216
+ esModuleInterop: true,
1217
+ skipLibCheck: true,
1218
+ forceConsistentCasingInFileNames: true,
1219
+ paths: {
1220
+ [sharedPkgName]: ['../shared'],
1221
+ [`${sharedPkgName}/*`]: ['../shared/*'],
1222
+ },
1223
+ },
1224
+ include: ['src/**/*'],
1225
+ exclude: ['node_modules', 'dist'],
1226
+ };
1227
+ fs.writeFileSync(path.join(functionsDir, 'tsconfig.json'), JSON.stringify(functionsTsConfig, null, 2));
1228
+
1229
+ const srcDir = path.join(functionsDir, 'src');
1230
+ fs.mkdirSync(srcDir, { recursive: true });
1231
+ fs.writeFileSync(path.join(srcDir, 'greet.ts'), `import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';
1232
+ import { z } from 'zod/v4';
1233
+
1234
+ const greetRequestSchema = z.object({
1235
+ name: z.string().min(1, 'Name is required').max(50, 'Name must be less than 50 characters'),
1236
+ });
1237
+
1238
+ export async function greet(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
1239
+ context.log('HTTP trigger function processed a request.');
1240
+
1241
+ try {
1242
+ const name = request.query.get('name') || (await request.text());
1243
+ const result = greetRequestSchema.safeParse({ name });
1244
+
1245
+ if (!result.success) {
1246
+ return {
1247
+ status: 400,
1248
+ jsonBody: {
1249
+ error: result.error.issues[0].message
1250
+ }
1251
+ };
1252
+ }
1253
+
1254
+ const greeting = \`Hello, \${result.data.name}! This message is from Azure Functions.\`;
1255
+
1256
+ return {
1257
+ status: 200,
1258
+ jsonBody: {
1259
+ message: greeting,
1260
+ timestamp: new Date().toISOString()
1261
+ }
1262
+ };
1263
+ } catch (error) {
1264
+ context.error('Error processing request:', error);
1265
+ return {
1266
+ status: 500,
1267
+ jsonBody: {
1268
+ error: 'Internal server error'
1269
+ }
1270
+ };
1271
+ }
1272
+ }
1273
+
1274
+ app.http('greet', {
1275
+ methods: ['GET', 'POST'],
1276
+ authLevel: 'anonymous',
1277
+ handler: greet
1278
+ });
1279
+ `);
1280
+ }
1281
+
1282
+ function createCSharpFunctionsProject(projectDir: string, functionsDir: string): void {
1283
+ const projectBaseName = path.basename(projectDir);
1284
+ const projectPascal = projectBaseName.charAt(0).toUpperCase() + projectBaseName.slice(1);
1285
+ const csprojName = `${projectPascal}.Functions.csproj`;
1286
+
1287
+ fs.writeFileSync(path.join(functionsDir, csprojName), buildCSharpFunctionsProjectSource());
1288
+ fs.mkdirSync(path.join(functionsDir, '.config'), { recursive: true });
1289
+ fs.writeFileSync(
1290
+ path.join(functionsDir, '.config', 'dotnet-tools.json'),
1291
+ buildCSharpCodegenToolManifestSource()
1292
+ );
1293
+
1294
+ fs.writeFileSync(path.join(functionsDir, 'Program.cs'), buildCSharpFunctionsProgramSource());
1295
+
1296
+ const crudDir = path.join(functionsDir, 'Crud');
1297
+ fs.mkdirSync(crudDir, { recursive: true });
1298
+ fs.writeFileSync(path.join(crudDir, 'GreetFunction.cs'), `using System.Net;
1299
+ using Microsoft.Azure.Functions.Worker;
1300
+ using Microsoft.Azure.Functions.Worker.Http;
1301
+
1302
+ namespace SwallowKit.Functions;
1303
+
1304
+ public sealed class GreetFunction
1305
+ {
1306
+ [Function("greet")]
1307
+ public async Task<HttpResponseData> Run(
1308
+ [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "greet")] HttpRequestData request)
1309
+ {
1310
+ var query = request.Url.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries);
1311
+ var name = "SwallowKit";
1312
+ foreach (var segment in query)
1313
+ {
1314
+ var parts = segment.Split('=', 2);
1315
+ if (parts.Length == 2 && parts[0] == "name")
1316
+ {
1317
+ name = Uri.UnescapeDataString(parts[1]);
1318
+ break;
1319
+ }
1320
+ }
1321
+ var response = request.CreateResponse(HttpStatusCode.OK);
1322
+ await response.WriteAsJsonAsync(new
1323
+ {
1324
+ message = $"Hello, {name}! This message is from Azure Functions.",
1325
+ timestamp = DateTimeOffset.UtcNow.ToString("O"),
1326
+ });
1327
+ return response;
1328
+ }
1329
+ }
1330
+ `);
1331
+ }
1332
+
1333
+ function createPythonFunctionsProject(projectDir: string, functionsDir: string): void {
1334
+ fs.writeFileSync(path.join(projectDir, '.python-version'), '3.11\n');
1335
+ ensureProjectGitignoreEntry(projectDir, '.uv');
1336
+
1337
+ fs.writeFileSync(path.join(functionsDir, 'requirements.txt'), `azure-functions>=1.20.0
1338
+ azure-cosmos>=4.9.0
1339
+ azure-identity>=1.19.0
1340
+ `);
1341
+ fs.writeFileSync(
1342
+ path.join(functionsDir, 'requirements.codegen.txt'),
1343
+ buildPythonCodegenRequirementsSource()
1344
+ );
1345
+
1346
+ const blueprintsDir = path.join(functionsDir, 'blueprints');
1347
+ fs.mkdirSync(blueprintsDir, { recursive: true });
1348
+ fs.writeFileSync(path.join(blueprintsDir, '__init__.py'), '');
1349
+
1350
+ fs.writeFileSync(path.join(blueprintsDir, 'greet.py'), `import json
1351
+ from datetime import datetime, timezone
1352
+
1353
+ import azure.functions as func
1354
+
1355
+ bp = func.Blueprint()
1356
+
1357
+
1358
+ @bp.route(route="greet", methods=["GET", "POST"])
1359
+ def greet(req: func.HttpRequest) -> func.HttpResponse:
1360
+ name = req.params.get("name") or "SwallowKit"
1361
+ payload = {
1362
+ "message": f"Hello, {name}! This message is from Azure Functions.",
1363
+ "timestamp": datetime.now(timezone.utc).isoformat(),
1364
+ }
1365
+ return func.HttpResponse(
1366
+ body=json.dumps(payload, ensure_ascii=False),
1367
+ status_code=200,
1368
+ mimetype="application/json",
1369
+ )
1370
+ `);
1371
+
1372
+ fs.writeFileSync(path.join(functionsDir, 'function_app.py'), `import azure.functions as func
1373
+
1374
+ from blueprints.greet import bp as greet_bp
1375
+
1376
+ app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
1377
+
1378
+ app.register_blueprint(greet_bp)
1379
+ # SwallowKit scaffold registrations
1380
+ `);
1381
+ }
1382
+
1383
+ function ensureProjectGitignoreEntry(projectDir: string, entry: string): void {
1384
+ const gitignorePath = path.join(projectDir, '.gitignore');
1385
+ if (!fs.existsSync(gitignorePath)) {
1386
+ return;
1387
+ }
1388
+
1389
+ const current = fs.readFileSync(gitignorePath, 'utf8');
1390
+ const lines = current.split(/\r?\n/);
1391
+ if (lines.includes(entry)) {
1392
+ return;
1393
+ }
1394
+
1395
+ const normalized = current.endsWith('\n') ? current : `${current}\n`;
1396
+ fs.writeFileSync(gitignorePath, `${normalized}${entry}\n`);
1397
+ }
1398
+
1399
+ async function createBffApiRoute(projectDir: string) {
1400
+ console.log('📦 Creating BFF API route...\n');
1401
+
1402
+ const apiDir = path.join(projectDir, 'app', 'api', 'greet');
1403
+ fs.mkdirSync(apiDir, { recursive: true });
1404
+
1405
+ // Create API route that calls Azure Functions using shared utility
1406
+ const apiRoute = `import { NextRequest, NextResponse } from 'next/server';
1407
+ import { api } from '@/lib/api/backend';
1408
+
1409
+ interface GreetResponse {
1410
+ message: string;
1411
+ timestamp: string;
1412
+ }
1413
+
1414
+ export async function GET(request: NextRequest) {
1415
+ try {
1416
+ const { searchParams } = new URL(request.url);
1417
+ const name = searchParams.get('name') || 'World';
1418
+
1419
+ const data = await api.get<GreetResponse>('/api/greet', { name });
1420
+
1421
+ return NextResponse.json(data);
1422
+ } catch (error) {
1423
+ console.error('Error calling Azure Functions:', error);
1424
+ const errorMessage = error instanceof Error ? error.message : 'Failed to call backend function';
1425
+ return NextResponse.json(
1426
+ { error: errorMessage, details: 'Make sure Azure Functions is running on port 7071' },
1427
+ { status: 500 }
1428
+ );
1429
+ }
1430
+ }
1431
+
1432
+ export async function POST(request: NextRequest) {
1433
+ try {
1434
+ const body = await request.json();
1435
+
1436
+ const data = await api.post<GreetResponse>('/api/greet', body);
1437
+
1438
+ return NextResponse.json(data);
1439
+ } catch (error) {
1440
+ console.error('Error calling Azure Functions:', error);
1441
+ const errorMessage = error instanceof Error ? error.message : 'Failed to call backend function';
1442
+ return NextResponse.json(
1443
+ { error: errorMessage, details: 'Make sure Azure Functions is running on port 7071' },
1444
+ { status: 500 }
1445
+ );
1446
+ }
1447
+ }
1448
+ `;
1449
+ fs.writeFileSync(path.join(apiDir, 'route.ts'), apiRoute);
1450
+
1451
+ // Update .env.example to include BACKEND_FUNCTIONS_BASE_URL
1452
+ const envExamplePath = path.join(projectDir, '.env.example');
1453
+ let envExample = fs.readFileSync(envExamplePath, 'utf-8');
1454
+
1455
+ if (!envExample.includes('BACKEND_FUNCTIONS_BASE_URL')) {
1456
+ envExample += `\n# Azure Functions Backend URL\nBACKEND_FUNCTIONS_BASE_URL=http://localhost:7071\n`;
1457
+ fs.writeFileSync(envExamplePath, envExample);
1458
+ }
1459
+
1460
+ // Update .env.local
1461
+ const envLocalPath = path.join(projectDir, '.env.local');
1462
+ let envLocal = fs.readFileSync(envLocalPath, 'utf-8');
1463
+
1464
+ if (!envLocal.includes('BACKEND_FUNCTIONS_BASE_URL')) {
1465
+ envLocal += `\n# Azure Functions Backend URL (Local)\nBACKEND_FUNCTIONS_BASE_URL=http://localhost:7071\n`;
1466
+ fs.writeFileSync(envLocalPath, envLocal);
1467
+ }
1468
+
1469
+ console.log('✅ BFF API route created\n');
1470
+ }
1471
+
1472
+ async function createHomePage(projectDir: string, pm: PackageManager = 'pnpm') {
1473
+ console.log('📦 Creating home page...\n');
1474
+
1475
+ const pmCmd = getCommands(pm);
1476
+
1477
+ const pageContent = `'use client'
1478
+
1479
+ export const dynamic = 'force-dynamic';
1480
+
1481
+ import { useState } from 'react';
1482
+ import { scaffoldConfig } from '@/lib/scaffold-config';
1483
+
1484
+ export default function Home() {
1485
+ const [greetingStatus, setGreetingStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
1486
+ const [message, setMessage] = useState('');
1487
+
1488
+ const testConnection = async () => {
1489
+ setGreetingStatus('loading');
1490
+ try {
1491
+ const response = await fetch('/api/greet?name=SwallowKit');
1492
+ const data = await response.json();
1493
+ if (!response.ok) {
1494
+ throw new Error(data.error || \`Server error: \${response.status}\`);
1495
+ }
1496
+ setMessage(data.message);
1497
+ setGreetingStatus('success');
1498
+ } catch (error) {
1499
+ setMessage(error instanceof Error ? error.message : 'Failed to connect to Azure Functions');
1500
+ setGreetingStatus('error');
1501
+ }
1502
+ };
1503
+
1504
+ return (
1505
+ <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-gray-900 dark:to-gray-800">
1506
+ <div className="container mx-auto px-4 py-12">
1507
+ <header className="text-center mb-16">
1508
+ <h1 className="text-5xl font-bold text-gray-800 dark:text-white mb-4">
1509
+ Welcome to SwallowKit
1510
+ </h1>
1511
+ <p className="text-xl text-gray-600 dark:text-gray-400">
1512
+ Next.js on Azure Static Web Apps + Functions + Cosmos DB — Zod schema sharing
1513
+ </p>
1514
+ </header>
1515
+
1516
+ {/* Connection Test */}
1517
+ <section className="max-w-2xl mx-auto mb-12">
1518
+ <div className="bg-white dark:bg-gray-800 rounded-xl p-8 border border-gray-200 dark:border-gray-700">
1519
+ <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-gray-100">
1520
+ Test BFF → Functions Connection
1521
+ </h2>
1522
+ <button
1523
+ onClick={testConnection}
1524
+ disabled={greetingStatus === 'loading'}
1525
+ className="px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white rounded-lg font-medium transition-colors"
1526
+ >
1527
+ {greetingStatus === 'loading' ? 'Testing...' : 'Test Connection'}
1528
+ </button>
1529
+ {greetingStatus === 'success' && (
1530
+ <div className="mt-4 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
1531
+ <p className="text-green-800 dark:text-green-200 font-medium">✅ Connection successful!</p>
1532
+ <p className="text-green-700 dark:text-green-300 text-sm mt-1">{message}</p>
1533
+ </div>
1534
+ )}
1535
+ {greetingStatus === 'error' && (
1536
+ <div className="mt-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
1537
+ <p className="text-red-800 dark:text-red-200 font-medium">❌ Connection failed</p>
1538
+ <p className="text-red-700 dark:text-red-300 text-sm mt-1">{message}</p>
1539
+ </div>
1540
+ )}
1541
+ </div>
1542
+ </section>
1543
+
1544
+ {/* Scaffolded Models Menu */}
1545
+ {scaffoldConfig.models.length > 0 ? (
1546
+ <section className="max-w-6xl mx-auto">
1547
+ <h2 className="text-3xl font-bold mb-8 text-gray-900 dark:text-gray-100">Your Models</h2>
1548
+ <div className="grid gap-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
1549
+ {scaffoldConfig.models.map((model) => (
1550
+ <a
1551
+ key={model.name}
1552
+ href={model.path}
1553
+ className="block p-8 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl hover:shadow-lg hover:border-blue-400 dark:hover:border-blue-600 transition-all"
1554
+ >
1555
+ <h3 className="text-2xl font-semibold mb-2 text-gray-900 dark:text-gray-100">{model.label}</h3>
1556
+ <p className="text-gray-600 dark:text-gray-400">Manage {model.label.toLowerCase()}</p>
1557
+ </a>
1558
+ ))}
1559
+ </div>
1560
+ </section>
1561
+ ) : (
1562
+ <section className="max-w-2xl mx-auto text-center">
1563
+ <div className="bg-white dark:bg-gray-800 rounded-xl p-12 border border-gray-200 dark:border-gray-700">
1564
+ <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-gray-100">Get Started</h2>
1565
+ <p className="text-gray-600 dark:text-gray-400 mb-6">
1566
+ Create your first model with Zod and generate CRUD operations automatically.
1567
+ </p>
1568
+ <code className="block bg-gray-100 dark:bg-gray-900 p-4 rounded text-left text-sm">
1569
+ ${pmCmd.dlx} swallowkit scaffold shared/models/your-model.ts
1570
+ </code>
1571
+ </div>
1572
+ </section>
1573
+ )}
1574
+
1575
+ <footer className="mt-16 text-center text-gray-600 dark:text-gray-400 text-sm">
1576
+ <p>Built with SwallowKit</p>
1577
+ </footer>
1578
+ </div>
1579
+ </div>
1580
+ );
1581
+ }
1582
+ `;
1583
+
1584
+ fs.writeFileSync(path.join(projectDir, 'app', 'page.tsx'), pageContent);
1585
+
1586
+ console.log('✅ Home page created\n');
1587
+
1588
+ // Create initial scaffold-config.ts
1589
+ const scaffoldConfigDir = path.join(projectDir, 'lib');
1590
+ if (!fs.existsSync(scaffoldConfigDir)) {
1591
+ fs.mkdirSync(scaffoldConfigDir, { recursive: true });
1592
+ }
1593
+
1594
+ const scaffoldConfigContent = `export interface ScaffoldModel {
1595
+ name: string;
1596
+ path: string;
1597
+ label: string;
1598
+ }
1599
+
1600
+ export const scaffoldConfig = {
1601
+ models: [
1602
+ // Scaffolded models will be added here by 'swallowkit scaffold' command
1603
+ ] as ScaffoldModel[]
1604
+ };
1605
+ `;
1606
+
1607
+ fs.writeFileSync(path.join(scaffoldConfigDir, 'scaffold-config.ts'), scaffoldConfigContent);
1608
+ console.log('✅ Scaffold config created\n');
1609
+ }
1610
+
1611
+ function createReadme(
1612
+ projectDir: string,
1613
+ projectName: string,
1614
+ cicdChoice: string,
1615
+ azureConfig: AzureConfig,
1616
+ pm: PackageManager,
1617
+ backendLanguage: BackendLanguage
1618
+ ) {
1619
+ console.log('📝 Creating README.md...\n');
1620
+
1621
+ const pmCmd = getCommands(pm);
1622
+ const cosmosDbModeLabel = azureConfig.cosmosDbMode === 'freetier' ? 'Free Tier (1000 RU/s)' : 'Serverless';
1623
+ const cicdLabel = cicdChoice === 'github' ? 'GitHub Actions' : cicdChoice === 'azure' ? 'Azure Pipelines' : 'None';
1624
+ const vnetLabel = azureConfig.vnetOption === 'none' ? 'None (public endpoints)' :
1625
+ 'Outbound VNet (Cosmos DB Private Endpoint)';
1626
+ const backendLanguageLabel = getBackendLanguageLabel(backendLanguage);
1627
+ const schemaBridgeDescription = backendLanguage === 'typescript'
1628
+ ? 'Zod (shared between frontend and backend)'
1629
+ : `Zod + OpenAPI export (Zod in shared/, native-generated ${backendLanguageLabel} schemas in functions/generated/)`;
1630
+ const functionsTree = backendLanguage === 'typescript'
1631
+ ? `│ └── src/\n│ └── greet.ts # Sample function`
1632
+ : backendLanguage === 'csharp'
1633
+ ? `│ ├── Crud/\n│ │ └── GreetFunction.cs\n│ └── generated/ # Native-generated C# schema assets`
1634
+ : `│ ├── blueprints/\n│ │ └── greet.py\n│ └── generated/ # Native-generated Python schema assets`;
1635
+ const backendScaffoldNote = backendLanguage === 'typescript'
1636
+ ? '- Azure Functions CRUD endpoints'
1637
+ : `- Azure Functions ${backendLanguageLabel} CRUD handlers\n- OpenAPI export + native-generated ${backendLanguageLabel} schema assets`;
1638
+ const pythonUvPaths = getProjectLocalUvPaths(projectDir);
1639
+ const pythonLocalDevNote = backendLanguage === 'python'
1640
+ ? `\n**Python local dev note**: SwallowKit uses \`uv\` for Python backends and keeps the managed Python runtime under \`${path.relative(projectDir, pythonUvPaths.pythonInstallDir)}\`. Local Azure Functions runs from \`functions/.venv\`, schema generation uses \`functions/.codegen-venv\`, and \`swallowkit dev\` bootstraps a project-local \`uv\` binary automatically when needed. Keep \`functions/requirements.txt\` and \`functions/requirements.codegen.txt\` as the dependency sources of truth.\n`
1641
+ : '';
1642
+
1643
+ const readme = `# ${projectName}
1644
+
1645
+ A full-stack application built with **SwallowKit** - Next.js on Azure Static Web Apps + Functions + Cosmos DB with Zod schema sharing.
1646
+
1647
+ ## 🚀 Tech Stack
1648
+
1649
+ - **Frontend**: Next.js 15 (App Router), React, TypeScript, Tailwind CSS
1650
+ - **BFF (Backend for Frontend)**: Next.js API Routes
1651
+ - **Backend**: Azure Functions (${backendLanguageLabel})
1652
+ - **Database**: Azure Cosmos DB
1653
+ - **Schema Validation**: ${schemaBridgeDescription}
1654
+ - **Infrastructure**: Bicep (Infrastructure as Code)
1655
+ - **CI/CD**: ${cicdLabel}
1656
+
1657
+ ## 📋 Project Configuration
1658
+
1659
+ This project was initialized with the following settings:
1660
+
1661
+ - **Azure Functions Plan**: Flex Consumption
1662
+ - **Cosmos DB Mode**: ${cosmosDbModeLabel}
1663
+ - **Network Security**: ${vnetLabel}
1664
+ - **CI/CD**: ${cicdLabel}
1665
+
1666
+ ## ✅ Prerequisites
1667
+
1668
+ Before you begin, ensure you have the following installed:
1669
+
1670
+ 1. **Node.js 18+**: [Download](https://nodejs.org/)${pm === 'pnpm' ? `\n2. **pnpm**: \`corepack enable\` or \`npm install -g pnpm\`` : ''}
1671
+ ${pm === 'pnpm' ? '3' : '2'}. **Azure CLI**: Required for provisioning Azure resources
1672
+ - Install: \`winget install Microsoft.AzureCLI\` (Windows)
1673
+ - Or: [Download](https://aka.ms/installazurecliwindows)
1674
+ ${pm === 'pnpm' ? '4' : '3'}. **Azure Cosmos DB Emulator**: Required for local development
1675
+ - Windows: \`winget install Microsoft.Azure.CosmosEmulator\`
1676
+ - Or: [Download](https://aka.ms/cosmosdb-emulator)
1677
+ - Docker: \`docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator\`
1678
+ ${pm === 'pnpm' ? '6' : '5'}. **Azure Functions Core Tools**: Automatically installed with project dependencies
1679
+
1680
+ ## 📁 Project Structure
1681
+
1682
+ \`\`\`
1683
+ ${projectName}/
1684
+ ├── app/ # Next.js App Router (frontend)
1685
+ │ ├── api/ # BFF API routes (proxy to Functions)
1686
+ │ └── page.tsx # Home page
1687
+ ├── functions/ # Azure Functions (backend)
1688
+ ${functionsTree}
1689
+ ├── lib/
1690
+ │ └── api/ # API client utilities
1691
+ ├── infra/ # Bicep infrastructure files
1692
+ │ ├── main.bicep
1693
+ │ └── modules/ # Bicep modules for each resource
1694
+ └── .github/workflows/ # CI/CD workflows
1695
+ \`\`\`
1696
+
1697
+ ## 🏗️ Getting Started
1698
+
1699
+ ### 1. Create Your First Model
1700
+
1701
+ Define your data model with Zod schema:
1702
+
1703
+ \`\`\`bash
1704
+ ${pmCmd.dlx} swallowkit create-model <model-name>
1705
+ \`\`\`
1706
+
1707
+ This creates a model file in \`shared/models/<model-name>.ts\`. Edit it to define your schema.
1708
+
1709
+ ### 2. Generate CRUD Code
1710
+
1711
+ Generate complete CRUD operations (Functions, API routes, UI):
1712
+
1713
+ \`\`\`bash
1714
+ ${pmCmd.dlx} swallowkit scaffold shared/models/<model-name>.ts
1715
+ \`\`\`
1716
+
1717
+ This generates:
1718
+ ${backendScaffoldNote}
1719
+ - Next.js BFF API routes
1720
+ - React UI components (list, detail, create, edit)
1721
+ - Navigation menu integration
1722
+
1723
+ ### 3. Start Development Servers
1724
+
1725
+ \`\`\`bash
1726
+ ${pmCmd.dlx} swallowkit dev
1727
+ \`\`\`
1728
+
1729
+ This starts:
1730
+ - Next.js dev server (http://localhost:3000)
1731
+ - Azure Functions (http://localhost:7071)
1732
+ - Cosmos DB Emulator check (must be running separately)
1733
+
1734
+ **Note**: You need to start Cosmos DB Emulator manually before running \`swallowkit dev\`.
1735
+ ${pythonLocalDevNote}
1736
+
1737
+ ## ☁️ Deploy to Azure
1738
+
1739
+ ### Provision Azure Resources
1740
+
1741
+ Create all required Azure resources using Bicep:
1742
+
1743
+ \`\`\`bash
1744
+ ${pmCmd.dlx} swallowkit provision --resource-group <rg-name>
1745
+ \`\`\`
1746
+
1747
+ This creates:
1748
+ - Static Web App (\`swa-${projectName}\`)
1749
+ - Azure Functions (\`func-${projectName}\`)
1750
+ - Cosmos DB (\`cosmos-${projectName}\`)
1751
+ - Storage Account
1752
+
1753
+ You will be prompted to select Azure regions:
1754
+ 1. **Primary location**: For Functions and Cosmos DB (default: Japan East)
1755
+ 2. **Static Web App location**: Limited availability (default: East Asia)
1756
+
1757
+ ### CI/CD Setup
1758
+
1759
+ ${cicdChoice === 'github' ? `#### GitHub Actions
1760
+
1761
+ 1. Get Static Web App deployment token:
1762
+ \`\`\`bash
1763
+ az staticwebapp secrets list --name swa-${projectName} --resource-group <rg-name> --query "properties.apiKey" -o tsv
1764
+ \`\`\`
1765
+
1766
+ 2. Get Function App publish profile:
1767
+ \`\`\`bash
1768
+ az webapp deployment list-publishing-profiles --name func-${projectName} --resource-group <rg-name> --xml
1769
+ \`\`\`
1770
+
1771
+ 3. Add secrets to GitHub repository:
1772
+ - \`AZURE_STATIC_WEB_APPS_API_TOKEN\`: SWA deployment token (from step 1)
1773
+ - \`AZURE_FUNCTIONAPP_NAME\`: \`func-${projectName}\`
1774
+ - \`AZURE_FUNCTIONAPP_PUBLISH_PROFILE\`: Functions publish profile (from step 2)
1775
+
1776
+ 4. Push to \`main\` branch to trigger deployment (or use **Actions** → **Run workflow** for manual deployment)` : cicdChoice === 'azure' ? `#### Azure Pipelines
1777
+
1778
+ 1. Set up service connection in Azure DevOps
1779
+ 2. Update \`azure-pipelines.yml\` with your resource names
1780
+ 3. Configure pipeline variables:
1781
+ - \`azureSubscription\`: Service connection name
1782
+ - \`resourceGroupName\`: Resource group name
1783
+ 4. Run pipeline to deploy` : `CI/CD is not configured. You can manually deploy:
1784
+
1785
+ **Deploy Static Web App:**
1786
+ \`\`\`bash
1787
+ ${pmCmd.run} build
1788
+ az staticwebapp deploy --name swa-${projectName} --resource-group <rg-name> --app-location ./
1789
+ \`\`\`
1790
+
1791
+ **Deploy Functions:**
1792
+ \`\`\`bash
1793
+ cd functions
1794
+ ${pmCmd.run} build
1795
+ func azure functionapp publish func-${projectName}
1796
+ \`\`\``}
1797
+
1798
+ ## 🔧 Available Commands
1799
+
1800
+ - \`${pmCmd.dlx} swallowkit create-model <name>\` - Create a new data model
1801
+ - \`${pmCmd.dlx} swallowkit scaffold <model-file>\` - Generate CRUD code
1802
+ - \`${pmCmd.dlx} swallowkit dev\` - Start development servers
1803
+ - \`${pmCmd.dlx} swallowkit provision -g <rg-name>\` - Provision Azure resources
1804
+ ${azureConfig.vnetOption !== 'none' ? `
1805
+ ## 🔒 Network Security (VNet Configuration)
1806
+
1807
+ This project is configured with **${vnetLabel}**.
1808
+
1809
+ ### Architecture
1810
+
1811
+ \`\`\`
1812
+ Static Web App ──(public)──> Azure Functions ──(VNet/PE)──> Cosmos DB
1813
+
1814
+ VNet Integration
1815
+ (outbound only)
1816
+ \`\`\`
1817
+
1818
+ - **Functions → Cosmos DB**: Connected via Private Endpoint (private connection)
1819
+ - **SWA → Functions**: Connected via public endpoint (secured with CORS + IP restrictions)
1820
+
1821
+ ### VNet Resources
1822
+
1823
+ | Resource | Purpose |
1824
+ |----------|---------|
1825
+ | \`vnet-${projectName}\` | Virtual Network (10.0.0.0/16) |
1826
+ | \`snet-functions\` | Functions subnet (10.0.1.0/24) |
1827
+ | \`snet-private-endpoints\` | Private Endpoints subnet (10.0.2.0/24) |
1828
+ | \`pe-cosmos-${projectName}\` | Cosmos DB Private Endpoint |
1829
+
1830
+ ### Private DNS Zones
1831
+
1832
+ - \`privatelink.documents.azure.com\` (Cosmos DB)
1833
+ ` : ''}
1834
+ ## 📚 Learn More
1835
+
1836
+ - [SwallowKit Documentation](https://github.com/himanago/swallowkit)
1837
+ - [Azure Static Web Apps](https://learn.microsoft.com/en-us/azure/static-web-apps/)
1838
+ - [Azure Functions](https://learn.microsoft.com/en-us/azure/azure-functions/)
1839
+ - [Azure Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/)
1840
+ - [Next.js](https://nextjs.org/)
1841
+ - [Zod](https://zod.dev/)
1842
+
1843
+ ## 💭 Feedback
1844
+
1845
+ This project was generated by SwallowKit. If you encounter any issues or have suggestions for improvements, please open an issue on the [SwallowKit repository](https://github.com/himanago/swallowkit).
1846
+ `;
1847
+
1848
+ fs.writeFileSync(path.join(projectDir, 'README.md'), readme);
1849
+ console.log('✅ README.md created\n');
1850
+ }
1851
+
1852
+ function createAiAgentFiles(projectDir: string, projectName: string, backendLanguage: BackendLanguage, pm: PackageManager) {
1853
+ console.log('🤖 Creating AI agent instruction files...\n');
1854
+ const backendLanguageLabel = getBackendLanguageLabel(backendLanguage);
1855
+ const runCmd = pm === 'pnpm' ? 'pnpm' : 'npx';
1856
+ const projectMcpConfigSource = buildSwallowKitMcpProjectConfigSource();
1857
+ const functionsStructureLine = backendLanguage === 'typescript'
1858
+ ? `│ └── src/ # HTTP trigger handlers with Cosmos DB bindings`
1859
+ : backendLanguage === 'csharp'
1860
+ ? `│ ├── Crud/ # C# HTTP trigger handlers\n│ └── generated/ # Native-generated C# schema assets`
1861
+ : `│ ├── blueprints/ # Python HTTP trigger handlers\n│ └── generated/ # Native-generated Python schema assets`;
1862
+ const backendSchemaNote = backendLanguage === 'typescript'
1863
+ ? `- The shared package (\`@${projectName}/shared\`) is consumed by both Next.js and Azure Functions as a workspace dependency.`
1864
+ : `- The frontend/BFF source of truth stays in \`shared/models/\` as Zod schemas.\n- \`swallowkit scaffold\` exports OpenAPI into \`functions/openapi/\` and generates ${backendLanguageLabel} schema assets into \`functions/generated/\` with native ${backendLanguageLabel} tooling.`;
1865
+ const backendRulesNote = backendLanguage === 'typescript'
1866
+ ? `- All CRUD operations and business logic live in \`functions/src/\`.\n- Use Azure Functions Cosmos DB **input/output bindings** (\`extraInputs\`/\`extraOutputs\`) for reads and writes.\n- Use the Cosmos DB SDK client directly **only** for delete operations (bindings do not support delete).\n- Validate all data against Zod schemas before writing to Cosmos DB.\n- The backend auto-generates \`id\` (UUID), \`createdAt\`, and \`updatedAt\` — never trust client-sent values for these fields.`
1867
+ : `- All business logic lives in \`functions/\` and the generated handlers perform real Cosmos DB CRUD.\n- Keep Zod schemas in \`shared/models/\` as the source of truth.\n- Regenerate backend contracts with \`swallowkit scaffold shared/models/<name>.ts\` whenever a schema changes.\n- Use the native-generated schema assets in \`functions/generated/\` to keep backend contracts aligned.\n- The backend should still own \`id\`, \`createdAt\`, and \`updatedAt\`.`;
1868
+
1869
+ // ── 1. AGENTS.md (Codex / generic agents) ──────────────────────────
1870
+
1871
+ const agentsMd = `# AGENTS.md
1872
+
1873
+ This project was generated by **SwallowKit**.
1874
+ All coding agents **must** follow the architecture and conventions described below.
1875
+
1876
+ ## Architecture Overview
1877
+
1878
+ This is a full-stack application deployed on Azure with a TypeScript frontend/BFF and an Azure Functions backend in ${backendLanguageLabel}.
1879
+
1880
+ \`\`\`
1881
+ Frontend (React / Next.js App Router)
1882
+ ↓ fetch('/api/{model}', ...)
1883
+ BFF Layer (Next.js API Routes)
1884
+ ↓ HTTP → Azure Functions
1885
+ Backend (Azure Functions)
1886
+
1887
+ Azure Cosmos DB (Document Database)
1888
+ \`\`\`
1889
+
1890
+ ### Project Structure
1891
+
1892
+ \`\`\`
1893
+ ${projectName}/
1894
+ ├── app/ # Next.js App Router
1895
+ │ ├── api/ # BFF API routes (proxy to Azure Functions)
1896
+ │ └── {model}/ # UI pages per model (list, detail, create, edit)
1897
+ ├── functions/ # Azure Functions (backend)
1898
+ ${functionsStructureLine}
1899
+ ├── shared/ # Shared workspace package
1900
+ │ ├── models/ # Zod schema definitions (single source of truth)
1901
+ │ └── index.ts # Re-exports all models
1902
+ ├── lib/
1903
+ │ └── api/ # API client utilities (backend.ts, call-function.ts)
1904
+ ├── components/ # Shared React components
1905
+ ├── infra/ # Bicep infrastructure-as-code files
1906
+ │ ├── main.bicep
1907
+ │ └── modules/
1908
+ ├── .mcp.json # Project-scoped MCP bootstrap using local installed SwallowKit
1909
+ └── .github/workflows/ # CI/CD workflows (if configured)
1910
+ \`\`\`
1911
+
1912
+ ## SwallowKit MCP / Machine Workflow
1913
+
1914
+ - This repository includes a project-scoped \`.mcp.json\` file that starts the locally installed SwallowKit MCP server on runtimes that auto-load project MCP configurations.
1915
+ - Prefer the \`swallowkit_*\` MCP tools for framework-owned inspection, validation, and generation when they are available.
1916
+ - If MCP is unavailable in your runtime, fall back to the machine CLI:
1917
+ - \`${runCmd} swallowkit machine inspect project\`
1918
+ - \`${runCmd} swallowkit machine validate project\`
1919
+ - \`${runCmd} swallowkit machine generate scaffold <name> --api-only\`
1920
+ - Do not hand-edit framework-owned artifacts when the MCP or machine interface can generate or validate them for you.
1921
+ - The local MCP bootstrap depends on project dependencies already being installed.
1922
+ - **Always invoke SwallowKit via \`${runCmd}\`.** Do not mix package manager commands.
1923
+
1924
+ ## Critical Design Principles
1925
+
1926
+ ### 1. Next.js API Routes Are Strictly a BFF (Backend for Frontend)
1927
+
1928
+ - \`app/api/\` routes exist **only** to proxy requests to Azure Functions.
1929
+ - **Never** place business logic, database access, or direct Cosmos DB calls in Next.js API routes.
1930
+ - The BFF layer may validate input/output with Zod schemas before forwarding to Functions.
1931
+ - Use the \`callFunction\` helper (\`lib/api/call-function.ts\`) or the \`api\` client (\`lib/api/backend.ts\`) to call Azure Functions.
1932
+
1933
+ Example BFF route pattern:
1934
+
1935
+ \`\`\`typescript
1936
+ // app/api/{model}/route.ts
1937
+ import { callFunction } from '@/lib/api/call-function';
1938
+ import { ModelSchema } from '@${projectName}/shared';
1939
+ import { z } from 'zod/v4';
1940
+
1941
+ export async function GET() {
1942
+ return callFunction({
1943
+ method: 'GET',
1944
+ path: '/api/{model}',
1945
+ responseSchema: z.array(ModelSchema),
1946
+ });
1947
+ }
1948
+
1949
+ export async function POST(request: NextRequest) {
1950
+ const body = await request.json();
1951
+ return callFunction({
1952
+ method: 'POST',
1953
+ path: '/api/{model}',
1954
+ body,
1955
+ inputSchema: ModelSchema.omit({ id: true, createdAt: true, updatedAt: true }),
1956
+ responseSchema: ModelSchema,
1957
+ successStatus: 201,
1958
+ });
1959
+ }
1960
+ \`\`\`
1961
+
1962
+ ### 2. Zod Schemas Are the Single Source of Truth
1963
+
1964
+ - All data models are defined **once** as Zod schemas in \`shared/models/\`.
1965
+ - TypeScript types are derived with \`z.infer<typeof Schema>\` — never define types separately.
1966
+ - ${backendSchemaNote}
1967
+
1968
+ Model definition pattern:
1969
+
1970
+ \`\`\`typescript
1971
+ // shared/models/{model}.ts
1972
+ import { z } from 'zod/v4';
1973
+
1974
+ export const Todo = z.object({
1975
+ id: z.string(),
1976
+ name: z.string().min(1),
1977
+ // ... your fields
1978
+ createdAt: z.string().optional(),
1979
+ updatedAt: z.string().optional(),
1980
+ });
1981
+
1982
+ export type Todo = z.infer<typeof Todo>;
1983
+ export const displayName = 'Todo';
1984
+ \`\`\`
1985
+
1986
+ Key rules:
1987
+ - Use the **Zod official pattern**: the schema constant and the TypeScript type share the same name.
1988
+ - \`id\`, \`createdAt\`, and \`updatedAt\` are auto-managed by the backend. Mark them as \`optional()\` in the schema.
1989
+ - Always re-export models from \`shared/index.ts\`.
1990
+
1991
+ ### 3. Azure Functions Own All Business Logic and Data Access
1992
+
1993
+ - ${backendRulesNote}
1994
+
1995
+ ${backendLanguage === 'typescript' ? 'Azure Functions handler pattern:' : `Generated ${backendLanguageLabel} handlers live under \`functions/\`. Re-run \`swallowkit scaffold shared/models/<name>.ts\` after schema changes to keep generated CRUD handlers and the native schema assets under \`functions/generated/\` in sync.`}
1996
+
1997
+ ${backendLanguage === 'typescript' ? `\`\`\`typescript
1998
+ // functions/src/{model}.ts
1999
+ import { app } from '@azure/functions';
2000
+ import { ModelSchema } from '@${projectName}/shared';
2001
+
2002
+ const containerName = 'Models'; // PascalCase + 's'
2003
+
2004
+ app.http('{model}-get-all', {
2005
+ methods: ['GET'],
2006
+ route: '{model}',
2007
+ authLevel: 'anonymous',
2008
+ extraInputs: [{ type: 'cosmosDB', name: 'cosmosInput', containerName, ... }],
2009
+ handler: async (request, context) => {
2010
+ const documents = context.extraInputs.get('cosmosInput');
2011
+ const validated = z.array(ModelSchema).parse(documents);
2012
+ return { status: 200, jsonBody: validated };
2013
+ },
2014
+ });
2015
+ \`\`\`` : ''}
2016
+
2017
+ ## Naming Conventions
2018
+
2019
+ | Item | Convention | Example |
2020
+ |------|-----------|---------|
2021
+ | Model schema file | \`shared/models/{kebab-case}.ts\` | \`shared/models/todo.ts\` |
2022
+ | Schema/type name | PascalCase (same name for both) | \`export const Todo = z.object({...}); export type Todo = z.infer<typeof Todo>;\` |
2023
+ | Functions handler file | backend-language specific under \`functions/\` | \`${backendLanguage === 'typescript' ? 'functions/src/todo.ts' : backendLanguage === 'csharp' ? 'functions/Crud/TodoCrudFunctions.cs' : 'functions/blueprints/todo.py'}\` |
2024
+ | Functions handler name | \`{camelCase}-{operation}\` | \`todo-get-all\`, \`todo-create\` |
2025
+ | API route path | \`/api/{camelCase}\` | \`/api/todo\`, \`/api/todo/{id}\` |
2026
+ | BFF route file | \`app/api/{kebab-case}/route.ts\` | \`app/api/todo/route.ts\` |
2027
+ | BFF detail route | \`app/api/{kebab-case}/[id]/route.ts\` | \`app/api/todo/[id]/route.ts\` |
2028
+ | UI page directory | \`app/{kebab-case}/\` | \`app/todo/page.tsx\` |
2029
+ | React component | PascalCase | \`TodoForm.tsx\` |
2030
+ | Cosmos DB container | PascalCase + 's' | \`Todos\` |
2031
+ | Cosmos DB partition key | \`/id\` (default) | Custom: \`export const partitionKey = '/field'\` |
2032
+ | Bicep container file | \`infra/containers/{kebab-case}-container.bicep\` | \`infra/containers/todo-container.bicep\` |
2033
+
2034
+ ## Adding New Models (SwallowKit CLI Skills)
2035
+
2036
+ Use the SwallowKit CLI — do **not** manually create model files or CRUD boilerplate.
2037
+
2038
+ ### Skill: Create a new data model
2039
+
2040
+ \`\`\`bash
2041
+ ${runCmd} swallowkit create-model <name>
2042
+ # Multiple models at once:
2043
+ ${runCmd} swallowkit create-model user post comment
2044
+ \`\`\`
2045
+
2046
+ Creates \`shared/models/<name>.ts\` with a Zod schema template including \`id\`, \`createdAt\`, \`updatedAt\`.
2047
+ Edit the generated file to add your domain-specific fields, then run scaffold.
2048
+
2049
+ ### Skill: Generate full CRUD from a model
2050
+
2051
+ \`\`\`bash
2052
+ ${runCmd} swallowkit scaffold shared/models/<name>.ts
2053
+ \`\`\`
2054
+
2055
+ Generates:
2056
+ - Azure Functions handlers (${backendLanguage === 'typescript' ? '`functions/src/<name>.ts`' : '`functions/` language-specific CRUD files + `functions/generated/` schema assets'})
2057
+ - BFF API routes (\`app/api/<name>/route.ts\`, \`app/api/<name>/[id]/route.ts\`)
2058
+ - UI pages (\`app/<name>/page.tsx\`, detail, create, edit pages)
2059
+ - Cosmos DB Bicep container config (\`infra/containers/<name>-container.bicep\`)
2060
+
2061
+ ### Skill: Start development servers
2062
+
2063
+ \`\`\`bash
2064
+ ${runCmd} swallowkit dev
2065
+ \`\`\`
2066
+
2067
+ Runs Next.js (http://localhost:3000) and Azure Functions (http://localhost:7071) concurrently.
2068
+ Checks for Cosmos DB Emulator availability.
2069
+
2070
+ ### Skill: Provision Azure resources
2071
+
2072
+ \`\`\`bash
2073
+ ${runCmd} swallowkit provision --resource-group <name> --location <region>
2074
+ \`\`\`
2075
+
2076
+ Deploys Bicep infrastructure: Static Web Apps, Functions, Cosmos DB, Storage, Managed Identity.
2077
+
2078
+ ### Typical workflow for "add a new feature/model"
2079
+
2080
+ 1. \`${runCmd} swallowkit create-model <name>\`
2081
+ 2. Edit \`shared/models/<name>.ts\` — add fields
2082
+ 3. \`${runCmd} swallowkit scaffold shared/models/<name>.ts\`
2083
+ 4. \`${runCmd} swallowkit dev\` — verify at http://localhost:3000/<name>
2084
+ 5. If \`dev-seeds/\` already exists, update the seed JSON files to include realistic data for the new model and adjust existing seeds if relationships changed.
2085
+
2086
+ ## Do NOT
2087
+
2088
+ - **Do not** put business logic or database calls in \`app/api/\` routes. They are BFF only.
2089
+ - **Do not** define TypeScript interfaces/types separately from Zod schemas. Always derive types with \`z.infer<>\`.
2090
+ - **Do not** manually duplicate model definitions across layers. Use the shared package.
2091
+ - **Do not** manually create CRUD boilerplate. Use \`swallowkit scaffold\`.
2092
+ - **Do not** hardcode Cosmos DB connection strings. Use Managed Identity (\`CosmosDBConnection__accountEndpoint\`) in production and emulator settings locally.
2093
+ - By default, all containers use \`/id\` as the partition key. To use a custom partition key, add \`export const partitionKey = '/yourField'\` to the model file. The scaffold command will apply it across all layers.
2094
+
2095
+ ## Technology Stack
2096
+
2097
+ - **Frontend**: Next.js (App Router), React, TypeScript, Tailwind CSS
2098
+ - **BFF**: Next.js API Routes (proxy only)
2099
+ - **Backend**: Azure Functions (${backendLanguageLabel})
2100
+ - **Database**: Azure Cosmos DB (NoSQL)
2101
+ - **Schema**: Zod (shared across all layers via workspace package)
2102
+ - **Infrastructure**: Bicep (IaC)
2103
+ - **Hosting**: Azure Static Web Apps (frontend) + Azure Functions Flex Consumption (backend)
2104
+ - **Auth**: Azure Managed Identity (no connection strings in production)
2105
+ - **Monitoring**: Application Insights
2106
+ `;
2107
+
2108
+ fs.writeFileSync(path.join(projectDir, 'AGENTS.md'), agentsMd);
2109
+ console.log(' ✅ AGENTS.md (Codex / generic agents)');
2110
+
2111
+ // ── 2. CLAUDE.md (Claude Code) ─────────────────────────────────────
2112
+
2113
+ const claudeMd = `# CLAUDE.md
2114
+
2115
+ This file is for Claude Code. Read AGENTS.md in the project root for the full architecture, conventions, and rules.
2116
+
2117
+ ## Quick Reference
2118
+
2119
+ - **Architecture**: Next.js (frontend) → BFF (API routes, proxy only) → Azure Functions (backend) → Cosmos DB
2120
+ - **Schema**: Zod schemas in \`shared/models/\` are the single source of truth. Never define types separately.
2121
+ - **BFF rule**: \`app/api/\` routes must ONLY proxy to Azure Functions via \`callFunction()\`. No business logic.
2122
+ - **Backend language**: ${backendLanguageLabel}
2123
+ - **Backend rule**: Regenerate backend contracts with \`swallowkit scaffold\` after schema changes and keep \`functions/generated/\` in sync.
2124
+
2125
+ ## SwallowKit MCP
2126
+
2127
+ - This repository includes a project-scoped \`.mcp.json\` that registers the locally installed SwallowKit MCP server for runtimes that support project MCP files.
2128
+ - When the \`swallowkit_*\` tools are available, prefer them for inspect / validate / generate tasks.
2129
+ - If MCP is unavailable, use \`${runCmd} swallowkit machine ...\` instead.
2130
+ - **Always invoke SwallowKit via \`${runCmd}\`.** Do not mix package manager commands.
2131
+
2132
+ ## SwallowKit CLI Commands
2133
+
2134
+ | Task | Command |
2135
+ |------|---------|
2136
+ | Create model | \`${runCmd} swallowkit create-model <name>\` |
2137
+ | Generate CRUD | \`${runCmd} swallowkit scaffold shared/models/<name>.ts\` |
2138
+ | Dev servers | \`${runCmd} swallowkit dev\` |
2139
+ | Provision Azure | \`${runCmd} swallowkit provision --resource-group <rg> --location <region>\` |
2140
+
2141
+ ## Workflow: Add a new model
2142
+
2143
+ 1. \`${runCmd} swallowkit create-model <name>\`
2144
+ 2. Edit \`shared/models/<name>.ts\` — add your fields
2145
+ 3. \`${runCmd} swallowkit scaffold shared/models/<name>.ts\`
2146
+ 4. \`${runCmd} swallowkit dev\` — verify at http://localhost:3000/<name>
2147
+ 5. If \`dev-seeds/\` exists, update the seed JSON files to include data for the new model and adjust existing seeds if relationships changed.
2148
+ `;
2149
+
2150
+ fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), claudeMd);
2151
+ console.log(' ✅ CLAUDE.md (Claude Code)');
2152
+
2153
+ fs.writeFileSync(path.join(projectDir, '.mcp.json'), projectMcpConfigSource);
2154
+ console.log(' ✅ .mcp.json (project-scoped MCP bootstrap)');
2155
+
2156
+ // ── 3. .github/copilot-instructions.md (GitHub Copilot) ────────────
2157
+
2158
+ const ghDir = path.join(projectDir, '.github');
2159
+ fs.mkdirSync(ghDir, { recursive: true });
2160
+
2161
+ const copilotInstructions = `# Copilot Instructions
2162
+
2163
+ This project was generated by **SwallowKit**. See \`AGENTS.md\` in the project root for the full specification.
2164
+
2165
+ ## Architecture (3-layer)
2166
+
2167
+ \`\`\`
2168
+ Frontend (Next.js App Router) → BFF (Next.js API Routes) → Backend (Azure Functions) → Cosmos DB
2169
+ \`\`\`
2170
+
2171
+ ## Key Rules
2172
+
2173
+ 1. **BFF is proxy only** — \`app/api/\` routes call Azure Functions via \`callFunction()\`. No business logic, no direct DB access.
2174
+ 2. **Zod = single source of truth** — Models live in \`shared/models/\`. Types are derived with \`z.infer<>\`. Never define types separately.
2175
+ 3. **Backend owns data** — All CRUD and business logic stay in \`functions/\`, and generated contract assets under \`functions/generated/\` must stay aligned with \`shared/models/\`.
2176
+ 4. **Use the CLI** — Run \`${runCmd} swallowkit create-model <name>\` then \`${runCmd} swallowkit scaffold shared/models/<name>.ts\` to add models. Do not create boilerplate manually.
2177
+ 5. **Maintain seed data** — When adding models or changing schemas, update the JSON files under \`dev-seeds/\` to keep seed data consistent with the current schema.
2178
+
2179
+ ## SwallowKit Framework Operations
2180
+
2181
+ - Prefer the SwallowKit MCP or machine interface for framework-owned inspection, validation, and generation instead of hand-editing generated files.
2182
+ - If your runtime loads project-scoped MCP config from \`.mcp.json\`, use the \`swallowkit_*\` tools.
2183
+ - Otherwise use \`${runCmd} swallowkit machine inspect project\`, \`${runCmd} swallowkit machine validate project\`, and \`${runCmd} swallowkit machine generate scaffold <name> --api-only\`.
2184
+ - **Always invoke SwallowKit via \`${runCmd}\`.** Do not mix package manager commands.
2185
+
2186
+ ## Naming
2187
+
2188
+ - Schema/type: PascalCase, same name for both (\`export const Todo = z.object({...}); export type Todo = z.infer<typeof Todo>;\`)
2189
+ - Files: kebab-case (\`shared/models/todo.ts\`, backend handlers under \`functions/\`)
2190
+ - Cosmos DB containers: PascalCase + 's' (\`Todos\`), partition key default \`/id\` (customizable via \`export const partitionKey\`)
2191
+
2192
+ ## Managed Fields
2193
+
2194
+ \`id\`, \`createdAt\`, \`updatedAt\` are auto-managed by the backend. Define them as \`optional()\` in schemas. Never trust client-sent values.
2195
+ `;
2196
+
2197
+ fs.writeFileSync(path.join(ghDir, 'copilot-instructions.md'), copilotInstructions);
2198
+ console.log(' ✅ .github/copilot-instructions.md (GitHub Copilot)');
2199
+
2200
+ // ── 4. .github/instructions/*.instructions.md (Copilot layer-specific) ──
2201
+
2202
+ const instructionsDir = path.join(ghDir, 'instructions');
2203
+ fs.mkdirSync(instructionsDir, { recursive: true });
2204
+
2205
+ // 4a. shared/models — Zod schema layer
2206
+ const sharedModelsInstructions = `---
2207
+ applyTo: "shared/models/**"
2208
+ ---
2209
+
2210
+ # Shared Models — Zod Schema Rules
2211
+
2212
+ Files in this directory are the **single source of truth** for data models across the entire application.
2213
+
2214
+ ## Rules
2215
+
2216
+ - Define Zod schemas using \`zod/v4\` (\`import { z } from 'zod/v4'\`).
2217
+ - Use the **Zod official pattern**: the schema constant and the TypeScript type share the same name.
2218
+ \`\`\`typescript
2219
+ export const Todo = z.object({ ... });
2220
+ export type Todo = z.infer<typeof Todo>;
2221
+ \`\`\`
2222
+ - Always include \`id: z.string()\`, \`createdAt: z.string().optional()\`, \`updatedAt: z.string().optional()\`. These are managed by the backend.
2223
+ - Export a \`displayName\` string constant for UI display.
2224
+ - Re-export every model from \`shared/index.ts\`.
2225
+ - For relationships, use **nested schemas** (import and embed the related schema), not ID references.
2226
+ - After editing a model, run \`${runCmd} swallowkit scaffold shared/models/<name>.ts\` to regenerate CRUD code.
2227
+ `;
2228
+
2229
+ fs.writeFileSync(
2230
+ path.join(instructionsDir, 'shared-models.instructions.md'),
2231
+ sharedModelsInstructions
2232
+ );
2233
+
2234
+ // 4b. app/api — BFF layer
2235
+ const bffInstructions = `---
2236
+ applyTo: "app/api/**"
2237
+ ---
2238
+
2239
+ # BFF API Routes — Rules
2240
+
2241
+ Files in \`app/api/\` are the **BFF (Backend for Frontend)** layer. They exist solely to proxy requests to Azure Functions.
2242
+
2243
+ ## Rules
2244
+
2245
+ - **Never** put business logic, database access, or direct Cosmos DB calls here.
2246
+ - Use \`callFunction()\` from \`@/lib/api/call-function\` to forward requests to Azure Functions.
2247
+ - You may validate input/output with Zod schemas before forwarding.
2248
+ - Import schemas from \`@${projectName}/shared\`.
2249
+
2250
+ ## Pattern
2251
+
2252
+ \`\`\`typescript
2253
+ import { callFunction } from '@/lib/api/call-function';
2254
+ import { ModelSchema } from '@${projectName}/shared';
2255
+ import { z } from 'zod/v4';
2256
+
2257
+ export async function GET() {
2258
+ return callFunction({
2259
+ method: 'GET',
2260
+ path: '/api/{model}',
2261
+ responseSchema: z.array(ModelSchema),
2262
+ });
2263
+ }
2264
+ \`\`\`
2265
+ `;
2266
+
2267
+ fs.writeFileSync(
2268
+ path.join(instructionsDir, 'bff-routes.instructions.md'),
2269
+ bffInstructions
2270
+ );
2271
+
2272
+ // 4c. functions — Azure Functions backend layer
2273
+ const functionsInstructions = `---
2274
+ applyTo: "functions/**"
2275
+ ---
2276
+
2277
+ # Azure Functions — Backend Rules
2278
+
2279
+ Files in \`functions/\` contain all business logic and data access for this application.
2280
+
2281
+ ## Rules
2282
+
2283
+ - Keep backend contracts aligned with \`shared/models/\` by rerunning \`swallowkit scaffold\` after schema changes.
2284
+ - For TypeScript backends, use Cosmos DB **input/output bindings** (\`extraInputs\`/\`extraOutputs\`) for reads and writes.
2285
+ - For C#/Python backends, consume the native-generated assets in \`functions/generated/\`.
2286
+ - Auto-generate \`id\` (UUID), \`createdAt\`, and \`updatedAt\` on the backend. Never trust client-sent values.
2287
+ - Container names are PascalCase + 's' (e.g., \`Todos\`). Partition key defaults to \`/id\` but can be customized per model.
2288
+
2289
+ ## Handler Pattern
2290
+
2291
+ \`\`\`typescript
2292
+ import { app } from '@azure/functions';
2293
+ import { ModelSchema } from '@${projectName}/shared';
2294
+
2295
+ app.http('{model}-get-all', {
2296
+ methods: ['GET'],
2297
+ route: '{model}',
2298
+ authLevel: 'anonymous',
2299
+ extraInputs: [cosmosInput],
2300
+ handler: async (request, context) => {
2301
+ const documents = context.extraInputs.get(cosmosInput);
2302
+ const validated = z.array(ModelSchema).parse(documents);
2303
+ return { status: 200, jsonBody: validated };
2304
+ },
2305
+ });
2306
+ \`\`\`
2307
+ `;
2308
+
2309
+ fs.writeFileSync(
2310
+ path.join(instructionsDir, 'azure-functions.instructions.md'),
2311
+ functionsInstructions
2312
+ );
2313
+
2314
+ console.log(' ✅ .github/instructions/ (Copilot layer-specific instructions)');
2315
+ console.log(' - shared-models.instructions.md');
2316
+ console.log(' - bff-routes.instructions.md');
2317
+ console.log(' - azure-functions.instructions.md');
2318
+
2319
+ console.log('\n✅ AI agent files created\n');
2320
+ console.log(' Supported agents:');
2321
+ console.log(' - OpenAI Codex → AGENTS.md');
2322
+ console.log(' - Claude Code → CLAUDE.md (+ AGENTS.md)');
2323
+ console.log(' - Project MCP runtimes → .mcp.json');
2324
+ console.log(' - GitHub Copilot → .github/copilot-instructions.md');
2325
+ console.log(' - GitHub Copilot (edit) → .github/instructions/*.instructions.md');
2326
+ console.log('');
2327
+ }
2328
+
2329
+ async function createInfrastructure(
2330
+ projectDir: string,
2331
+ projectName: string,
2332
+ azureConfig: AzureConfig,
2333
+ backendLanguage: BackendLanguage
2334
+ ) {
2335
+ console.log('📦 Creating infrastructure files (Bicep)...\n');
2336
+
2337
+ const infraDir = path.join(projectDir, 'infra');
2338
+ const modulesDir = path.join(infraDir, 'modules');
2339
+ fs.mkdirSync(modulesDir, { recursive: true });
2340
+
2341
+ const enableVNet = azureConfig.vnetOption !== 'none';
2342
+ const functionsRuntime = getFunctionsRuntimeConfig(backendLanguage);
2343
+
2344
+ // main.bicep
2345
+ const mainBicep = `targetScope = 'resourceGroup'
2346
+
2347
+ @description('Project name')
2348
+ param projectName string
2349
+
2350
+ @description('Location for Functions and Cosmos DB')
2351
+ param location string = resourceGroup().location
2352
+
2353
+ @description('Location for Static Web App (must be explicitly provided)')
2354
+ param swaLocation string
2355
+
2356
+ @description('Cosmos DB mode')
2357
+ @allowed(['freetier', 'serverless'])
2358
+ param cosmosDbMode string = '${azureConfig.cosmosDbMode}'
2359
+
2360
+ @description('Enable VNet integration')
2361
+ param enableVNet bool = ${enableVNet}
2362
+
2363
+ // Shared Log Analytics Workspace (in Functions region for data residency)
2364
+ module logAnalytics 'modules/loganalytics.bicep' = {
2365
+ name: 'logAnalytics'
2366
+ params: {
2367
+ name: 'log-\${projectName}'
2368
+ location: location
2369
+ }
2370
+ }
2371
+
2372
+ // Application Insights for Static Web App (must be in same region as SWA)
2373
+ module appInsightsSwa 'modules/appinsights.bicep' = {
2374
+ name: 'appInsightsSwa'
2375
+ params: {
2376
+ name: 'appi-\${projectName}-swa'
2377
+ location: swaLocation
2378
+ logAnalyticsWorkspaceId: logAnalytics.outputs.id
2379
+ }
2380
+ }
2381
+
2382
+ // Application Insights for Functions (in same region as Functions)
2383
+ module appInsightsFunctions 'modules/appinsights.bicep' = {
2384
+ name: 'appInsightsFunctions'
2385
+ params: {
2386
+ name: 'appi-\${projectName}-func'
2387
+ location: location
2388
+ logAnalyticsWorkspaceId: logAnalytics.outputs.id
2389
+ }
2390
+ }
2391
+
2392
+ // Static Web App
2393
+ module staticWebApp 'modules/staticwebapp.bicep' = {
2394
+ name: 'staticWebApp'
2395
+ params: {
2396
+ name: 'swa-\${projectName}'
2397
+ location: swaLocation
2398
+ sku: 'Standard'
2399
+ appInsightsConnectionString: appInsightsSwa.outputs.connectionString
2400
+ }
2401
+ }
2402
+
2403
+ // VNet (conditional)
2404
+ module vnet 'modules/vnet.bicep' = if (enableVNet) {
2405
+ name: 'vnet'
2406
+ params: {
2407
+ name: 'vnet-\${projectName}'
2408
+ location: location
2409
+ }
2410
+ }
2411
+
2412
+ // Cosmos DB (conditional based on mode) - Deploy BEFORE Functions
2413
+ module cosmosDbFreeTier 'modules/cosmosdb-freetier.bicep' = if (cosmosDbMode == 'freetier') {
2414
+ name: 'cosmosDb'
2415
+ params: {
2416
+ accountName: 'cosmos-\${projectName}'
2417
+ databaseName: '\${projectName}Database'
2418
+ location: location
2419
+ publicNetworkAccess: enableVNet ? 'Disabled' : 'Enabled'
2420
+ }
2421
+ }
2422
+
2423
+ module cosmosDbServerless 'modules/cosmosdb-serverless.bicep' = if (cosmosDbMode == 'serverless') {
2424
+ name: 'cosmosDb'
2425
+ params: {
2426
+ accountName: 'cosmos-\${projectName}'
2427
+ databaseName: '\${projectName}Database'
2428
+ location: location
2429
+ publicNetworkAccess: enableVNet ? 'Disabled' : 'Enabled'
2430
+ }
2431
+ }
2432
+
2433
+ // Cosmos DB Private Endpoint (conditional)
2434
+ module cosmosPrivateEndpoint 'modules/private-endpoint-cosmos.bicep' = if (enableVNet) {
2435
+ name: 'cosmosPrivateEndpoint'
2436
+ params: {
2437
+ name: 'pe-cosmos-\${projectName}'
2438
+ location: location
2439
+ cosmosAccountId: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.id : cosmosDbServerless.outputs.id
2440
+ cosmosAccountName: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.accountName : cosmosDbServerless.outputs.accountName
2441
+ subnetId: vnet.outputs.privateEndpointSubnetId
2442
+ vnetId: vnet.outputs.id
2443
+ }
2444
+ dependsOn: [
2445
+ cosmosDbFreeTier
2446
+ cosmosDbServerless
2447
+ vnet
2448
+ ]
2449
+ }
2450
+
2451
+ // Azure Functions (Flex Consumption) - Deploy AFTER Cosmos DB
2452
+ module functionsFlex 'modules/functions-flex.bicep' = {
2453
+ name: 'functionsApp'
2454
+ params: {
2455
+ name: 'func-\${projectName}'
2456
+ location: location
2457
+ storageAccountName: 'stg\${uniqueString(resourceGroup().id, projectName)}'
2458
+ appInsightsConnectionString: appInsightsFunctions.outputs.connectionString
2459
+ swaDefaultHostname: staticWebApp.outputs.defaultHostname
2460
+ cosmosDbEndpoint: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.endpoint : cosmosDbServerless.outputs.endpoint
2461
+ cosmosDbDatabaseName: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.databaseName : cosmosDbServerless.outputs.databaseName
2462
+ functionsRuntimeName: '${functionsRuntime.name}'
2463
+ functionsRuntimeVersion: '${functionsRuntime.version}'
2464
+ enableVNet: enableVNet
2465
+ vnetSubnetId: enableVNet ? vnet.outputs.functionsSubnetId : ''
2466
+ }
2467
+ dependsOn: [
2468
+ cosmosDbFreeTier
2469
+ cosmosDbServerless
2470
+ cosmosPrivateEndpoint
2471
+ ]
2472
+ }
2473
+
2474
+ // Cosmos DB role assignment for Functions (after Functions is created)
2475
+ module cosmosDbRoleAssignmentFreeTier 'modules/cosmosdb-role-assignment.bicep' = if (cosmosDbMode == 'freetier') {
2476
+ name: 'cosmosDbRoleAssignment'
2477
+ params: {
2478
+ cosmosAccountName: cosmosDbFreeTier.outputs.accountName
2479
+ functionsPrincipalId: functionsFlex.outputs.principalId
2480
+ }
2481
+ dependsOn: [
2482
+ functionsFlex
2483
+ ]
2484
+ }
2485
+
2486
+ module cosmosDbRoleAssignmentServerless 'modules/cosmosdb-role-assignment.bicep' = if (cosmosDbMode == 'serverless') {
2487
+ name: 'cosmosDbRoleAssignment'
2488
+ params: {
2489
+ cosmosAccountName: cosmosDbServerless.outputs.accountName
2490
+ functionsPrincipalId: functionsFlex.outputs.principalId
2491
+ }
2492
+ dependsOn: [
2493
+ functionsFlex
2494
+ ]
2495
+ }
2496
+
2497
+ // Update SWA config with Functions hostname (after Functions deployment)
2498
+ module staticWebAppConfig 'modules/staticwebapp-config.bicep' = {
2499
+ name: 'staticWebAppConfig'
2500
+ params: {
2501
+ staticWebAppName: staticWebApp.outputs.name
2502
+ functionsDefaultHostname: functionsFlex.outputs.defaultHostname
2503
+ appInsightsConnectionString: appInsightsSwa.outputs.connectionString
2504
+ }
2505
+ dependsOn: [
2506
+ functionsFlex
2507
+ ]
2508
+ }
2509
+
2510
+ output staticWebAppName string = staticWebApp.outputs.name
2511
+ output staticWebAppUrl string = staticWebApp.outputs.defaultHostname
2512
+ output functionsAppName string = functionsFlex.outputs.name
2513
+ output functionsAppUrl string = functionsFlex.outputs.defaultHostname
2514
+ output cosmosDbAccountName string = cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.accountName : cosmosDbServerless.outputs.accountName
2515
+ output cosmosDbEndpoint string = cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.endpoint : cosmosDbServerless.outputs.endpoint
2516
+ output cosmosDatabaseName string = cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.databaseName : cosmosDbServerless.outputs.databaseName
2517
+ output logAnalyticsWorkspaceName string = logAnalytics.outputs.name
2518
+ output logAnalyticsWorkspaceId string = logAnalytics.outputs.id
2519
+ output appInsightsSwaName string = appInsightsSwa.outputs.name
2520
+ output appInsightsSwaConnectionString string = appInsightsSwa.outputs.connectionString
2521
+ output appInsightsFunctionsName string = appInsightsFunctions.outputs.name
2522
+ output appInsightsFunctionsConnectionString string = appInsightsFunctions.outputs.connectionString
2523
+ output vnetEnabled bool = enableVNet
2524
+ output vnetName string = enableVNet ? vnet.outputs.name : ''
2525
+ `;
2526
+
2527
+ fs.writeFileSync(path.join(infraDir, 'main.bicep'), mainBicep);
2528
+
2529
+ // main.parameters.json
2530
+ const params = `{
2531
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
2532
+ "contentVersion": "1.0.0.0",
2533
+ "parameters": {
2534
+ "projectName": {
2535
+ "value": "${projectName}"
2536
+ },
2537
+ "cosmosDbMode": {
2538
+ "value": "${azureConfig.cosmosDbMode}"
2539
+ },
2540
+ "enableVNet": {
2541
+ "value": ${enableVNet}
2542
+ }
2543
+ }
2544
+ }
2545
+ `;
2546
+ fs.writeFileSync(path.join(infraDir, 'main.parameters.json'), params);
2547
+
2548
+ // modules/staticwebapp.bicep
2549
+ const staticWebAppBicep = `@description('Static Web App name')
2550
+ param name string
2551
+
2552
+ @description('Location for the Static Web App')
2553
+ param location string
2554
+
2555
+ @description('SKU name (Free or Standard)')
2556
+ @allowed([
2557
+ 'Free'
2558
+ 'Standard'
2559
+ ])
2560
+ param sku string = 'Standard'
2561
+
2562
+ @description('Application Insights connection string')
2563
+ param appInsightsConnectionString string
2564
+
2565
+ resource staticWebApp 'Microsoft.Web/staticSites@2023-01-01' = {
2566
+ name: name
2567
+ location: location
2568
+ sku: {
2569
+ name: sku
2570
+ tier: sku
2571
+ }
2572
+ properties: {
2573
+ buildProperties: {
2574
+ skipGithubActionWorkflowGeneration: true
2575
+ }
2576
+ }
2577
+ }
2578
+
2579
+ // Link Application Insights to Static Web App (for both client and server-side telemetry)
2580
+ resource staticWebAppConfig 'Microsoft.Web/staticSites/config@2023-01-01' = {
2581
+ parent: staticWebApp
2582
+ name: 'appsettings'
2583
+ properties: {
2584
+ APPLICATIONINSIGHTS_CONNECTION_STRING: appInsightsConnectionString
2585
+ ApplicationInsightsAgent_EXTENSION_VERSION: '~3'
2586
+ }
2587
+ }
2588
+
2589
+ output id string = staticWebApp.id
2590
+ output name string = staticWebApp.name
2591
+ output defaultHostname string = staticWebApp.properties.defaultHostname
2592
+ `;
2593
+ fs.writeFileSync(path.join(modulesDir, 'staticwebapp.bicep'), staticWebAppBicep);
2594
+
2595
+ // modules/staticwebapp-config.bicep (for updating config after Functions deployment)
2596
+ const staticWebAppConfigBicep = `@description('Static Web App name')
2597
+ param staticWebAppName string
2598
+
2599
+ @description('Functions App default hostname for backend API calls')
2600
+ param functionsDefaultHostname string
2601
+
2602
+ @description('Application Insights connection string for SWA')
2603
+ param appInsightsConnectionString string
2604
+
2605
+ resource staticWebApp 'Microsoft.Web/staticSites@2023-01-01' existing = {
2606
+ name: staticWebAppName
2607
+ }
2608
+
2609
+ resource staticWebAppConfig 'Microsoft.Web/staticSites/config@2023-01-01' = {
2610
+ parent: staticWebApp
2611
+ name: 'appsettings'
2612
+ properties: {
2613
+ APPLICATIONINSIGHTS_CONNECTION_STRING: appInsightsConnectionString
2614
+ ApplicationInsightsAgent_EXTENSION_VERSION: '~3'
2615
+ BACKEND_FUNCTIONS_BASE_URL: 'https://\${functionsDefaultHostname}'
2616
+ }
2617
+ }
2618
+
2619
+ output configName string = staticWebAppConfig.name
2620
+ `;
2621
+ fs.writeFileSync(path.join(modulesDir, 'staticwebapp-config.bicep'), staticWebAppConfigBicep);
2622
+
2623
+ // modules/loganalytics.bicep (Shared Log Analytics Workspace)
2624
+ const logAnalyticsBicep = `@description('Log Analytics workspace name')
2625
+ param name string
2626
+
2627
+ @description('Location for Log Analytics workspace')
2628
+ param location string
2629
+
2630
+ resource logAnalytics 'Microsoft.OperationalInsights/workspaces@2023-09-01' = {
2631
+ name: name
2632
+ location: location
2633
+ properties: {
2634
+ sku: {
2635
+ name: 'PerGB2018'
2636
+ }
2637
+ retentionInDays: 30
2638
+ }
2639
+ }
2640
+
2641
+ output id string = logAnalytics.id
2642
+ output name string = logAnalytics.name
2643
+ `;
2644
+ fs.writeFileSync(path.join(modulesDir, 'loganalytics.bicep'), logAnalyticsBicep);
2645
+
2646
+ // modules/appinsights.bicep (Application Insights only, connects to shared Log Analytics)
2647
+ const appInsightsBicep = `@description('Application Insights name')
2648
+ param name string
2649
+
2650
+ @description('Location for Application Insights')
2651
+ param location string
2652
+
2653
+ @description('Log Analytics workspace resource ID')
2654
+ param logAnalyticsWorkspaceId string
2655
+
2656
+ // Application Insights
2657
+ resource appInsights 'Microsoft.Insights/components@2020-02-02' = {
2658
+ name: name
2659
+ location: location
2660
+ kind: 'web'
2661
+ properties: {
2662
+ Application_Type: 'web'
2663
+ WorkspaceResourceId: logAnalyticsWorkspaceId
2664
+ RetentionInDays: 30
2665
+ }
2666
+ }
2667
+
2668
+ output id string = appInsights.id
2669
+ output name string = appInsights.name
2670
+ output connectionString string = appInsights.properties.ConnectionString
2671
+ output instrumentationKey string = appInsights.properties.InstrumentationKey
2672
+ `;
2673
+ fs.writeFileSync(path.join(modulesDir, 'appinsights.bicep'), appInsightsBicep);
2674
+
2675
+ // modules/functions-flex.bicep (Flex Consumption)
2676
+ const functionsFlexBicep = `@description('Functions App name')
2677
+ param name string
2678
+
2679
+ @description('Location for the Functions App')
2680
+ param location string
2681
+
2682
+ @description('Storage account name for Functions')
2683
+ param storageAccountName string
2684
+
2685
+ @description('Application Insights connection string')
2686
+ param appInsightsConnectionString string
2687
+
2688
+ @description('Static Web App default hostname for CORS')
2689
+ param swaDefaultHostname string
2690
+
2691
+ @description('Cosmos DB endpoint')
2692
+ param cosmosDbEndpoint string
2693
+
2694
+ @description('Cosmos DB database name')
2695
+ param cosmosDbDatabaseName string
2696
+
2697
+ @description('Enable VNet integration')
2698
+ param enableVNet bool = false
2699
+
2700
+ @description('VNet subnet ID for Functions (required if enableVNet is true)')
2701
+ param vnetSubnetId string = ''
2702
+
2703
+ @description('Functions runtime name')
2704
+ param functionsRuntimeName string
2705
+
2706
+ @description('Functions runtime version')
2707
+ param functionsRuntimeVersion string
2708
+
2709
+ // Storage Account for Functions
2710
+ resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
2711
+ name: storageAccountName
2712
+ location: location
2713
+ sku: {
2714
+ name: 'Standard_LRS'
2715
+ }
2716
+ kind: 'StorageV2'
2717
+ properties: {
2718
+ supportsHttpsTrafficOnly: true
2719
+ minimumTlsVersion: 'TLS1_2'
2720
+ }
2721
+ }
2722
+
2723
+ // Blob Service for deployment package container
2724
+ resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01' = {
2725
+ parent: storageAccount
2726
+ name: 'default'
2727
+ }
2728
+
2729
+ // Deployment package container
2730
+ resource deploymentContainer 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = {
2731
+ parent: blobService
2732
+ name: 'deploymentpackage'
2733
+ properties: {
2734
+ publicAccess: 'None'
2735
+ }
2736
+ }
2737
+
2738
+ // App Service Plan (Flex Consumption)
2739
+ resource hostingPlan 'Microsoft.Web/serverfarms@2023-12-01' = {
2740
+ name: '\${name}-plan'
2741
+ location: location
2742
+ sku: {
2743
+ name: 'FC1'
2744
+ tier: 'FlexConsumption'
2745
+ }
2746
+ properties: {
2747
+ reserved: true // Required for Linux
2748
+ }
2749
+ }
2750
+
2751
+ // Azure Functions App
2752
+ resource functionApp 'Microsoft.Web/sites@2023-12-01' = {
2753
+ name: name
2754
+ location: location
2755
+ kind: 'functionapp,linux'
2756
+ identity: {
2757
+ type: 'SystemAssigned'
2758
+ }
2759
+ properties: {
2760
+ serverFarmId: hostingPlan.id
2761
+ reserved: true
2762
+ virtualNetworkSubnetId: enableVNet ? vnetSubnetId : null
2763
+ vnetContentShareEnabled: enableVNet
2764
+ functionAppConfig: {
2765
+ deployment: {
2766
+ storage: {
2767
+ type: 'blobContainer'
2768
+ value: '\${storageAccount.properties.primaryEndpoints.blob}deploymentpackage'
2769
+ authentication: {
2770
+ type: 'SystemAssignedIdentity'
2771
+ }
2772
+ }
2773
+ }
2774
+ scaleAndConcurrency: {
2775
+ maximumInstanceCount: 100
2776
+ instanceMemoryMB: 2048
2777
+ }
2778
+ runtime: {
2779
+ name: functionsRuntimeName
2780
+ version: functionsRuntimeVersion
2781
+ }
2782
+ }
2783
+ siteConfig: {
2784
+ appSettings: [
2785
+ {
2786
+ name: 'AzureWebJobsStorage__accountName'
2787
+ value: storageAccount.name
2788
+ }
2789
+ {
2790
+ name: 'FUNCTIONS_EXTENSION_VERSION'
2791
+ value: '~4'
2792
+ }
2793
+ {
2794
+ name: 'APPLICATIONINSIGHTS_CONNECTION_STRING'
2795
+ value: appInsightsConnectionString
2796
+ }
2797
+ {
2798
+ name: 'CosmosDBConnection__accountEndpoint'
2799
+ value: cosmosDbEndpoint
2800
+ }
2801
+ {
2802
+ name: 'COSMOS_DB_DATABASE_NAME'
2803
+ value: cosmosDbDatabaseName
2804
+ }
2805
+ ]
2806
+ cors: {
2807
+ allowedOrigins: [
2808
+ 'https://\${swaDefaultHostname}'
2809
+ ]
2810
+ }
2811
+ ipSecurityRestrictions: [
2812
+ {
2813
+ action: 'Allow'
2814
+ ipAddress: 'AzureCloud'
2815
+ tag: 'ServiceTag'
2816
+ priority: 100
2817
+ }
2818
+ ]
2819
+ }
2820
+ httpsOnly: true
2821
+ }
2822
+ }
2823
+
2824
+ // Role Assignment: Storage Blob Data Contributor
2825
+ resource blobDataContributorRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
2826
+ name: guid(functionApp.id, storageAccount.id, 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')
2827
+ scope: storageAccount
2828
+ properties: {
2829
+ roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')
2830
+ principalId: functionApp.identity.principalId
2831
+ principalType: 'ServicePrincipal'
2832
+ }
2833
+ }
2834
+
2835
+ output id string = functionApp.id
2836
+ output name string = functionApp.name
2837
+ output defaultHostname string = functionApp.properties.defaultHostName
2838
+ output principalId string = functionApp.identity.principalId
2839
+ `;
2840
+ fs.writeFileSync(path.join(modulesDir, 'functions-flex.bicep'), functionsFlexBicep);
2841
+
2842
+ // modules/cosmosdb-freetier.bicep (Free Tier)
2843
+ const cosmosDbFreeTierBicep = buildCosmosDbFreeTierBicepSource();
2844
+ fs.writeFileSync(path.join(modulesDir, 'cosmosdb-freetier.bicep'), cosmosDbFreeTierBicep);
2845
+
2846
+ // modules/cosmosdb-serverless.bicep (Serverless)
2847
+ const cosmosDbServerlessBicep = `@description('Cosmos DB account name')
2848
+ param accountName string
2849
+
2850
+ @description('Database name')
2851
+ param databaseName string
2852
+
2853
+ @description('Location for Cosmos DB')
2854
+ param location string
2855
+
2856
+ @description('Public network access')
2857
+ @allowed(['Enabled', 'Disabled'])
2858
+ param publicNetworkAccess string = 'Enabled'
2859
+
2860
+ // Cosmos DB Account (Serverless)
2861
+ resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {
2862
+ name: accountName
2863
+ location: location
2864
+ kind: 'GlobalDocumentDB'
2865
+ properties: {
2866
+ databaseAccountOfferType: 'Standard'
2867
+ enableAutomaticFailover: false
2868
+ publicNetworkAccess: publicNetworkAccess
2869
+ disableLocalAuth: true
2870
+ consistencyPolicy: {
2871
+ defaultConsistencyLevel: 'Session'
2872
+ }
2873
+ locations: [
2874
+ {
2875
+ locationName: location
2876
+ failoverPriority: 0
2877
+ isZoneRedundant: false
2878
+ }
2879
+ ]
2880
+ capabilities: [
2881
+ {
2882
+ name: 'EnableServerless'
2883
+ }
2884
+ ]
2885
+ disableKeyBasedMetadataWriteAccess: true
2886
+ }
2887
+ }
2888
+
2889
+ // Cosmos DB Database
2890
+ resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15' = {
2891
+ parent: cosmosAccount
2892
+ name: databaseName
2893
+ properties: {
2894
+ resource: {
2895
+ id: databaseName
2896
+ }
2897
+ }
2898
+ }
2899
+
2900
+ output id string = cosmosAccount.id
2901
+ output accountName string = cosmosAccount.name
2902
+ output endpoint string = cosmosAccount.properties.documentEndpoint
2903
+ output databaseName string = database.name
2904
+ `;
2905
+ fs.writeFileSync(path.join(modulesDir, 'cosmosdb-serverless.bicep'), cosmosDbServerlessBicep);
2906
+
2907
+ // modules/cosmosdb-role-assignment.bicep (Role Assignment Module)
2908
+ const cosmosDbRoleAssignmentBicep = `@description('Cosmos DB account name')
2909
+ param cosmosAccountName string
2910
+
2911
+ @description('Functions App Managed Identity Principal ID')
2912
+ param functionsPrincipalId string
2913
+
2914
+ resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' existing = {
2915
+ name: cosmosAccountName
2916
+ }
2917
+
2918
+ // Built-in Cosmos DB Data Contributor role definition
2919
+ var cosmosDbDataContributorRoleId = '00000000-0000-0000-0000-000000000002'
2920
+
2921
+ // Role assignment for Functions to access Cosmos DB
2922
+ resource roleAssignment 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2023-11-15' = {
2923
+ parent: cosmosAccount
2924
+ name: guid(cosmosAccount.id, functionsPrincipalId, cosmosDbDataContributorRoleId)
2925
+ properties: {
2926
+ roleDefinitionId: '\${cosmosAccount.id}/sqlRoleDefinitions/\${cosmosDbDataContributorRoleId}'
2927
+ principalId: functionsPrincipalId
2928
+ scope: cosmosAccount.id
2929
+ }
2930
+ }
2931
+
2932
+ output roleAssignmentId string = roleAssignment.id
2933
+ `;
2934
+ fs.writeFileSync(path.join(modulesDir, 'cosmosdb-role-assignment.bicep'), cosmosDbRoleAssignmentBicep);
2935
+
2936
+ // VNet modules (only generate if VNet is enabled)
2937
+ if (enableVNet) {
2938
+ // modules/vnet.bicep
2939
+ const vnetBicep = `@description('VNet name')
2940
+ param name string
2941
+
2942
+ @description('Location for VNet')
2943
+ param location string
2944
+
2945
+ resource vnet 'Microsoft.Network/virtualNetworks@2023-09-01' = {
2946
+ name: name
2947
+ location: location
2948
+ properties: {
2949
+ addressSpace: {
2950
+ addressPrefixes: [
2951
+ '10.0.0.0/16'
2952
+ ]
2953
+ }
2954
+ subnets: [
2955
+ {
2956
+ name: 'snet-functions'
2957
+ properties: {
2958
+ addressPrefix: '10.0.1.0/24'
2959
+ delegations: [
2960
+ {
2961
+ name: 'delegation'
2962
+ properties: {
2963
+ serviceName: 'Microsoft.App/environments'
2964
+ }
2965
+ }
2966
+ ]
2967
+ }
2968
+ }
2969
+ {
2970
+ name: 'snet-private-endpoints'
2971
+ properties: {
2972
+ addressPrefix: '10.0.2.0/24'
2973
+ privateEndpointNetworkPolicies: 'Disabled'
2974
+ }
2975
+ }
2976
+ ]
2977
+ }
2978
+ }
2979
+
2980
+ output id string = vnet.id
2981
+ output name string = vnet.name
2982
+ output functionsSubnetId string = vnet.properties.subnets[0].id
2983
+ output privateEndpointSubnetId string = vnet.properties.subnets[1].id
2984
+ `;
2985
+ fs.writeFileSync(path.join(modulesDir, 'vnet.bicep'), vnetBicep);
2986
+
2987
+ // modules/private-endpoint-cosmos.bicep
2988
+ const cosmosPrivateEndpointBicep = `@description('Private endpoint name')
2989
+ param name string
2990
+
2991
+ @description('Location')
2992
+ param location string
2993
+
2994
+ @description('Cosmos DB account resource ID')
2995
+ param cosmosAccountId string
2996
+
2997
+ @description('Cosmos DB account name')
2998
+ param cosmosAccountName string
2999
+
3000
+ @description('Subnet ID for private endpoint')
3001
+ param subnetId string
3002
+
3003
+ @description('VNet ID for DNS zone link')
3004
+ param vnetId string
3005
+
3006
+ // Private DNS Zone for Cosmos DB
3007
+ resource privateDnsZone 'Microsoft.Network/privateDnsZones@2020-06-01' = {
3008
+ name: 'privatelink.documents.azure.com'
3009
+ location: 'global'
3010
+ }
3011
+
3012
+ // Link DNS Zone to VNet
3013
+ resource privateDnsZoneVnetLink 'Microsoft.Network/privateDnsZones/virtualNetworkLinks@2020-06-01' = {
3014
+ parent: privateDnsZone
3015
+ name: '\${cosmosAccountName}-vnet-link'
3016
+ location: 'global'
3017
+ properties: {
3018
+ virtualNetwork: {
3019
+ id: vnetId
3020
+ }
3021
+ registrationEnabled: false
3022
+ }
3023
+ }
3024
+
3025
+ // Private Endpoint for Cosmos DB
3026
+ resource privateEndpoint 'Microsoft.Network/privateEndpoints@2023-09-01' = {
3027
+ name: name
3028
+ location: location
3029
+ properties: {
3030
+ subnet: {
3031
+ id: subnetId
3032
+ }
3033
+ privateLinkServiceConnections: [
3034
+ {
3035
+ name: '\${cosmosAccountName}-connection'
3036
+ properties: {
3037
+ privateLinkServiceId: cosmosAccountId
3038
+ groupIds: [
3039
+ 'Sql'
3040
+ ]
3041
+ }
3042
+ }
3043
+ ]
3044
+ }
3045
+ }
3046
+
3047
+ // DNS Zone Group
3048
+ resource privateDnsZoneGroup 'Microsoft.Network/privateEndpoints/privateDnsZoneGroups@2023-09-01' = {
3049
+ parent: privateEndpoint
3050
+ name: 'default'
3051
+ properties: {
3052
+ privateDnsZoneConfigs: [
3053
+ {
3054
+ name: 'cosmos-dns-config'
3055
+ properties: {
3056
+ privateDnsZoneId: privateDnsZone.id
3057
+ }
3058
+ }
3059
+ ]
3060
+ }
3061
+ }
3062
+
3063
+ output privateEndpointId string = privateEndpoint.id
3064
+ output privateDnsZoneId string = privateDnsZone.id
3065
+ `;
3066
+ fs.writeFileSync(path.join(modulesDir, 'private-endpoint-cosmos.bicep'), cosmosPrivateEndpointBicep);
3067
+
3068
+ console.log('✅ VNet modules created\n');
3069
+ }
3070
+
3071
+ console.log('✅ Infrastructure files created\n');
3072
+ }
3073
+
3074
+ export function getGitHubFunctionsWorkflow(pm: PackageManager, backendLanguage: BackendLanguage): string {
3075
+ const pmCmd = getCommands(pm);
3076
+ const pnpmSetupStep = getCiSetupStep(pm);
3077
+
3078
+ const commonSetup = ` - uses: actions/checkout@v4
3079
+
3080
+ - name: Setup Node.js
3081
+ uses: actions/setup-node@v4
3082
+ with:
3083
+ node-version: '22'
3084
+ ${pnpmSetupStep ? `\n${pnpmSetupStep}\n` : ''}
3085
+ - name: Install dependencies
3086
+ run: |
3087
+ ${pmCmd.ci}
3088
+
3089
+ - name: Build shared package
3090
+ run: |
3091
+ ${pmCmd.runFilter('shared')} build
3092
+ `;
3093
+
3094
+ if (backendLanguage === 'typescript') {
3095
+ return `name: Deploy Azure Functions
3096
+
3097
+ on:
3098
+ push:
3099
+ branches:
3100
+ - main
3101
+ paths:
3102
+ - 'functions/**'
3103
+ - 'shared/**'
3104
+ pull_request:
3105
+ branches:
3106
+ - main
3107
+ paths:
3108
+ - 'functions/**'
3109
+ - 'shared/**'
3110
+ workflow_dispatch:
3111
+
3112
+ jobs:
3113
+ build-and-deploy:
3114
+ runs-on: ubuntu-latest
3115
+ name: Build and Deploy Functions
3116
+
3117
+ steps:
3118
+ ${commonSetup} - name: Build Functions
3119
+ run: |
3120
+ ${pmCmd.runFilter('functions')} build
3121
+
3122
+ - name: Prepare functions for deployment
3123
+ run: |
3124
+ SHARED_PKG_NAME=$(node -p "require('./shared/package.json').name")
3125
+ mkdir -p /tmp/fn-deps
3126
+ node -e "const p=JSON.parse(require('fs').readFileSync('./functions/package.json','utf8'));Object.keys(p.dependencies).filter(k=>k.endsWith('/shared')).forEach(k=>delete p.dependencies[k]);require('fs').writeFileSync('/tmp/fn-deps/package.json',JSON.stringify(p,null,2));"
3127
+ cd /tmp/fn-deps && ${pmCmd.installProd} && cd -
3128
+ rm -rf ./functions/node_modules
3129
+ mv /tmp/fn-deps/node_modules ./functions/node_modules
3130
+ SHARED_DEST="./functions/node_modules/$SHARED_PKG_NAME"
3131
+ mkdir -p "$SHARED_DEST"
3132
+ cp -r ./shared/dist "$SHARED_DEST/dist"
3133
+ cp ./shared/package.json "$SHARED_DEST/package.json"
3134
+
3135
+ - name: Deploy to Azure Functions
3136
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
3137
+ uses: Azure/functions-action@v1
3138
+ with:
3139
+ app-name: \${{ secrets.AZURE_FUNCTIONAPP_NAME }}
3140
+ package: './functions'
3141
+ publish-profile: \${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }}
3142
+ sku: flexconsumption
3143
+ `;
3144
+ }
3145
+
3146
+ if (backendLanguage === 'csharp') {
3147
+ return `name: Deploy Azure Functions
3148
+
3149
+ on:
3150
+ push:
3151
+ branches:
3152
+ - main
3153
+ paths:
3154
+ - 'functions/**'
3155
+ - 'shared/**'
3156
+ pull_request:
3157
+ branches:
3158
+ - main
3159
+ paths:
3160
+ - 'functions/**'
3161
+ - 'shared/**'
3162
+ workflow_dispatch:
3163
+
3164
+ jobs:
3165
+ build-and-deploy:
3166
+ runs-on: ubuntu-latest
3167
+ name: Build and Deploy Functions
3168
+
3169
+ steps:
3170
+ ${commonSetup} - name: Setup .NET
3171
+ uses: actions/setup-dotnet@v4
3172
+ with:
3173
+ dotnet-version: '10.0.x'
3174
+
3175
+ - name: Publish Functions
3176
+ run: |
3177
+ dotnet publish ./functions -c Release -o ./functions/publish
3178
+
3179
+ - name: Deploy to Azure Functions
3180
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
3181
+ uses: Azure/functions-action@v1
3182
+ with:
3183
+ app-name: \${{ secrets.AZURE_FUNCTIONAPP_NAME }}
3184
+ package: './functions/publish'
3185
+ publish-profile: \${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }}
3186
+ sku: flexconsumption
3187
+ `;
3188
+ }
3189
+
3190
+ return `name: Deploy Azure Functions
3191
+
3192
+ on:
3193
+ push:
3194
+ branches:
3195
+ - main
3196
+ paths:
3197
+ - 'functions/**'
3198
+ - 'shared/**'
3199
+ pull_request:
3200
+ branches:
3201
+ - main
3202
+ paths:
3203
+ - 'functions/**'
3204
+ - 'shared/**'
3205
+ workflow_dispatch:
3206
+
3207
+ jobs:
3208
+ build-and-deploy:
3209
+ runs-on: ubuntu-latest
3210
+ name: Build and Deploy Functions
3211
+
3212
+ steps:
3213
+ ${commonSetup} - name: Setup Python
3214
+ uses: actions/setup-python@v5
3215
+ with:
3216
+ python-version: '3.11'
3217
+
3218
+ - name: Install Functions dependencies
3219
+ run: |
3220
+ python -m pip install --upgrade pip
3221
+ python -m pip install -r ./functions/requirements.txt --target "./functions/.python_packages/lib/site-packages"
3222
+
3223
+ - name: Deploy to Azure Functions
3224
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
3225
+ uses: Azure/functions-action@v1
3226
+ with:
3227
+ app-name: \${{ secrets.AZURE_FUNCTIONAPP_NAME }}
3228
+ package: './functions'
3229
+ publish-profile: \${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }}
3230
+ sku: flexconsumption
3231
+ `;
3232
+ }
3233
+
3234
+ export function getAzureFunctionsPipeline(pm: PackageManager, backendLanguage: BackendLanguage): string {
3235
+ const pmCmd = getCommands(pm);
3236
+ const azPipelinesSetup = getAzurePipelinesSetup(pm);
3237
+ const commonSetup = ` - task: NodeTool@0
3238
+ inputs:
3239
+ versionSpec: '22.x'
3240
+ displayName: 'Install Node.js'
3241
+ ${azPipelinesSetup ? `\n${azPipelinesSetup}\n` : ''}
3242
+ - script: |
3243
+ ${pmCmd.ci}
3244
+ displayName: 'Install workspace dependencies'
3245
+
3246
+ - script: |
3247
+ ${pmCmd.runFilter('shared')} build
3248
+ displayName: 'Build shared package'
3249
+ `;
3250
+
3251
+ if (backendLanguage === 'typescript') {
3252
+ return `trigger:
3253
+ branches:
3254
+ include:
3255
+ - main
3256
+ paths:
3257
+ include:
3258
+ - functions/**
3259
+ - shared/**
3260
+
3261
+ pr:
3262
+ branches:
3263
+ include:
3264
+ - main
3265
+ paths:
3266
+ include:
3267
+ - functions/**
3268
+ - shared/**
3269
+
3270
+ pool:
3271
+ vmImage: 'ubuntu-latest'
3272
+
3273
+ variables:
3274
+ - group: azure-deployment
3275
+
3276
+ steps:
3277
+ ${commonSetup} - script: |
3278
+ ${pmCmd.runFilter('functions')} build
3279
+ displayName: 'Build Functions'
3280
+
3281
+ - script: |
3282
+ SHARED_PKG_NAME=$(node -p "require('./shared/package.json').name")
3283
+ mkdir -p /tmp/fn-deps
3284
+ node -e "const p=JSON.parse(require('fs').readFileSync('./functions/package.json','utf8'));Object.keys(p.dependencies).filter(k=>k.endsWith('/shared')).forEach(k=>delete p.dependencies[k]);require('fs').writeFileSync('/tmp/fn-deps/package.json',JSON.stringify(p,null,2));"
3285
+ cd /tmp/fn-deps && ${pmCmd.installProd} && cd -
3286
+ rm -rf ./functions/node_modules
3287
+ mv /tmp/fn-deps/node_modules ./functions/node_modules
3288
+ SHARED_DEST="./functions/node_modules/$SHARED_PKG_NAME"
3289
+ mkdir -p "$SHARED_DEST"
3290
+ cp -r ./shared/dist "$SHARED_DEST/dist"
3291
+ cp ./shared/package.json "$SHARED_DEST/package.json"
3292
+ displayName: 'Prepare functions for deployment'
3293
+
3294
+ - task: ArchiveFiles@2
3295
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3296
+ inputs:
3297
+ rootFolderOrFile: '$(System.DefaultWorkingDirectory)/functions'
3298
+ includeRootFolder: false
3299
+ archiveType: 'zip'
3300
+ archiveFile: '$(Build.ArtifactStagingDirectory)/functions.zip'
3301
+ displayName: 'Archive Functions'
3302
+
3303
+ - task: PublishBuildArtifacts@1
3304
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3305
+ inputs:
3306
+ PathtoPublish: '$(Build.ArtifactStagingDirectory)/functions.zip'
3307
+ ArtifactName: 'functions'
3308
+ displayName: 'Publish Functions artifact'
3309
+
3310
+ - task: AzureFunctionApp@2
3311
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3312
+ inputs:
3313
+ azureSubscription: '$(AZURE_SUBSCRIPTION)'
3314
+ appType: 'functionAppLinux'
3315
+ appName: '$(AZURE_FUNCTIONAPP_NAME)'
3316
+ package: '$(Build.ArtifactStagingDirectory)/functions.zip'
3317
+ displayName: 'Deploy to Azure Functions'
3318
+ `;
3319
+ }
3320
+
3321
+ if (backendLanguage === 'csharp') {
3322
+ return `trigger:
3323
+ branches:
3324
+ include:
3325
+ - main
3326
+ paths:
3327
+ include:
3328
+ - functions/**
3329
+ - shared/**
3330
+
3331
+ pr:
3332
+ branches:
3333
+ include:
3334
+ - main
3335
+ paths:
3336
+ include:
3337
+ - functions/**
3338
+ - shared/**
3339
+
3340
+ pool:
3341
+ vmImage: 'ubuntu-latest'
3342
+
3343
+ variables:
3344
+ - group: azure-deployment
3345
+
3346
+ steps:
3347
+ ${commonSetup} - task: UseDotNet@2
3348
+ inputs:
3349
+ version: '10.0.x'
3350
+ displayName: 'Install .NET SDK'
3351
+
3352
+ - script: |
3353
+ dotnet publish ./functions -c Release -o ./functions/publish
3354
+ displayName: 'Publish Functions'
3355
+
3356
+ - task: ArchiveFiles@2
3357
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3358
+ inputs:
3359
+ rootFolderOrFile: '$(System.DefaultWorkingDirectory)/functions/publish'
3360
+ includeRootFolder: false
3361
+ archiveType: 'zip'
3362
+ archiveFile: '$(Build.ArtifactStagingDirectory)/functions.zip'
3363
+ displayName: 'Archive Functions'
3364
+
3365
+ - task: AzureFunctionApp@2
3366
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3367
+ inputs:
3368
+ azureSubscription: '$(AZURE_SUBSCRIPTION)'
3369
+ appType: 'functionAppLinux'
3370
+ appName: '$(AZURE_FUNCTIONAPP_NAME)'
3371
+ package: '$(Build.ArtifactStagingDirectory)/functions.zip'
3372
+ displayName: 'Deploy to Azure Functions'
3373
+ `;
3374
+ }
3375
+
3376
+ return `trigger:
3377
+ branches:
3378
+ include:
3379
+ - main
3380
+ paths:
3381
+ include:
3382
+ - functions/**
3383
+ - shared/**
3384
+
3385
+ pr:
3386
+ branches:
3387
+ include:
3388
+ - main
3389
+ paths:
3390
+ include:
3391
+ - functions/**
3392
+ - shared/**
3393
+
3394
+ pool:
3395
+ vmImage: 'ubuntu-latest'
3396
+
3397
+ variables:
3398
+ - group: azure-deployment
3399
+
3400
+ steps:
3401
+ ${commonSetup} - task: UsePythonVersion@0
3402
+ inputs:
3403
+ versionSpec: '3.11'
3404
+ displayName: 'Install Python'
3405
+
3406
+ - script: |
3407
+ python -m pip install --upgrade pip
3408
+ python -m pip install -r ./functions/requirements.txt --target "./functions/.python_packages/lib/site-packages"
3409
+ displayName: 'Install Functions dependencies'
3410
+
3411
+ - task: ArchiveFiles@2
3412
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3413
+ inputs:
3414
+ rootFolderOrFile: '$(System.DefaultWorkingDirectory)/functions'
3415
+ includeRootFolder: false
3416
+ archiveType: 'zip'
3417
+ archiveFile: '$(Build.ArtifactStagingDirectory)/functions.zip'
3418
+ displayName: 'Archive Functions'
3419
+
3420
+ - task: AzureFunctionApp@2
3421
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3422
+ inputs:
3423
+ azureSubscription: '$(AZURE_SUBSCRIPTION)'
3424
+ appType: 'functionAppLinux'
3425
+ appName: '$(AZURE_FUNCTIONAPP_NAME)'
3426
+ package: '$(Build.ArtifactStagingDirectory)/functions.zip'
3427
+ displayName: 'Deploy to Azure Functions'
3428
+ `;
3429
+ }
3430
+
3431
+ export function buildAzureSwaPipeline(pm: PackageManager): string {
3432
+ const pmCmd = getCommands(pm);
3433
+ const azPipelinesSetup = getAzurePipelinesSetup(pm);
3434
+
3435
+ return `trigger:
3436
+ branches:
3437
+ include:
3438
+ - main
3439
+ paths:
3440
+ include:
3441
+ - app/**
3442
+ - components/**
3443
+ - lib/**
3444
+ - shared/**
3445
+ - public/**
3446
+ - package.json
3447
+ - next.config.js
3448
+
3449
+ pr:
3450
+ branches:
3451
+ include:
3452
+ - main
3453
+ paths:
3454
+ include:
3455
+ - app/**
3456
+ - components/**
3457
+ - lib/**
3458
+ - shared/**
3459
+ - public/**
3460
+ - package.json
3461
+ - next.config.js
3462
+
3463
+ pool:
3464
+ vmImage: 'ubuntu-latest'
3465
+
3466
+ variables:
3467
+ - group: azure-deployment
3468
+
3469
+ steps:
3470
+ - task: NodeTool@0
3471
+ inputs:
3472
+ versionSpec: '22.x'
3473
+ displayName: 'Install Node.js'
3474
+ ${azPipelinesSetup ? `\n${azPipelinesSetup}\n` : ''}
3475
+ - script: |
3476
+ ${pmCmd.ci}
3477
+ displayName: 'Install dependencies'
3478
+
3479
+ - script: |
3480
+ ${pmCmd.run} build
3481
+ env:
3482
+ NODE_ENV: production
3483
+ displayName: 'Build Next.js app'
3484
+
3485
+ - task: AzureStaticWebApp@0
3486
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3487
+ inputs:
3488
+ app_location: '.'
3489
+ output_location: '.next/standalone'
3490
+ skip_app_build: true
3491
+ azure_static_web_apps_api_token: $(AZURE_STATIC_WEB_APPS_API_TOKEN)
3492
+ displayName: 'Deploy to Azure Static Web Apps'
3493
+ `;
3494
+ }
3495
+
3496
+ async function createGitHubActionsWorkflows(
3497
+ projectDir: string,
3498
+ azureConfig: AzureConfig,
3499
+ pm: PackageManager,
3500
+ backendLanguage: BackendLanguage
3501
+ ) {
3502
+ console.log('📦 Creating GitHub Actions workflows...\n');
3503
+ const workflowsDir = path.join(projectDir, '.github', 'workflows');
3504
+ fs.mkdirSync(workflowsDir, { recursive: true });
3505
+
3506
+ const actionsPm: PackageManager = 'npm';
3507
+
3508
+ const swaWorkflow = buildGitHubSwaWorkflow(actionsPm);
3509
+ fs.writeFileSync(path.join(workflowsDir, 'deploy-swa.yml'), swaWorkflow);
3510
+
3511
+ // deploy-functions.yml
3512
+ const functionsWorkflow = getGitHubFunctionsWorkflow(actionsPm, backendLanguage);
3513
+ fs.writeFileSync(path.join(workflowsDir, 'deploy-functions.yml'), functionsWorkflow);
3514
+
3515
+ console.log('✅ GitHub Actions workflows created\n');
3516
+ }
3517
+
3518
+ export function buildGitHubSwaWorkflow(pm: PackageManager): string {
3519
+ return `name: Deploy Static Web App
3520
+
3521
+ on:
3522
+ push:
3523
+ branches:
3524
+ - main
3525
+ paths:
3526
+ - 'app/**'
3527
+ - 'components/**'
3528
+ - 'lib/**'
3529
+ - 'shared/**'
3530
+ - 'public/**'
3531
+ - 'package.json'
3532
+ - 'next.config.js'
3533
+ - 'next.config.ts'
3534
+ workflow_dispatch:
3535
+ pull_request:
3536
+ branches:
3537
+ - main
3538
+ paths:
3539
+ - 'app/**'
3540
+ - 'components/**'
3541
+ - 'lib/**'
3542
+ - 'shared/**'
3543
+ - 'public/**'
3544
+ - 'package.json'
3545
+ - 'next.config.js'
3546
+ - 'next.config.ts'
3547
+
3548
+ jobs:
3549
+ build-and-deploy:
3550
+ runs-on: ubuntu-latest
3551
+ name: Build and Deploy Static Web App
3552
+
3553
+ steps:
3554
+ - uses: actions/checkout@v4
3555
+ with:
3556
+ submodules: true
3557
+
3558
+ - name: Setup Node.js
3559
+ uses: actions/setup-node@v4
3560
+ with:
3561
+ node-version: '22'
3562
+ ${getCiSetupStep(pm) ? `\n${getCiSetupStep(pm)}\n` : ''}
3563
+ - name: Install and build app
3564
+ run: |
3565
+ ${getSwaAppBuildCommand(pm)}
3566
+
3567
+ - name: Deploy to Azure Static Web Apps
3568
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
3569
+ uses: Azure/static-web-apps-deploy@v1
3570
+ with:
3571
+ azure_static_web_apps_api_token: \${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
3572
+ repo_token: \${{ secrets.GITHUB_TOKEN }}
3573
+ action: 'upload'
3574
+ app_location: '/'
3575
+ api_location: ''
3576
+ output_location: ''
3577
+ app_build_command: '${getSwaAppBuildCommand(pm)}'
3578
+ env:
3579
+ NEXT_TURBOPACK_EXPERIMENTAL_USE_SYSTEM_TLS_CERTS: '1'
3580
+ `;
3581
+ }
3582
+
3583
+ async function createAzurePipelines(projectDir: string, pm: PackageManager, backendLanguage: BackendLanguage) {
3584
+ console.log('📦 Creating Azure Pipelines...\n');
3585
+
3586
+ const pipelinesPm: PackageManager = 'npm';
3587
+ const pipelinesDir = path.join(projectDir, 'pipelines');
3588
+ fs.mkdirSync(pipelinesDir, { recursive: true });
3589
+
3590
+ // swa.yml
3591
+ const swaPipeline = buildAzureSwaPipeline(pipelinesPm);
3592
+ fs.writeFileSync(path.join(pipelinesDir, 'swa.yml'), swaPipeline);
3593
+
3594
+ // functions.yml
3595
+ const functionsPipeline = getAzureFunctionsPipeline(pipelinesPm, backendLanguage);
3596
+ fs.writeFileSync(path.join(pipelinesDir, 'functions.yml'), functionsPipeline);
3597
+
3598
+ console.log('✅ Azure Pipelines created\n');
3599
+ }
3600
+