swallowkit 1.0.0-beta.5 → 1.0.0-beta.7

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