native-update-capacitor 0.0.0-stage → 4.3.0

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 (139) hide show
  1. package/AI-INTEGRATION-GUIDE.md +578 -0
  2. package/LICENSE +25 -0
  3. package/NativeUpdate.podspec +19 -0
  4. package/README.md +574 -2
  5. package/android/build.gradle +125 -0
  6. package/android/consumer-rules.pro +9 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  8. package/android/gradle.properties +17 -0
  9. package/android/manifest-additions.xml +28 -0
  10. package/android/proguard-rules.pro +26 -0
  11. package/android/settings.gradle +2 -0
  12. package/android/src/main/AndroidManifest.xml +13 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
  20. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
  21. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
  22. package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
  23. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
  24. package/android/variables.gradle +5 -0
  25. package/cli/commands/backend-create.js +623 -0
  26. package/cli/commands/bundle-create.js +145 -0
  27. package/cli/commands/bundle-sign.js +64 -0
  28. package/cli/commands/bundle-verify.js +58 -0
  29. package/cli/commands/init.js +146 -0
  30. package/cli/commands/keys-generate.js +58 -0
  31. package/cli/commands/monitor.js +89 -0
  32. package/cli/commands/remote-shared.js +262 -0
  33. package/cli/commands/remote.js +622 -0
  34. package/cli/commands/server-start.js +96 -0
  35. package/cli/index.js +605 -0
  36. package/cli/package.json +21 -0
  37. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  38. package/dist/esm/app-review/app-review-manager.js +194 -0
  39. package/dist/esm/app-review/index.d.ts +5 -0
  40. package/dist/esm/app-review/index.js +5 -0
  41. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  42. package/dist/esm/app-review/platform-review-handler.js +137 -0
  43. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  44. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  45. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  46. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  47. package/dist/esm/app-review/types.d.ts +41 -0
  48. package/dist/esm/app-review/types.js +1 -0
  49. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  50. package/dist/esm/app-update/app-update-checker.js +227 -0
  51. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  52. package/dist/esm/app-update/app-update-installer.js +134 -0
  53. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  54. package/dist/esm/app-update/app-update-manager.js +198 -0
  55. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  56. package/dist/esm/app-update/app-update-notifier.js +99 -0
  57. package/dist/esm/app-update/index.d.ts +6 -0
  58. package/dist/esm/app-update/index.js +6 -0
  59. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  60. package/dist/esm/app-update/platform-app-update.js +138 -0
  61. package/dist/esm/app-update/types.d.ts +58 -0
  62. package/dist/esm/app-update/types.js +11 -0
  63. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  64. package/dist/esm/background-update/background-scheduler.js +332 -0
  65. package/dist/esm/background-update/index.d.ts +3 -0
  66. package/dist/esm/background-update/index.js +2 -0
  67. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  68. package/dist/esm/background-update/notification-manager.js +88 -0
  69. package/dist/esm/config/support.d.ts +9 -0
  70. package/dist/esm/config/support.js +9 -0
  71. package/dist/esm/core/analytics.d.ts +83 -0
  72. package/dist/esm/core/analytics.js +151 -0
  73. package/dist/esm/core/cache-manager.d.ts +72 -0
  74. package/dist/esm/core/cache-manager.js +274 -0
  75. package/dist/esm/core/config.d.ts +69 -0
  76. package/dist/esm/core/config.js +107 -0
  77. package/dist/esm/core/errors.d.ts +56 -0
  78. package/dist/esm/core/errors.js +85 -0
  79. package/dist/esm/core/event-emitter.d.ts +30 -0
  80. package/dist/esm/core/event-emitter.js +80 -0
  81. package/dist/esm/core/logger.d.ts +21 -0
  82. package/dist/esm/core/logger.js +108 -0
  83. package/dist/esm/core/performance.d.ts +53 -0
  84. package/dist/esm/core/performance.js +153 -0
  85. package/dist/esm/core/plugin-manager.d.ts +88 -0
  86. package/dist/esm/core/plugin-manager.js +224 -0
  87. package/dist/esm/core/security.d.ts +123 -0
  88. package/dist/esm/core/security.js +361 -0
  89. package/dist/esm/core/update-check.d.ts +121 -0
  90. package/dist/esm/core/update-check.js +127 -0
  91. package/dist/esm/definitions.d.ts +872 -0
  92. package/dist/esm/definitions.js +104 -0
  93. package/dist/esm/index.d.ts +14 -0
  94. package/dist/esm/index.js +18 -0
  95. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  96. package/dist/esm/live-update/bundle-manager.js +344 -0
  97. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  98. package/dist/esm/live-update/certificate-pinning.js +77 -0
  99. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  100. package/dist/esm/live-update/delta-processor.js +257 -0
  101. package/dist/esm/live-update/download-manager.d.ts +106 -0
  102. package/dist/esm/live-update/download-manager.js +412 -0
  103. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  104. package/dist/esm/live-update/rollout-checker.js +304 -0
  105. package/dist/esm/live-update/update-manager.d.ts +63 -0
  106. package/dist/esm/live-update/update-manager.js +321 -0
  107. package/dist/esm/live-update/version-manager.d.ts +93 -0
  108. package/dist/esm/live-update/version-manager.js +390 -0
  109. package/dist/esm/plugin.d.ts +3 -0
  110. package/dist/esm/plugin.js +848 -0
  111. package/dist/esm/security/crypto.d.ts +88 -0
  112. package/dist/esm/security/crypto.js +228 -0
  113. package/dist/esm/security/validator.d.ts +60 -0
  114. package/dist/esm/security/validator.js +142 -0
  115. package/dist/esm/types/app-identity.d.ts +36 -0
  116. package/dist/esm/types/app-identity.js +1 -0
  117. package/dist/esm/types/rollout.d.ts +91 -0
  118. package/dist/esm/types/rollout.js +25 -0
  119. package/dist/esm/web.d.ts +130 -0
  120. package/dist/esm/web.js +981 -0
  121. package/dist/plugin.cjs +1 -0
  122. package/dist/plugin.esm.js +1 -0
  123. package/dist/plugin.js +2 -0
  124. package/docs/CHANGELOG.md +993 -0
  125. package/docs/KNOWN_LIMITATIONS.md +235 -0
  126. package/docs/MIGRATION.md +391 -0
  127. package/docs/protocol/CLIENT-PROTOCOL.md +178 -0
  128. package/docs/server-requirements.md +211 -0
  129. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  130. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  131. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  133. package/ios/Plugin/Info.plist +43 -0
  134. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  135. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  136. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  137. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  138. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  139. package/package.json +135 -4
