appwrite-utils-cli 0.10.86 → 1.0.1

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 (178) hide show
  1. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +380 -0
  2. package/.appwrite/.yaml_schemas/collection.schema.json +255 -0
  3. package/.appwrite/collections/Categories.yaml +182 -0
  4. package/.appwrite/collections/ExampleCollection.yaml +36 -0
  5. package/.appwrite/collections/Posts.yaml +227 -0
  6. package/.appwrite/collections/Users.yaml +149 -0
  7. package/.appwrite/config.yaml +109 -0
  8. package/.appwrite/import/README.md +148 -0
  9. package/.appwrite/import/categories-import.yaml +129 -0
  10. package/.appwrite/import/posts-import.yaml +208 -0
  11. package/.appwrite/import/users-import.yaml +130 -0
  12. package/.appwrite/importData/categories.json +194 -0
  13. package/.appwrite/importData/posts.json +270 -0
  14. package/.appwrite/importData/users.json +220 -0
  15. package/.appwrite/schemas/categories.json +128 -0
  16. package/.appwrite/schemas/exampleCollection.json +52 -0
  17. package/.appwrite/schemas/posts.json +173 -0
  18. package/.appwrite/schemas/users.json +125 -0
  19. package/README.md +260 -33
  20. package/dist/collections/attributes.js +3 -2
  21. package/dist/collections/methods.js +56 -38
  22. package/dist/config/yamlConfig.d.ts +501 -0
  23. package/dist/config/yamlConfig.js +452 -0
  24. package/dist/databases/setup.d.ts +6 -0
  25. package/dist/databases/setup.js +119 -0
  26. package/dist/functions/methods.d.ts +1 -1
  27. package/dist/functions/methods.js +5 -2
  28. package/dist/functions/openapi.d.ts +4 -0
  29. package/dist/functions/openapi.js +60 -0
  30. package/dist/interactiveCLI.d.ts +5 -0
  31. package/dist/interactiveCLI.js +194 -49
  32. package/dist/main.js +91 -30
  33. package/dist/migrations/afterImportActions.js +2 -2
  34. package/dist/migrations/appwriteToX.d.ts +10 -0
  35. package/dist/migrations/appwriteToX.js +15 -4
  36. package/dist/migrations/backup.d.ts +16 -16
  37. package/dist/migrations/dataLoader.d.ts +83 -1
  38. package/dist/migrations/dataLoader.js +4 -4
  39. package/dist/migrations/importController.js +25 -18
  40. package/dist/migrations/importDataActions.js +2 -2
  41. package/dist/migrations/logging.d.ts +9 -1
  42. package/dist/migrations/logging.js +41 -22
  43. package/dist/migrations/migrationHelper.d.ts +4 -4
  44. package/dist/migrations/relationships.js +1 -1
  45. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  46. package/dist/migrations/services/DataTransformationService.js +158 -0
  47. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  48. package/dist/migrations/services/FileHandlerService.js +236 -0
  49. package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
  50. package/dist/migrations/services/ImportOrchestrator.js +488 -0
  51. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  52. package/dist/migrations/services/RateLimitManager.js +279 -0
  53. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  54. package/dist/migrations/services/RelationshipResolver.js +332 -0
  55. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  56. package/dist/migrations/services/UserMappingService.js +277 -0
  57. package/dist/migrations/services/ValidationService.d.ts +74 -0
  58. package/dist/migrations/services/ValidationService.js +260 -0
  59. package/dist/migrations/transfer.d.ts +0 -6
  60. package/dist/migrations/transfer.js +16 -132
  61. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +384 -0
  62. package/dist/migrations/yaml/YamlImportConfigLoader.js +375 -0
  63. package/dist/migrations/yaml/YamlImportIntegration.d.ts +87 -0
  64. package/dist/migrations/yaml/YamlImportIntegration.js +330 -0
  65. package/dist/migrations/yaml/generateImportSchemas.d.ts +17 -0
  66. package/dist/migrations/yaml/generateImportSchemas.js +575 -0
  67. package/dist/schemas/authUser.d.ts +9 -9
  68. package/dist/shared/attributeManager.d.ts +17 -0
  69. package/dist/shared/attributeManager.js +273 -0
  70. package/dist/shared/confirmationDialogs.d.ts +75 -0
  71. package/dist/shared/confirmationDialogs.js +236 -0
  72. package/dist/shared/functionManager.d.ts +48 -0
  73. package/dist/shared/functionManager.js +322 -0
  74. package/dist/shared/indexManager.d.ts +24 -0
  75. package/dist/shared/indexManager.js +150 -0
  76. package/dist/shared/jsonSchemaGenerator.d.ts +51 -0
  77. package/dist/shared/jsonSchemaGenerator.js +313 -0
  78. package/dist/shared/logging.d.ts +10 -0
  79. package/dist/shared/logging.js +46 -0
  80. package/dist/shared/messageFormatter.d.ts +37 -0
  81. package/dist/shared/messageFormatter.js +152 -0
  82. package/dist/shared/migrationHelpers.d.ts +173 -0
  83. package/dist/shared/migrationHelpers.js +142 -0
  84. package/dist/shared/operationLogger.d.ts +3 -0
  85. package/dist/shared/operationLogger.js +25 -0
  86. package/dist/shared/operationQueue.d.ts +13 -0
  87. package/dist/shared/operationQueue.js +79 -0
  88. package/dist/shared/progressManager.d.ts +62 -0
  89. package/dist/shared/progressManager.js +215 -0
  90. package/dist/shared/schemaGenerator.d.ts +18 -0
  91. package/dist/shared/schemaGenerator.js +523 -0
  92. package/dist/storage/methods.d.ts +3 -1
  93. package/dist/storage/methods.js +144 -55
  94. package/dist/storage/schemas.d.ts +56 -16
  95. package/dist/types.d.ts +2 -2
  96. package/dist/types.js +1 -1
  97. package/dist/users/methods.d.ts +16 -0
  98. package/dist/users/methods.js +276 -0
  99. package/dist/utils/configMigration.d.ts +1 -0
  100. package/dist/utils/configMigration.js +156 -0
  101. package/dist/utils/dataConverters.d.ts +46 -0
  102. package/dist/utils/dataConverters.js +139 -0
  103. package/dist/utils/loadConfigs.d.ts +15 -4
  104. package/dist/utils/loadConfigs.js +377 -51
  105. package/dist/utils/schemaStrings.js +2 -1
  106. package/dist/utils/setupFiles.d.ts +2 -1
  107. package/dist/utils/setupFiles.js +723 -28
  108. package/dist/utils/validationRules.d.ts +43 -0
  109. package/dist/utils/validationRules.js +42 -0
  110. package/dist/utils/yamlConverter.d.ts +48 -0
  111. package/dist/utils/yamlConverter.js +98 -0
  112. package/dist/utilsController.js +65 -43
  113. package/package.json +19 -15
  114. package/src/collections/attributes.ts +3 -2
  115. package/src/collections/methods.ts +85 -51
  116. package/src/config/yamlConfig.ts +488 -0
  117. package/src/{migrations/setupDatabase.ts → databases/setup.ts} +11 -5
  118. package/src/functions/methods.ts +8 -4
  119. package/src/functions/templates/count-docs-in-collection/package.json +25 -0
  120. package/src/functions/templates/count-docs-in-collection/tsconfig.json +28 -0
  121. package/src/functions/templates/typescript-node/package.json +24 -0
  122. package/src/functions/templates/typescript-node/tsconfig.json +28 -0
  123. package/src/functions/templates/uv/README.md +31 -0
  124. package/src/functions/templates/uv/pyproject.toml +29 -0
  125. package/src/interactiveCLI.ts +226 -61
  126. package/src/main.ts +111 -37
  127. package/src/migrations/afterImportActions.ts +2 -2
  128. package/src/migrations/appwriteToX.ts +17 -4
  129. package/src/migrations/dataLoader.ts +4 -4
  130. package/src/migrations/importController.ts +30 -22
  131. package/src/migrations/importDataActions.ts +2 -2
  132. package/src/migrations/relationships.ts +1 -1
  133. package/src/migrations/services/DataTransformationService.ts +196 -0
  134. package/src/migrations/services/FileHandlerService.ts +311 -0
  135. package/src/migrations/services/ImportOrchestrator.ts +669 -0
  136. package/src/migrations/services/RateLimitManager.ts +363 -0
  137. package/src/migrations/services/RelationshipResolver.ts +461 -0
  138. package/src/migrations/services/UserMappingService.ts +345 -0
  139. package/src/migrations/services/ValidationService.ts +349 -0
  140. package/src/migrations/transfer.ts +22 -228
  141. package/src/migrations/yaml/YamlImportConfigLoader.ts +427 -0
  142. package/src/migrations/yaml/YamlImportIntegration.ts +419 -0
  143. package/src/migrations/yaml/generateImportSchemas.ts +589 -0
  144. package/src/shared/attributeManager.ts +429 -0
  145. package/src/shared/confirmationDialogs.ts +327 -0
  146. package/src/shared/functionManager.ts +515 -0
  147. package/src/shared/indexManager.ts +253 -0
  148. package/src/shared/jsonSchemaGenerator.ts +403 -0
  149. package/src/shared/logging.ts +74 -0
  150. package/src/shared/messageFormatter.ts +195 -0
  151. package/src/{migrations/migrationHelper.ts → shared/migrationHelpers.ts} +22 -4
  152. package/src/{migrations/helper.ts → shared/operationLogger.ts} +7 -2
  153. package/src/{migrations/queue.ts → shared/operationQueue.ts} +1 -1
  154. package/src/shared/progressManager.ts +278 -0
  155. package/src/{migrations/schemaStrings.ts → shared/schemaGenerator.ts} +71 -17
  156. package/src/storage/methods.ts +199 -78
  157. package/src/types.ts +2 -2
  158. package/src/{migrations/users.ts → users/methods.ts} +2 -2
  159. package/src/utils/configMigration.ts +212 -0
  160. package/src/utils/loadConfigs.ts +414 -52
  161. package/src/utils/schemaStrings.ts +2 -1
  162. package/src/utils/setupFiles.ts +742 -40
  163. package/src/{migrations → utils}/validationRules.ts +1 -1
  164. package/src/utils/yamlConverter.ts +131 -0
  165. package/src/utilsController.ts +75 -54
  166. package/src/functions/templates/poetry/README.md +0 -30
  167. package/src/functions/templates/poetry/pyproject.toml +0 -16
  168. package/src/migrations/attributes.ts +0 -561
  169. package/src/migrations/backup.ts +0 -205
  170. package/src/migrations/databases.ts +0 -39
  171. package/src/migrations/dbHelpers.ts +0 -92
  172. package/src/migrations/indexes.ts +0 -40
  173. package/src/migrations/logging.ts +0 -29
  174. package/src/migrations/storage.ts +0 -538
  175. /package/src/{migrations → functions}/openapi.ts +0 -0
  176. /package/src/functions/templates/{poetry → uv}/src/__init__.py +0 -0
  177. /package/src/functions/templates/{poetry → uv}/src/index.py +0 -0
  178. /package/src/{migrations/converters.ts → utils/dataConverters.ts} +0 -0
@@ -0,0 +1,515 @@
1
+ import { Client, Functions, Runtime, type Models } from "node-appwrite";
2
+ import { type AppwriteFunction } from "appwrite-utils";
3
+ import { join, relative, resolve, basename } from "node:path";
4
+ import fs from "node:fs";
5
+ import chalk from "chalk";
6
+ import pLimit from "p-limit";
7
+ import { tryAwaitWithRetry } from "../utils/helperFunctions.js";
8
+
9
+ // Concurrency limits
10
+ const functionLimit = pLimit(5); // Moderate limit for function operations
11
+ const queryLimit = pLimit(25); // Higher limit for read operations
12
+
13
+ export interface FunctionSearchOptions {
14
+ searchPaths?: string[];
15
+ caseSensitive?: boolean;
16
+ allowFuzzyMatch?: boolean;
17
+ verbose?: boolean;
18
+ }
19
+
20
+ export interface FunctionDeploymentOptions {
21
+ activate?: boolean;
22
+ entrypoint?: string;
23
+ commands?: string;
24
+ ignored?: string[];
25
+ verbose?: boolean;
26
+ forceRedeploy?: boolean;
27
+ }
28
+
29
+ export class FunctionManager {
30
+ private client: Client;
31
+ private functions: Functions;
32
+
33
+ constructor(client: Client) {
34
+ this.client = client;
35
+ this.functions = new Functions(client);
36
+ }
37
+
38
+ /**
39
+ * Improved function directory detection with multiple strategies
40
+ */
41
+ public async findFunctionDirectory(
42
+ functionName: string,
43
+ options: FunctionSearchOptions = {}
44
+ ): Promise<string | null> {
45
+ const {
46
+ searchPaths = [process.cwd()],
47
+ caseSensitive = false,
48
+ allowFuzzyMatch = true,
49
+ verbose = false
50
+ } = options;
51
+
52
+ if (verbose) {
53
+ console.log(chalk.blue(`🔍 Searching for function: ${functionName}`));
54
+ }
55
+
56
+ // Normalize function name for comparison
57
+ const normalizedName = caseSensitive ? functionName : functionName.toLowerCase();
58
+ const nameVariations = this.generateNameVariations(normalizedName);
59
+
60
+ // Strategy 1: Check standard locations first
61
+ const standardPaths = this.getStandardFunctionPaths(searchPaths, functionName);
62
+ for (const path of standardPaths) {
63
+ if (await this.isValidFunctionDirectory(path)) {
64
+ if (verbose) {
65
+ console.log(chalk.green(`✓ Found function at standard location: ${path}`));
66
+ }
67
+ return path;
68
+ }
69
+ }
70
+
71
+ // Strategy 2: Recursive directory search with fuzzy matching
72
+ if (allowFuzzyMatch) {
73
+ for (const searchPath of searchPaths) {
74
+ const foundPath = await this.recursiveDirectorySearch(
75
+ searchPath,
76
+ nameVariations,
77
+ { caseSensitive, verbose }
78
+ );
79
+ if (foundPath) {
80
+ if (verbose) {
81
+ console.log(chalk.green(`✓ Found function via fuzzy search: ${foundPath}`));
82
+ }
83
+ return foundPath;
84
+ }
85
+ }
86
+ }
87
+
88
+ if (verbose) {
89
+ console.log(chalk.yellow(`⚠ Function directory not found: ${functionName}`));
90
+ }
91
+ return null;
92
+ }
93
+
94
+ private generateNameVariations(name: string): Set<string> {
95
+ const variations = new Set<string>([
96
+ name,
97
+ name.toLowerCase(),
98
+ name.replace(/\s+/g, "-"),
99
+ name.replace(/\s+/g, "_"),
100
+ name.replace(/[^a-z0-9]/gi, ""),
101
+ name.replace(/[-_\s]+/g, ""),
102
+ name.replace(/[-_\s]+/g, "-").toLowerCase(),
103
+ name.replace(/[-_\s]+/g, "_").toLowerCase(),
104
+ ]);
105
+
106
+ return variations;
107
+ }
108
+
109
+ private getStandardFunctionPaths(searchPaths: string[], functionName: string): string[] {
110
+ const normalizedName = functionName.toLowerCase().replace(/\s+/g, "-");
111
+ const paths: string[] = [];
112
+
113
+ for (const basePath of searchPaths) {
114
+ paths.push(
115
+ join(basePath, "functions", functionName),
116
+ join(basePath, "functions", normalizedName),
117
+ join(basePath, "src", "functions", functionName),
118
+ join(basePath, "src", "functions", normalizedName),
119
+ join(basePath, functionName),
120
+ join(basePath, normalizedName),
121
+ join(basePath, "appwrite", "functions", functionName),
122
+ join(basePath, "appwrite", "functions", normalizedName)
123
+ );
124
+ }
125
+
126
+ return paths;
127
+ }
128
+
129
+ private async recursiveDirectorySearch(
130
+ searchPath: string,
131
+ nameVariations: Set<string>,
132
+ options: { caseSensitive: boolean; verbose: boolean }
133
+ ): Promise<string | null> {
134
+ const { caseSensitive, verbose } = options;
135
+
136
+ try {
137
+ const stats = await fs.promises.stat(searchPath);
138
+ if (!stats.isDirectory()) return null;
139
+
140
+ const entries = await fs.promises.readdir(searchPath, { withFileTypes: true });
141
+
142
+ for (const entry of entries) {
143
+ if (!entry.isDirectory()) continue;
144
+
145
+ // Skip common directories that won't contain functions
146
+ if (this.shouldSkipDirectory(entry.name)) continue;
147
+
148
+ const entryPath = join(searchPath, entry.name);
149
+
150
+ // Check if this directory matches our function name
151
+ const entryNameToCheck = caseSensitive ? entry.name : entry.name.toLowerCase();
152
+ if (nameVariations.has(entryNameToCheck)) {
153
+ if (await this.isValidFunctionDirectory(entryPath)) {
154
+ return entryPath;
155
+ }
156
+ }
157
+
158
+ // Recursively search subdirectories
159
+ const result = await this.recursiveDirectorySearch(entryPath, nameVariations, options);
160
+ if (result) return result;
161
+ }
162
+ } catch (error) {
163
+ if (verbose) {
164
+ console.log(chalk.gray(`Skipping inaccessible directory: ${searchPath}`));
165
+ }
166
+ }
167
+
168
+ return null;
169
+ }
170
+
171
+ private shouldSkipDirectory(dirName: string): boolean {
172
+ const skipDirs = new Set([
173
+ 'node_modules',
174
+ '.git',
175
+ '.vscode',
176
+ '.idea',
177
+ 'dist',
178
+ 'build',
179
+ 'coverage',
180
+ '.nyc_output',
181
+ 'tmp',
182
+ 'temp',
183
+ '.cache',
184
+ '__pycache__',
185
+ '.pytest_cache',
186
+ 'venv',
187
+ '.venv',
188
+ 'env',
189
+ '.env'
190
+ ]);
191
+
192
+ return skipDirs.has(dirName) || dirName.startsWith('.');
193
+ }
194
+
195
+ private async isValidFunctionDirectory(path: string): Promise<boolean> {
196
+ try {
197
+ const stats = await fs.promises.stat(path);
198
+ if (!stats.isDirectory()) return false;
199
+
200
+ const files = await fs.promises.readdir(path);
201
+
202
+ // Check for common function indicators
203
+ const hasPackageJson = files.includes('package.json');
204
+ const hasMainFile = files.some(file =>
205
+ file.match(/^(index|main|app)\.(js|ts|py)$/i) ||
206
+ file === 'src' ||
207
+ file === 'lib'
208
+ );
209
+ const hasRequirements = files.includes('requirements.txt');
210
+ const hasPyProject = files.includes('pyproject.toml');
211
+
212
+ return hasPackageJson || hasMainFile || hasRequirements || hasPyProject;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Enhanced function deployment with better error handling and validation
220
+ */
221
+ public async deployFunction(
222
+ functionConfig: AppwriteFunction,
223
+ functionPath: string,
224
+ options: FunctionDeploymentOptions = {}
225
+ ): Promise<Models.Deployment> {
226
+ const {
227
+ activate = true,
228
+ entrypoint = functionConfig.entrypoint || "index.js",
229
+ commands = functionConfig.commands || "npm install",
230
+ ignored = ["node_modules", ".git", ".vscode", ".DS_Store", "__pycache__", ".venv"],
231
+ verbose = false,
232
+ forceRedeploy = false
233
+ } = options;
234
+
235
+ return await functionLimit(async () => {
236
+ if (verbose) {
237
+ console.log(chalk.blue(`🚀 Deploying function: ${functionConfig.name}`));
238
+ console.log(chalk.gray(` Path: ${functionPath}`));
239
+ console.log(chalk.gray(` Entrypoint: ${entrypoint}`));
240
+ }
241
+
242
+ // Validate function directory
243
+ if (!await this.isValidFunctionDirectory(functionPath)) {
244
+ throw new Error(`Invalid function directory: ${functionPath}`);
245
+ }
246
+
247
+ // Ensure function exists
248
+ let functionExists = false;
249
+ try {
250
+ await this.getFunction(functionConfig.$id);
251
+ functionExists = true;
252
+ } catch (error) {
253
+ if (verbose) {
254
+ console.log(chalk.yellow(`Function ${functionConfig.$id} does not exist, creating...`));
255
+ }
256
+ }
257
+
258
+ // Create function if it doesn't exist
259
+ if (!functionExists) {
260
+ await this.createFunction(functionConfig, { verbose });
261
+ } else if (forceRedeploy) {
262
+ await this.updateFunction(functionConfig, { verbose });
263
+ }
264
+
265
+ // Execute pre-deploy commands if specified
266
+ if (functionConfig.predeployCommands?.length) {
267
+ await this.executePredeployCommands(functionConfig.predeployCommands, functionPath, { verbose });
268
+ }
269
+
270
+ // Deploy the function
271
+ const deployment = await this.createDeployment(
272
+ functionConfig.$id,
273
+ functionPath,
274
+ { activate, entrypoint, commands, ignored, verbose }
275
+ );
276
+
277
+ if (verbose) {
278
+ console.log(chalk.green(`✅ Function ${functionConfig.name} deployed successfully`));
279
+ }
280
+
281
+ return deployment;
282
+ });
283
+ }
284
+
285
+ private async createFunction(
286
+ functionConfig: AppwriteFunction,
287
+ options: { verbose?: boolean } = {}
288
+ ): Promise<Models.Function> {
289
+ const { verbose = false } = options;
290
+
291
+ if (verbose) {
292
+ console.log(chalk.blue(`Creating function: ${functionConfig.name}`));
293
+ }
294
+
295
+ return await tryAwaitWithRetry(async () => {
296
+ return await this.functions.create(
297
+ functionConfig.$id,
298
+ functionConfig.name,
299
+ functionConfig.runtime as Runtime,
300
+ functionConfig.execute || [],
301
+ functionConfig.events || [],
302
+ functionConfig.schedule || "",
303
+ functionConfig.timeout || 15,
304
+ functionConfig.enabled !== false,
305
+ functionConfig.logging !== false,
306
+ functionConfig.entrypoint,
307
+ functionConfig.commands,
308
+ functionConfig.scopes || [],
309
+ functionConfig.installationId,
310
+ functionConfig.providerRepositoryId,
311
+ functionConfig.providerBranch,
312
+ functionConfig.providerSilentMode,
313
+ functionConfig.providerRootDirectory,
314
+ functionConfig.templateRepository,
315
+ functionConfig.templateOwner,
316
+ functionConfig.templateRootDirectory,
317
+ functionConfig.templateVersion,
318
+ functionConfig.specification
319
+ );
320
+ });
321
+ }
322
+
323
+ private async updateFunction(
324
+ functionConfig: AppwriteFunction,
325
+ options: { verbose?: boolean } = {}
326
+ ): Promise<Models.Function> {
327
+ const { verbose = false } = options;
328
+
329
+ if (verbose) {
330
+ console.log(chalk.blue(`Updating function: ${functionConfig.name}`));
331
+ }
332
+
333
+ return await tryAwaitWithRetry(async () => {
334
+ return await this.functions.update(
335
+ functionConfig.$id,
336
+ functionConfig.name,
337
+ functionConfig.runtime as Runtime,
338
+ functionConfig.execute || [],
339
+ functionConfig.events || [],
340
+ functionConfig.schedule || "",
341
+ functionConfig.timeout || 15,
342
+ functionConfig.enabled !== false,
343
+ functionConfig.logging !== false,
344
+ functionConfig.entrypoint,
345
+ functionConfig.commands,
346
+ functionConfig.scopes || [],
347
+ functionConfig.installationId,
348
+ functionConfig.providerRepositoryId,
349
+ functionConfig.providerBranch,
350
+ functionConfig.providerSilentMode,
351
+ functionConfig.providerRootDirectory,
352
+ functionConfig.specification
353
+ );
354
+ });
355
+ }
356
+
357
+ private async executePredeployCommands(
358
+ commands: string[],
359
+ workingDir: string,
360
+ options: { verbose?: boolean } = {}
361
+ ): Promise<void> {
362
+ const { verbose = false } = options;
363
+ const { execSync } = await import("child_process");
364
+ const { platform } = await import("node:os");
365
+
366
+ if (verbose) {
367
+ console.log(chalk.blue("Executing pre-deploy commands..."));
368
+ }
369
+
370
+ const isWindows = platform() === "win32";
371
+
372
+ for (const command of commands) {
373
+ if (verbose) {
374
+ console.log(chalk.gray(` $ ${command}`));
375
+ }
376
+
377
+ try {
378
+ execSync(command, {
379
+ cwd: workingDir,
380
+ stdio: verbose ? "inherit" : "pipe",
381
+ shell: isWindows ? "cmd.exe" : "/bin/sh",
382
+ windowsHide: true,
383
+ });
384
+ } catch (error) {
385
+ console.error(chalk.red(`Failed to execute command: ${command}`));
386
+ throw error;
387
+ }
388
+ }
389
+
390
+ if (verbose) {
391
+ console.log(chalk.green("✓ Pre-deploy commands completed"));
392
+ }
393
+ }
394
+
395
+ private async createDeployment(
396
+ functionId: string,
397
+ codePath: string,
398
+ options: FunctionDeploymentOptions & { verbose?: boolean } = {}
399
+ ): Promise<Models.Deployment> {
400
+ const { activate = true, entrypoint = "index.js", commands = "npm install", ignored = [], verbose = false } = options;
401
+
402
+ const { InputFile } = await import("node-appwrite/file");
403
+ const { create: createTarball } = await import("tar");
404
+
405
+ const tarPath = join(process.cwd(), `function-${functionId}-${Date.now()}.tar.gz`);
406
+
407
+ try {
408
+ if (verbose) {
409
+ console.log(chalk.blue("Creating deployment archive..."));
410
+ }
411
+
412
+ // Create tarball
413
+ await createTarball(
414
+ {
415
+ gzip: true,
416
+ file: tarPath,
417
+ cwd: codePath,
418
+ filter: (path) => {
419
+ const relativePath = relative(codePath, join(codePath, path)).toLowerCase();
420
+ const shouldIgnore = ignored.some(pattern =>
421
+ relativePath.startsWith(pattern.toLowerCase()) ||
422
+ relativePath.includes(`/${pattern.toLowerCase()}`) ||
423
+ relativePath.includes(`\\${pattern.toLowerCase()}`)
424
+ );
425
+
426
+ if (shouldIgnore && verbose) {
427
+ console.log(chalk.gray(` Ignoring: ${path}`));
428
+ }
429
+
430
+ return !shouldIgnore;
431
+ },
432
+ },
433
+ ["."]
434
+ );
435
+
436
+ // Read and upload
437
+ const fileBuffer = await fs.promises.readFile(tarPath);
438
+ const fileObject = InputFile.fromBuffer(
439
+ new Uint8Array(fileBuffer),
440
+ `function-${functionId}.tar.gz`
441
+ );
442
+
443
+ if (verbose) {
444
+ console.log(chalk.blue("Uploading deployment..."));
445
+ }
446
+
447
+ const deployment = await tryAwaitWithRetry(async () => {
448
+ return await this.functions.createDeployment(
449
+ functionId,
450
+ fileObject,
451
+ activate,
452
+ entrypoint,
453
+ commands
454
+ );
455
+ });
456
+
457
+ return deployment;
458
+ } finally {
459
+ // Clean up tarball
460
+ try {
461
+ await fs.promises.unlink(tarPath);
462
+ } catch {
463
+ // Ignore cleanup errors
464
+ }
465
+ }
466
+ }
467
+
468
+ public async getFunction(functionId: string): Promise<Models.Function> {
469
+ return await queryLimit(() =>
470
+ tryAwaitWithRetry(async () => await this.functions.get(functionId))
471
+ );
472
+ }
473
+
474
+ public async listFunctions(): Promise<Models.FunctionList> {
475
+ return await queryLimit(() =>
476
+ tryAwaitWithRetry(async () => await this.functions.list())
477
+ );
478
+ }
479
+
480
+ public async deleteFunction(functionId: string): Promise<void> {
481
+ await functionLimit(() =>
482
+ tryAwaitWithRetry(async () => await this.functions.delete(functionId))
483
+ );
484
+ }
485
+
486
+ /**
487
+ * Validate function configuration
488
+ */
489
+ public validateFunctionConfig(functionConfig: AppwriteFunction): { valid: boolean; errors: string[] } {
490
+ const errors: string[] = [];
491
+
492
+ if (!functionConfig.$id) {
493
+ errors.push("Function ID is required");
494
+ }
495
+
496
+ if (!functionConfig.name) {
497
+ errors.push("Function name is required");
498
+ }
499
+
500
+ if (!functionConfig.runtime) {
501
+ errors.push("Function runtime is required");
502
+ }
503
+
504
+ if (!functionConfig.entrypoint) {
505
+ errors.push("Function entrypoint is required");
506
+ }
507
+
508
+ // Validate timeout
509
+ if (functionConfig.timeout && (functionConfig.timeout < 1 || functionConfig.timeout > 900)) {
510
+ errors.push("Function timeout must be between 1 and 900 seconds");
511
+ }
512
+
513
+ return { valid: errors.length === 0, errors };
514
+ }
515
+ }