@@ -0,0 +1,623 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import { dirname } from 'path';
6
+ import ora from 'ora';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ /**
12
+ * Banner injected at the top of every generated server-side file. The
13
+ * generator emits SCAFFOLDS, not turn-key production code: bundle
14
+ * lookup, persistent storage, signature verification, and rollout
15
+ * gating are all left as `TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]`
16
+ * markers because the right answer depends on the host's storage +
17
+ * DB choices. Fully working references:
18
+ * - example-apps/node-express (minimal HTTP contract)
19
+ * - backend/ (Laravel + Nova production app)
20
+ */
21
+ const SCAFFOLD_BANNER = `/**
22
+ * ⚠️ SCAFFOLD — IMPLEMENT BEFORE DEPLOYING ⚠️
23
+ *
24
+ * This file was generated by \`native-update backend-create\` as a
25
+ * STARTING POINT, not a deploy-ready service. Every block tagged
26
+ * \`TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]\` MUST be replaced with
27
+ * real persistence + storage + signature verification before this
28
+ * runs in production.
29
+ *
30
+ * Working references:
31
+ * • example-apps/node-express — minimal HTTP-contract reference
32
+ * • backend/ (Laravel + Nova) — full SaaS implementation
33
+ *
34
+ * Deploying this file as-is will respond with hard-coded sample
35
+ * payloads and silently drop uploaded bundles.
36
+ */
37
+ `;
38
+
39
+ const POST_GENERATION_WARNING = [
40
+ '',
41
+ chalk.yellow.bold('⚠️ SCAFFOLD — NOT PRODUCTION READY ⚠️'),
42
+ chalk.gray('This template ships with placeholder bundle lookup + storage logic.'),
43
+ chalk.gray('Search the generated code for `TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]`'),
44
+ chalk.gray('and replace each block with your real DB / storage / signing logic.'),
45
+ chalk.gray('See:'),
46
+ chalk.gray(' • example-apps/node-express (minimal HTTP-contract reference)'),
47
+ chalk.gray(' • backend/ (Laravel + Nova) (full SaaS implementation)'),
48
+ '',
49
+ ].join('\n');
50
+
51
+ export async function createBackend(type, options) {
52
+ const spinner = ora(`Creating ${type} backend template...`).start();
53
+
54
+ try {
55
+ const outputDir = path.resolve(options.output);
56
+
57
+ // Check if directory exists
58
+ try {
59
+ await fs.access(outputDir);
60
+ spinner.fail(`Directory ${outputDir} already exists`);
61
+ return;
62
+ } catch {
63
+ // Directory doesn't exist, good
64
+ }
65
+
66
+ // Create output directory
67
+ await fs.mkdir(outputDir, { recursive: true });
68
+
69
+ switch (type) {
70
+ case 'express':
71
+ await createExpressBackend(outputDir, options);
72
+ break;
73
+ case 'firebase':
74
+ await createFirebaseBackend(outputDir, options);
75
+ break;
76
+ case 'vercel':
77
+ await createVercelBackend(outputDir, options);
78
+ break;
79
+ default:
80
+ throw new Error(`Unknown backend type: ${type}`);
81
+ }
82
+
83
+ spinner.succeed(`${type} backend scaffold created!`);
84
+
85
+ console.log(POST_GENERATION_WARNING);
86
+ console.log(chalk.bold('Next steps:'));
87
+ console.log(chalk.gray(` 1. cd ${options.output}`));
88
+ console.log(chalk.gray(` 2. npm install`));
89
+ console.log(chalk.gray(` 3. Configure your environment variables`));
90
+ console.log(chalk.gray(` 4. Replace every TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY] block`));
91
+ console.log(chalk.gray(` 5. npm run dev`));
92
+
93
+ } catch (error) {
94
+ spinner.fail(`Failed to create backend: ${error.message}`);
95
+ process.exit(1);
96
+ }
97
+ }
98
+
99
+ async function createExpressBackend(outputDir, options) {
100
+ // Create package.json
101
+ const packageJson = {
102
+ name: "native-update-backend",
103
+ version: "1.0.0",
104
+ description: "Native Update backend server",
105
+ type: "module",
106
+ scripts: {
107
+ dev: "node --watch server.js",
108
+ start: "node server.js",
109
+ test: "vitest"
110
+ },
111
+ dependencies: {
112
+ express: "^5.1.0",
113
+ cors: "^2.8.5",
114
+ "express-rate-limit": "^7.4.1",
115
+ multer: "^1.4.5-lts.1",
116
+ dotenv: "^16.4.7",
117
+ jsonwebtoken: "^9.0.2",
118
+ bcrypt: "^5.1.1"
119
+ }
120
+ };
121
+
122
+ if (options.withMonitoring) {
123
+ packageJson.dependencies["@opentelemetry/api"] = "^1.9.0";
124
+ packageJson.dependencies["@opentelemetry/sdk-node"] = "^0.57.0";
125
+ packageJson.dependencies["winston"] = "^3.17.1";
126
+ }
127
+
128
+ await fs.writeFile(
129
+ path.join(outputDir, 'package.json'),
130
+ JSON.stringify(packageJson, null, 2)
131
+ );
132
+
133
+ // Create server.js
134
+ const serverCode = `${SCAFFOLD_BANNER}import express from 'express';
135
+ import cors from 'cors';
136
+ import dotenv from 'dotenv';
137
+ import { router as bundleRouter } from './routes/bundles.js';
138
+ import { router as authRouter } from './routes/auth.js';
139
+ ${options.withMonitoring ? "import { initMonitoring } from './monitoring/index.js';" : ''}
140
+
141
+ dotenv.config();
142
+
143
+ const app = express();
144
+ const PORT = process.env.PORT || 3000;
145
+
146
+ ${options.withMonitoring ? 'initMonitoring(app);' : ''}
147
+
148
+ app.use(cors());
149
+ app.use(express.json());
150
+
151
+ // Routes
152
+ app.use('/api/bundles', bundleRouter);
153
+ app.use('/api/auth', authRouter);
154
+
155
+ // Health check
156
+ app.get('/health', (req, res) => {
157
+ res.json({ status: 'ok', timestamp: new Date().toISOString() });
158
+ });
159
+
160
+ app.listen(PORT, () => {
161
+ console.log(\`Server running on port \${PORT}\`);
162
+ });
163
+ `;
164
+
165
+ await fs.writeFile(path.join(outputDir, 'server.js'), serverCode);
166
+
167
+ // Create routes directory
168
+ await fs.mkdir(path.join(outputDir, 'routes'), { recursive: true });
169
+
170
+ // Create bundles route
171
+ const bundlesRoute = `import express from 'express';
172
+ import multer from 'multer';
173
+ import path from 'path';
174
+ import fs from 'fs/promises';
175
+ import crypto from 'crypto';
176
+
177
+ const router = express.Router();
178
+ const upload = multer({ dest: 'uploads/' });
179
+
180
+ // Get latest bundle
181
+ router.get('/latest', async (req, res) => {
182
+ try {
183
+ const { appId, version, channel = 'production' } = req.query;
184
+
185
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: replace with real bundle lookup (DB query against your apps + builds tables)
186
+ // This is a simplified example
187
+ const bundle = {
188
+ version: '1.0.1',
189
+ url: \`\${req.protocol}://\${req.get('host')}/bundles/latest.zip\`,
190
+ checksum: 'sha256:...',
191
+ signature: 'signature...',
192
+ metadata: {
193
+ releaseNotes: 'Bug fixes and improvements'
194
+ }
195
+ };
196
+
197
+ res.json(bundle);
198
+ } catch (error) {
199
+ res.status(500).json({ error: error.message });
200
+ }
201
+ });
202
+
203
+ // Upload new bundle
204
+ router.post('/upload', upload.single('bundle'), async (req, res) => {
205
+ try {
206
+ const { version, channel, metadata } = req.body;
207
+ const file = req.file;
208
+
209
+ if (!file) {
210
+ return res.status(400).json({ error: 'No bundle file provided' });
211
+ }
212
+
213
+ // Calculate checksum
214
+ const fileBuffer = await fs.readFile(file.path);
215
+ const checksum = crypto.createHash('sha256').update(fileBuffer).digest('hex');
216
+
217
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: persist build metadata (channel, version, checksum, signature, fileshub_public_id) — see backend/ Laravel migrations for the canonical shape
218
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: upload to FilesHub (preferred) or your CDN; multer drops to /uploads/ which is ephemeral
219
+
220
+ res.json({
221
+ success: true,
222
+ bundle: {
223
+ version,
224
+ channel,
225
+ checksum,
226
+ size: file.size
227
+ }
228
+ });
229
+ } catch (error) {
230
+ res.status(500).json({ error: error.message });
231
+ }
232
+ });
233
+
234
+ export { router };
235
+ `;
236
+
237
+ await fs.writeFile(path.join(outputDir, 'routes', 'bundles.js'), bundlesRoute);
238
+
239
+ // Create .env.example
240
+ const envExample = `# Server Configuration
241
+ PORT=3000
242
+
243
+ # Security
244
+ JWT_SECRET=your-secret-key-here
245
+ API_KEY=your-api-key-here
246
+
247
+ # Storage
248
+ STORAGE_PATH=./storage/bundles
249
+
250
+ # Database (optional)
251
+ # DATABASE_URL=postgresql://user:password@localhost:5432/native_update
252
+ `;
253
+
254
+ await fs.writeFile(path.join(outputDir, '.env.example'), envExample);
255
+
256
+ // Create README
257
+ const readme = `# Native Update Backend
258
+
259
+ Express.js backend for Native Update plugin.
260
+
261
+ ## Setup
262
+
263
+ 1. Copy \`.env.example\` to \`.env\` and configure
264
+ 2. Run \`npm install\`
265
+ 3. Run \`npm run dev\` for development
266
+
267
+ ## API Endpoints
268
+
269
+ - GET /api/bundles/latest - Get latest bundle for app
270
+ - POST /api/bundles/upload - Upload new bundle
271
+ - GET /health - Health check
272
+
273
+ ## Security
274
+
275
+ - Uses JWT for authentication
276
+ - Rate limiting enabled
277
+ - CORS configured
278
+
279
+ ${options.withMonitoring ? '## Monitoring\n\nOpenTelemetry monitoring is configured. Set up your preferred backend (Jaeger, Zipkin, etc.)' : ''}
280
+ `;
281
+
282
+ await fs.writeFile(path.join(outputDir, 'README.md'), readme);
283
+ }
284
+
285
+ async function createVercelBackend(outputDir, options) {
286
+ // Create api directory
287
+ const apiDir = path.join(outputDir, 'api');
288
+ await fs.mkdir(apiDir, { recursive: true });
289
+
290
+ // Create package.json
291
+ const packageJson = {
292
+ name: "native-update-vercel",
293
+ version: "1.0.0",
294
+ description: "Native Update Vercel backend",
295
+ type: "module",
296
+ scripts: {
297
+ dev: "vercel dev",
298
+ deploy: "vercel",
299
+ build: "echo 'No build step required'"
300
+ },
301
+ dependencies: {
302
+ "@vercel/node": "^3.0.0"
303
+ }
304
+ };
305
+
306
+ await fs.writeFile(
307
+ path.join(outputDir, 'package.json'),
308
+ JSON.stringify(packageJson, null, 2)
309
+ );
310
+
311
+ // Create bundles API endpoint
312
+ const bundlesApi = `${SCAFFOLD_BANNER}export default async function handler(req, res) {
313
+ // Enable CORS
314
+ res.setHeader('Access-Control-Allow-Credentials', true);
315
+ res.setHeader('Access-Control-Allow-Origin', '*');
316
+ res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT');
317
+ res.setHeader(
318
+ 'Access-Control-Allow-Headers',
319
+ 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
320
+ );
321
+
322
+ if (req.method === 'OPTIONS') {
323
+ res.status(200).end();
324
+ return;
325
+ }
326
+
327
+ if (req.method === 'GET') {
328
+ // Get latest bundle
329
+ const { appId, version, channel = 'production' } = req.query;
330
+
331
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: replace with real bundle lookup against your KV / DB store
332
+ // This is a simplified example
333
+ const bundle = {
334
+ version: '1.0.1',
335
+ url: \`https://\${req.headers.host}/bundles/latest.zip\`,
336
+ checksum: 'sha256:...',
337
+ signature: 'signature...',
338
+ metadata: {
339
+ releaseNotes: 'Bug fixes and improvements'
340
+ }
341
+ };
342
+
343
+ return res.status(200).json(bundle);
344
+ }
345
+
346
+ if (req.method === 'POST') {
347
+ // Handle bundle upload
348
+ const { version, channel, metadata } = req.body;
349
+
350
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: upload to Vercel Blob / S3 / FilesHub; verify signature against your signing key registry
351
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: persist build metadata to Vercel KV / Postgres / your DB of choice
352
+
353
+ return res.status(200).json({
354
+ success: true,
355
+ bundle: {
356
+ version,
357
+ channel,
358
+ message: 'Bundle uploaded successfully'
359
+ }
360
+ });
361
+ }
362
+
363
+ return res.status(405).json({ error: 'Method not allowed' });
364
+ }`;
365
+
366
+ await fs.writeFile(path.join(apiDir, 'bundles.js'), bundlesApi);
367
+
368
+ // Create health check endpoint
369
+ const healthApi = `export default function handler(req, res) {
370
+ res.status(200).json({
371
+ status: 'ok',
372
+ service: 'vercel-edge',
373
+ timestamp: new Date().toISOString()
374
+ });
375
+ }`;
376
+
377
+ await fs.writeFile(path.join(apiDir, 'health.js'), healthApi);
378
+
379
+ // Create vercel.json
380
+ const vercelConfig = {
381
+ functions: {
382
+ "api/*.js": {
383
+ maxDuration: 30
384
+ }
385
+ },
386
+ rewrites: [
387
+ {
388
+ source: "/api/bundles/latest",
389
+ destination: "/api/bundles"
390
+ }
391
+ ]
392
+ };
393
+
394
+ await fs.writeFile(
395
+ path.join(outputDir, 'vercel.json'),
396
+ JSON.stringify(vercelConfig, null, 2)
397
+ );
398
+
399
+ // Create .env.example
400
+ const envExample = `# Storage Configuration
401
+ STORAGE_URL=your-storage-url
402
+ STORAGE_KEY=your-storage-key
403
+
404
+ # Database Configuration (optional)
405
+ DATABASE_URL=your-database-url
406
+
407
+ # Security
408
+ API_KEY=your-api-key-here
409
+ `;
410
+
411
+ await fs.writeFile(path.join(outputDir, '.env.example'), envExample);
412
+
413
+ // Create README
414
+ const readme = `# Native Update Vercel Backend
415
+
416
+ Serverless backend for Native Update plugin using Vercel Edge Functions.
417
+
418
+ ## Setup
419
+
420
+ 1. Install Vercel CLI: \`npm i -g vercel\`
421
+ 2. Copy \`.env.example\` to \`.env.local\` and configure
422
+ 3. Run \`npm install\`
423
+ 4. Run \`vercel dev\` for local development
424
+
425
+ ## Deployment
426
+
427
+ \`\`\`bash
428
+ vercel
429
+ \`\`\`
430
+
431
+ ## API Endpoints
432
+
433
+ - GET /api/bundles - Get latest bundle
434
+ - POST /api/bundles - Upload new bundle
435
+ - GET /api/health - Health check
436
+
437
+ ## Storage Options
438
+
439
+ - Vercel Blob Storage
440
+ - AWS S3
441
+ - Cloudflare R2
442
+ - Any S3-compatible storage
443
+
444
+ ## Database Options
445
+
446
+ - Vercel KV
447
+ - Vercel Postgres
448
+ - PlanetScale
449
+ - Supabase
450
+
451
+ ${options.withMonitoring ? '## Monitoring\\n\\nUse Vercel Analytics and Logs for monitoring.' : ''}
452
+ `;
453
+
454
+ await fs.writeFile(path.join(outputDir, 'README.md'), readme);
455
+ }
456
+
457
+ async function createFirebaseBackend(outputDir, options) {
458
+ // Create functions directory
459
+ const functionsDir = path.join(outputDir, 'functions');
460
+ await fs.mkdir(functionsDir, { recursive: true });
461
+
462
+ // Create package.json for functions
463
+ const packageJson = {
464
+ name: "native-update-firebase-functions",
465
+ description: "Firebase Functions backend for Native Update",
466
+ type: "module",
467
+ engines: {
468
+ node: "22"
469
+ },
470
+ main: "index.js",
471
+ scripts: {
472
+ serve: "firebase emulators:start --only functions",
473
+ shell: "firebase functions:shell",
474
+ start: "npm run serve",
475
+ deploy: "firebase deploy --only functions",
476
+ logs: "firebase functions:log"
477
+ },
478
+ dependencies: {
479
+ "firebase-admin": "^12.0.0",
480
+ "firebase-functions": "^5.0.0",
481
+ cors: "^2.8.5",
482
+ "express": "^5.1.0"
483
+ }
484
+ };
485
+
486
+ await fs.writeFile(
487
+ path.join(functionsDir, 'package.json'),
488
+ JSON.stringify(packageJson, null, 2)
489
+ );
490
+
491
+ // Create index.js
492
+ const indexJs = `${SCAFFOLD_BANNER}import { onRequest } from 'firebase-functions/v2/https';
493
+ import * as admin from 'firebase-admin';
494
+ import express from 'express';
495
+ import cors from 'cors';
496
+
497
+ admin.initializeApp();
498
+
499
+ const app = express();
500
+ app.use(cors({ origin: true }));
501
+ app.use(express.json());
502
+
503
+ // Get latest bundle
504
+ app.get('/api/bundles/latest', async (req, res) => {
505
+ try {
506
+ const { appId, version, channel = 'production' } = req.query;
507
+
508
+ // Query Firestore for latest bundle
509
+ const db = admin.firestore();
510
+ const snapshot = await db.collection('bundles')
511
+ .where('appId', '==', appId)
512
+ .where('channel', '==', channel)
513
+ .where('enabled', '==', true)
514
+ .orderBy('createdAt', 'desc')
515
+ .limit(1)
516
+ .get();
517
+
518
+ if (snapshot.empty) {
519
+ return res.status(404).json({ error: 'No bundle found' });
520
+ }
521
+
522
+ const bundle = snapshot.docs[0].data();
523
+ res.json(bundle);
524
+ } catch (error) {
525
+ res.status(500).json({ error: error.message });
526
+ }
527
+ });
528
+
529
+ // Upload bundle
530
+ app.post('/api/bundles/upload', async (req, res) => {
531
+ try {
532
+ const { version, channel, metadata } = req.body;
533
+
534
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: upload to Cloud Storage; verify signature; enforce monotonic version per channel
535
+ // TODO[SCAFFOLD-IMPLEMENT-BEFORE-DEPLOY]: write to Firestore; remember Firestore rules must be locked down (no public writes)
536
+
537
+ res.json({ success: true, version });
538
+ } catch (error) {
539
+ res.status(500).json({ error: error.message });
540
+ }
541
+ });
542
+
543
+ // Health check
544
+ app.get('/health', (req, res) => {
545
+ res.json({ status: 'ok', service: 'firebase-functions' });
546
+ });
547
+
548
+ export const api = onRequest(app);
549
+ `;
550
+
551
+ await fs.writeFile(path.join(functionsDir, 'index.js'), indexJs);
552
+
553
+ // Create firebase.json
554
+ const firebaseConfig = {
555
+ functions: {
556
+ source: "functions",
557
+ runtime: "nodejs22"
558
+ },
559
+ firestore: {
560
+ rules: "firestore.rules",
561
+ indexes: "firestore.indexes.json"
562
+ },
563
+ storage: {
564
+ rules: "storage.rules"
565
+ }
566
+ };
567
+
568
+ await fs.writeFile(
569
+ path.join(outputDir, 'firebase.json'),
570
+ JSON.stringify(firebaseConfig, null, 2)
571
+ );
572
+
573
+ // Create Firestore rules
574
+ const firestoreRules = `rules_version = '2';
575
+ service cloud.firestore {
576
+ match /databases/{database}/documents {
577
+ // Bundles are read-only for clients
578
+ match /bundles/{document=**} {
579
+ allow read: if true;
580
+ allow write: if false;
581
+ }
582
+
583
+ // Analytics can be written by clients
584
+ match /analytics/{document=**} {
585
+ allow create: if true;
586
+ allow read, update, delete: if false;
587
+ }
588
+ }
589
+ }`;
590
+
591
+ await fs.writeFile(path.join(outputDir, 'firestore.rules'), firestoreRules);
592
+
593
+ // Create README
594
+ const readme = `# Native Update Firebase Backend
595
+
596
+ Firebase Functions backend for Native Update plugin.
597
+
598
+ ## Setup
599
+
600
+ 1. Install Firebase CLI: \`npm install -g firebase-tools\`
601
+ 2. Login: \`firebase login\`
602
+ 3. Initialize: \`firebase init\`
603
+ 4. Select your project or create new
604
+ 5. Install dependencies: \`cd functions && npm install\`
605
+ 6. Start emulator: \`npm run serve\`
606
+
607
+ ## Deployment
608
+
609
+ \`\`\`bash
610
+ firebase deploy
611
+ \`\`\`
612
+
613
+ ## Endpoints
614
+
615
+ - GET /api/bundles/latest - Get latest bundle
616
+ - POST /api/bundles/upload - Upload new bundle
617
+ - GET /health - Health check
618
+
619
+ ${options.withMonitoring ? '## Monitoring\n\nUse Firebase Console for monitoring and analytics.' : ''}
620
+ `;
621
+
622
+ await fs.writeFile(path.join(outputDir, 'README.md'), readme);
623
+ }