appwrite-cli 13.6.0 → 14.0.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 (92) hide show
  1. package/.github/workflows/ci.yml +66 -0
  2. package/CHANGELOG.md +14 -0
  3. package/README.md +2 -2
  4. package/cli.ts +3 -3
  5. package/dist/bundle-win-arm64.mjs +608 -310
  6. package/dist/cli.cjs +608 -310
  7. package/dist/index.cjs +354 -183
  8. package/dist/index.js +354 -183
  9. package/dist/lib/commands/config-validations.d.ts +1 -1
  10. package/dist/lib/commands/config-validations.d.ts.map +1 -1
  11. package/dist/lib/commands/errors.d.ts +4 -4
  12. package/dist/lib/commands/errors.d.ts.map +1 -1
  13. package/dist/lib/commands/generate.d.ts +2 -0
  14. package/dist/lib/commands/generate.d.ts.map +1 -1
  15. package/dist/lib/commands/generators/base.d.ts +25 -2
  16. package/dist/lib/commands/generators/base.d.ts.map +1 -1
  17. package/dist/lib/commands/generators/index.d.ts +1 -1
  18. package/dist/lib/commands/generators/index.d.ts.map +1 -1
  19. package/dist/lib/commands/generators/typescript/databases.d.ts +2 -2
  20. package/dist/lib/commands/generators/typescript/databases.d.ts.map +1 -1
  21. package/dist/lib/commands/generic.d.ts.map +1 -1
  22. package/dist/lib/commands/init.d.ts.map +1 -1
  23. package/dist/lib/commands/run.d.ts.map +1 -1
  24. package/dist/lib/commands/types.d.ts.map +1 -1
  25. package/dist/lib/commands/update.d.ts.map +1 -1
  26. package/dist/lib/commands/utils/change-approval.d.ts +3 -3
  27. package/dist/lib/commands/utils/change-approval.d.ts.map +1 -1
  28. package/dist/lib/commands/utils/database-sync.d.ts.map +1 -1
  29. package/dist/lib/commands/utils/deployment.d.ts +16 -4
  30. package/dist/lib/commands/utils/deployment.d.ts.map +1 -1
  31. package/dist/lib/commands/utils/pools.d.ts.map +1 -1
  32. package/dist/lib/constants.d.ts +1 -1
  33. package/dist/lib/emulation/docker.d.ts.map +1 -1
  34. package/dist/lib/json.d.ts +1 -1
  35. package/dist/lib/json.d.ts.map +1 -1
  36. package/dist/lib/paginate.d.ts +5 -6
  37. package/dist/lib/paginate.d.ts.map +1 -1
  38. package/dist/lib/parser.d.ts +5 -4
  39. package/dist/lib/parser.d.ts.map +1 -1
  40. package/dist/lib/spinner.d.ts +1 -1
  41. package/dist/lib/spinner.d.ts.map +1 -1
  42. package/dist/lib/utils.d.ts +6 -1
  43. package/dist/lib/utils.d.ts.map +1 -1
  44. package/dist/lib/validations.d.ts +1 -1
  45. package/dist/lib/validations.d.ts.map +1 -1
  46. package/docs/examples/projects/update-status.md +5 -0
  47. package/docs/examples/sites/create-deployment.md +1 -2
  48. package/eslint.config.js +45 -0
  49. package/install.ps1 +2 -2
  50. package/install.sh +1 -1
  51. package/lib/client.ts +3 -3
  52. package/lib/commands/config-validations.ts +1 -1
  53. package/lib/commands/config.ts +2 -2
  54. package/lib/commands/errors.ts +2 -2
  55. package/lib/commands/generate.ts +23 -8
  56. package/lib/commands/generators/base.ts +33 -2
  57. package/lib/commands/generators/index.ts +1 -0
  58. package/lib/commands/generators/typescript/databases.ts +31 -21
  59. package/lib/commands/generators/typescript/templates/databases.ts.hbs +16 -16
  60. package/lib/commands/generic.ts +21 -16
  61. package/lib/commands/init.ts +147 -61
  62. package/lib/commands/pull.ts +1 -1
  63. package/lib/commands/push.ts +19 -19
  64. package/lib/commands/run.ts +15 -9
  65. package/lib/commands/services/account.ts +1 -1
  66. package/lib/commands/services/databases.ts +20 -19
  67. package/lib/commands/services/health.ts +13 -0
  68. package/lib/commands/services/messaging.ts +1 -1
  69. package/lib/commands/services/projects.ts +25 -0
  70. package/lib/commands/services/sites.ts +8 -3
  71. package/lib/commands/services/tables-db.ts +3 -2
  72. package/lib/commands/services/teams.ts +2 -2
  73. package/lib/commands/types.ts +18 -8
  74. package/lib/commands/update.ts +24 -16
  75. package/lib/commands/utils/attributes.ts +6 -6
  76. package/lib/commands/utils/change-approval.ts +26 -19
  77. package/lib/commands/utils/database-sync.ts +58 -18
  78. package/lib/commands/utils/deployment.ts +22 -5
  79. package/lib/commands/utils/pools.ts +11 -5
  80. package/lib/config.ts +1 -1
  81. package/lib/constants.ts +1 -1
  82. package/lib/emulation/docker.ts +5 -6
  83. package/lib/emulation/utils.ts +2 -2
  84. package/lib/json.ts +15 -7
  85. package/lib/paginate.ts +30 -20
  86. package/lib/parser.ts +46 -15
  87. package/lib/questions.ts +38 -38
  88. package/lib/spinner.ts +5 -1
  89. package/lib/utils.ts +15 -3
  90. package/lib/validations.ts +1 -1
  91. package/package.json +8 -2
  92. package/scoop/appwrite.config.json +3 -3
package/dist/index.cjs CHANGED
@@ -1934,9 +1934,9 @@ var require_source = __commonJS({
1934
1934
  }
1935
1935
  });
1936
1936
 
1937
- // node_modules/escape-string-regexp/index.js
1937
+ // node_modules/figures/node_modules/escape-string-regexp/index.js
1938
1938
  var require_escape_string_regexp = __commonJS({
1939
- "node_modules/escape-string-regexp/index.js"(exports2, module2) {
1939
+ "node_modules/figures/node_modules/escape-string-regexp/index.js"(exports2, module2) {
1940
1940
  "use strict";
1941
1941
  var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
1942
1942
  module2.exports = function(str) {
@@ -19581,9 +19581,9 @@ var require_stream_duplex = __commonJS({
19581
19581
  }
19582
19582
  });
19583
19583
 
19584
- // node_modules/string_decoder/node_modules/safe-buffer/index.js
19584
+ // node_modules/safe-buffer/index.js
19585
19585
  var require_safe_buffer = __commonJS({
19586
- "node_modules/string_decoder/node_modules/safe-buffer/index.js"(exports2, module2) {
19586
+ "node_modules/safe-buffer/index.js"(exports2, module2) {
19587
19587
  var buffer = require("buffer");
19588
19588
  var Buffer2 = buffer.Buffer;
19589
19589
  function copyProps(src, dst) {
@@ -69377,7 +69377,7 @@ var id_default = ID;
69377
69377
  // lib/constants.ts
69378
69378
  var SDK_TITLE = "Appwrite";
69379
69379
  var SDK_TITLE_LOWER = "appwrite";
69380
- var SDK_VERSION = "13.6.0";
69380
+ var SDK_VERSION = "14.0.0";
69381
69381
  var SDK_LOGO = "\n _ _ _ ___ __ _____\n /_\\ _ __ _ ____ ___ __(_) |_ ___ / __\\ / / \\_ \\\n //_\\\\| '_ \\| '_ \\ \\ /\\ / / '__| | __/ _ \\ / / / / / /\\/\n / _ \\ |_) | |_) \\ V V /| | | | || __/ / /___/ /___/\\/ /_\n \\_/ \\_/ .__/| .__/ \\_/\\_/ |_| |_|\\__\\___| \\____/\\____/\\____/\n |_| |_|\n\n";
69382
69382
  var EXECUTABLE_NAME = "appwrite";
69383
69383
  var NPM_PACKAGE_NAME = "appwrite-cli";
@@ -83285,7 +83285,7 @@ var int64Schema = external_exports.preprocess(
83285
83285
  const valueOfResult = val.valueOf();
83286
83286
  const bigIntVal = BigInt(valueOfResult);
83287
83287
  return bigIntVal;
83288
- } catch (e) {
83288
+ } catch (_e) {
83289
83289
  return void 0;
83290
83290
  }
83291
83291
  }
@@ -83295,7 +83295,7 @@ var int64Schema = external_exports.preprocess(
83295
83295
  if (typeof val === "string") {
83296
83296
  try {
83297
83297
  return BigInt(val);
83298
- } catch (e) {
83298
+ } catch (_e) {
83299
83299
  return void 0;
83300
83300
  }
83301
83301
  }
@@ -83609,7 +83609,7 @@ var createSettingsObject = (project) => {
83609
83609
  };
83610
83610
  };
83611
83611
  var checkDeployConditions = (localConfig2) => {
83612
- if (Object.keys(localConfig2.data).length === 0) {
83612
+ if (localConfig2.keys().length === 0) {
83613
83613
  throw new Error(
83614
83614
  "No appwrite.config.json file found in the current directory. Please run this command again in the folder containing your appwrite.config.json file, or run 'appwrite init project' to link current directory to an Appwrite project."
83615
83615
  );
@@ -83757,7 +83757,7 @@ var Config = class {
83757
83757
  try {
83758
83758
  const file2 = import_fs.default.readFileSync(this.path).toString();
83759
83759
  this.data = JSONBig.parse(file2);
83760
- } catch (e) {
83760
+ } catch (_e) {
83761
83761
  this.data = {};
83762
83762
  }
83763
83763
  }
@@ -84668,7 +84668,7 @@ var Spinner = class _Spinner {
84668
84668
  static stop() {
84669
84669
  _Spinner.updatesBar.stop();
84670
84670
  }
84671
- static formatter(options, params, payload) {
84671
+ static formatter(_options, _params, payload) {
84672
84672
  const status = payload.status.padEnd(12);
84673
84673
  const middle = `${payload.resource} (${payload.id})`.padEnd(40);
84674
84674
  let prefix = import_chalk.default.cyan(payload.prefix ?? "\u29D7");
@@ -84739,19 +84739,22 @@ async function paginate(action, args = {}, limit = 100, wrapper = "", queries =
84739
84739
  ]
84740
84740
  });
84741
84741
  if (wrapper === "") {
84742
- if (response.length === 0) {
84742
+ const listResponse = response;
84743
+ if (listResponse.length === 0) {
84743
84744
  break;
84744
84745
  }
84745
- results = results.concat(response);
84746
+ results = results.concat(listResponse);
84746
84747
  } else {
84747
- if (response[wrapper].length === 0) {
84748
+ const wrappedResponse = response;
84749
+ const wrappedResults = wrappedResponse[wrapper] ?? [];
84750
+ if (wrappedResults.length === 0) {
84751
+ break;
84752
+ }
84753
+ results = results.concat(wrappedResults);
84754
+ total = wrappedResponse.total;
84755
+ if (results.length >= total) {
84748
84756
  break;
84749
84757
  }
84750
- results = results.concat(response[wrapper]);
84751
- }
84752
- total = response.total;
84753
- if (results.length >= total) {
84754
- break;
84755
84758
  }
84756
84759
  pageNumber++;
84757
84760
  }
@@ -84955,7 +84958,7 @@ var Client = class _Client {
84955
84958
  "x-sdk-name": "Console",
84956
84959
  "x-sdk-platform": "console",
84957
84960
  "x-sdk-language": "web",
84958
- "x-sdk-version": "3.1.0",
84961
+ "x-sdk-version": "4.0.0",
84959
84962
  "X-Appwrite-Response-Format": "1.8.0"
84960
84963
  };
84961
84964
  this.realtime = {
@@ -87693,6 +87696,47 @@ var Databases = class {
87693
87696
  };
87694
87697
  return this.client.call("post", uri, apiHeaders, payload);
87695
87698
  }
87699
+ updateRelationshipAttribute(paramsOrFirst, ...rest) {
87700
+ let params;
87701
+ if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
87702
+ params = paramsOrFirst || {};
87703
+ } else {
87704
+ params = {
87705
+ databaseId: paramsOrFirst,
87706
+ collectionId: rest[0],
87707
+ key: rest[1],
87708
+ onDelete: rest[2],
87709
+ newKey: rest[3]
87710
+ };
87711
+ }
87712
+ const databaseId = params.databaseId;
87713
+ const collectionId = params.collectionId;
87714
+ const key = params.key;
87715
+ const onDelete = params.onDelete;
87716
+ const newKey = params.newKey;
87717
+ if (typeof databaseId === "undefined") {
87718
+ throw new AppwriteException('Missing required parameter: "databaseId"');
87719
+ }
87720
+ if (typeof collectionId === "undefined") {
87721
+ throw new AppwriteException('Missing required parameter: "collectionId"');
87722
+ }
87723
+ if (typeof key === "undefined") {
87724
+ throw new AppwriteException('Missing required parameter: "key"');
87725
+ }
87726
+ const apiPath = "/databases/{databaseId}/collections/{collectionId}/attributes/relationship/{key}".replace("{databaseId}", databaseId).replace("{collectionId}", collectionId).replace("{key}", key);
87727
+ const payload = {};
87728
+ if (typeof onDelete !== "undefined") {
87729
+ payload["onDelete"] = onDelete;
87730
+ }
87731
+ if (typeof newKey !== "undefined") {
87732
+ payload["newKey"] = newKey;
87733
+ }
87734
+ const uri = new URL(this.client.config.endpoint + apiPath);
87735
+ const apiHeaders = {
87736
+ "content-type": "application/json"
87737
+ };
87738
+ return this.client.call("patch", uri, apiHeaders, payload);
87739
+ }
87696
87740
  createStringAttribute(paramsOrFirst, ...rest) {
87697
87741
  let params;
87698
87742
  if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
@@ -88210,47 +88254,6 @@ var Databases = class {
88210
88254
  };
88211
88255
  return this.client.call("delete", uri, apiHeaders, payload);
88212
88256
  }
88213
- updateRelationshipAttribute(paramsOrFirst, ...rest) {
88214
- let params;
88215
- if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
88216
- params = paramsOrFirst || {};
88217
- } else {
88218
- params = {
88219
- databaseId: paramsOrFirst,
88220
- collectionId: rest[0],
88221
- key: rest[1],
88222
- onDelete: rest[2],
88223
- newKey: rest[3]
88224
- };
88225
- }
88226
- const databaseId = params.databaseId;
88227
- const collectionId = params.collectionId;
88228
- const key = params.key;
88229
- const onDelete = params.onDelete;
88230
- const newKey = params.newKey;
88231
- if (typeof databaseId === "undefined") {
88232
- throw new AppwriteException('Missing required parameter: "databaseId"');
88233
- }
88234
- if (typeof collectionId === "undefined") {
88235
- throw new AppwriteException('Missing required parameter: "collectionId"');
88236
- }
88237
- if (typeof key === "undefined") {
88238
- throw new AppwriteException('Missing required parameter: "key"');
88239
- }
88240
- const apiPath = "/databases/{databaseId}/collections/{collectionId}/attributes/{key}/relationship".replace("{databaseId}", databaseId).replace("{collectionId}", collectionId).replace("{key}", key);
88241
- const payload = {};
88242
- if (typeof onDelete !== "undefined") {
88243
- payload["onDelete"] = onDelete;
88244
- }
88245
- if (typeof newKey !== "undefined") {
88246
- payload["newKey"] = newKey;
88247
- }
88248
- const uri = new URL(this.client.config.endpoint + apiPath);
88249
- const apiHeaders = {
88250
- "content-type": "application/json"
88251
- };
88252
- return this.client.call("patch", uri, apiHeaders, payload);
88253
- }
88254
88257
  listDocuments(paramsOrFirst, ...rest) {
88255
88258
  let params;
88256
88259
  if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
@@ -88261,7 +88264,8 @@ var Databases = class {
88261
88264
  collectionId: rest[0],
88262
88265
  queries: rest[1],
88263
88266
  transactionId: rest[2],
88264
- total: rest[3]
88267
+ total: rest[3],
88268
+ ttl: rest[4]
88265
88269
  };
88266
88270
  }
88267
88271
  const databaseId = params.databaseId;
@@ -88269,6 +88273,7 @@ var Databases = class {
88269
88273
  const queries = params.queries;
88270
88274
  const transactionId = params.transactionId;
88271
88275
  const total = params.total;
88276
+ const ttl = params.ttl;
88272
88277
  if (typeof databaseId === "undefined") {
88273
88278
  throw new AppwriteException('Missing required parameter: "databaseId"');
88274
88279
  }
@@ -88286,6 +88291,9 @@ var Databases = class {
88286
88291
  if (typeof total !== "undefined") {
88287
88292
  payload["total"] = total;
88288
88293
  }
88294
+ if (typeof ttl !== "undefined") {
88295
+ payload["ttl"] = ttl;
88296
+ }
88289
88297
  const uri = new URL(this.client.config.endpoint + apiPath);
88290
88298
  const apiHeaders = {};
88291
88299
  return this.client.call("get", uri, apiHeaders, payload);
@@ -94851,6 +94859,27 @@ var Projects = class {
94851
94859
  };
94852
94860
  return this.client.call("patch", uri, apiHeaders, payload);
94853
94861
  }
94862
+ updateConsoleAccess(paramsOrFirst) {
94863
+ let params;
94864
+ if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
94865
+ params = paramsOrFirst || {};
94866
+ } else {
94867
+ params = {
94868
+ projectId: paramsOrFirst
94869
+ };
94870
+ }
94871
+ const projectId = params.projectId;
94872
+ if (typeof projectId === "undefined") {
94873
+ throw new AppwriteException('Missing required parameter: "projectId"');
94874
+ }
94875
+ const apiPath = "/projects/{projectId}/console-access".replace("{projectId}", projectId);
94876
+ const payload = {};
94877
+ const uri = new URL(this.client.config.endpoint + apiPath);
94878
+ const apiHeaders = {
94879
+ "content-type": "application/json"
94880
+ };
94881
+ return this.client.call("patch", uri, apiHeaders, payload);
94882
+ }
94854
94883
  listDevKeys(paramsOrFirst, ...rest) {
94855
94884
  let params;
94856
94885
  if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
@@ -95927,6 +95956,35 @@ var Projects = class {
95927
95956
  };
95928
95957
  return this.client.call("post", uri, apiHeaders, payload);
95929
95958
  }
95959
+ updateStatus(paramsOrFirst, ...rest) {
95960
+ let params;
95961
+ if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
95962
+ params = paramsOrFirst || {};
95963
+ } else {
95964
+ params = {
95965
+ projectId: paramsOrFirst,
95966
+ status: rest[0]
95967
+ };
95968
+ }
95969
+ const projectId = params.projectId;
95970
+ const status = params.status;
95971
+ if (typeof projectId === "undefined") {
95972
+ throw new AppwriteException('Missing required parameter: "projectId"');
95973
+ }
95974
+ if (typeof status === "undefined") {
95975
+ throw new AppwriteException('Missing required parameter: "status"');
95976
+ }
95977
+ const apiPath = "/projects/{projectId}/status".replace("{projectId}", projectId);
95978
+ const payload = {};
95979
+ if (typeof status !== "undefined") {
95980
+ payload["status"] = status;
95981
+ }
95982
+ const uri = new URL(this.client.config.endpoint + apiPath);
95983
+ const apiHeaders = {
95984
+ "content-type": "application/json"
95985
+ };
95986
+ return this.client.call("patch", uri, apiHeaders, payload);
95987
+ }
95930
95988
  updateTeam(paramsOrFirst, ...rest) {
95931
95989
  let params;
95932
95990
  if (paramsOrFirst && typeof paramsOrFirst === "object" && !Array.isArray(paramsOrFirst)) {
@@ -97241,28 +97299,25 @@ var Sites = class {
97241
97299
  params = {
97242
97300
  siteId: paramsOrFirst,
97243
97301
  code: rest[0],
97244
- activate: rest[1],
97245
- installCommand: rest[2],
97246
- buildCommand: rest[3],
97247
- outputDirectory: rest[4]
97302
+ installCommand: rest[1],
97303
+ buildCommand: rest[2],
97304
+ outputDirectory: rest[3],
97305
+ activate: rest[4]
97248
97306
  };
97249
97307
  onProgress = rest[5];
97250
97308
  }
97251
97309
  const siteId = params.siteId;
97252
97310
  const code = params.code;
97253
- const activate = params.activate;
97254
97311
  const installCommand = params.installCommand;
97255
97312
  const buildCommand = params.buildCommand;
97256
97313
  const outputDirectory = params.outputDirectory;
97314
+ const activate = params.activate;
97257
97315
  if (typeof siteId === "undefined") {
97258
97316
  throw new AppwriteException('Missing required parameter: "siteId"');
97259
97317
  }
97260
97318
  if (typeof code === "undefined") {
97261
97319
  throw new AppwriteException('Missing required parameter: "code"');
97262
97320
  }
97263
- if (typeof activate === "undefined") {
97264
- throw new AppwriteException('Missing required parameter: "activate"');
97265
- }
97266
97321
  const apiPath = "/sites/{siteId}/deployments".replace("{siteId}", siteId);
97267
97322
  const payload = {};
97268
97323
  if (typeof installCommand !== "undefined") {
@@ -101000,7 +101055,8 @@ var TablesDB = class {
101000
101055
  tableId: rest[0],
101001
101056
  queries: rest[1],
101002
101057
  transactionId: rest[2],
101003
- total: rest[3]
101058
+ total: rest[3],
101059
+ ttl: rest[4]
101004
101060
  };
101005
101061
  }
101006
101062
  const databaseId = params.databaseId;
@@ -101008,6 +101064,7 @@ var TablesDB = class {
101008
101064
  const queries = params.queries;
101009
101065
  const transactionId = params.transactionId;
101010
101066
  const total = params.total;
101067
+ const ttl = params.ttl;
101011
101068
  if (typeof databaseId === "undefined") {
101012
101069
  throw new AppwriteException('Missing required parameter: "databaseId"');
101013
101070
  }
@@ -101025,6 +101082,9 @@ var TablesDB = class {
101025
101082
  if (typeof total !== "undefined") {
101026
101083
  payload["total"] = total;
101027
101084
  }
101085
+ if (typeof ttl !== "undefined") {
101086
+ payload["ttl"] = ttl;
101087
+ }
101028
101088
  const uri = new URL(this.client.config.endpoint + apiPath);
101029
101089
  const apiHeaders = {};
101030
101090
  return this.client.call("get", uri, apiHeaders, payload);
@@ -103336,20 +103396,69 @@ var SmtpEncryption;
103336
103396
  SmtpEncryption2["Ssl"] = "ssl";
103337
103397
  SmtpEncryption2["Tls"] = "tls";
103338
103398
  })(SmtpEncryption || (SmtpEncryption = {}));
103339
- var Resources;
103340
- (function(Resources2) {
103341
- Resources2["User"] = "user";
103342
- Resources2["Database"] = "database";
103343
- Resources2["Table"] = "table";
103344
- Resources2["Column"] = "column";
103345
- Resources2["Index"] = "index";
103346
- Resources2["Row"] = "row";
103347
- Resources2["Document"] = "document";
103348
- Resources2["Attribute"] = "attribute";
103349
- Resources2["Collection"] = "collection";
103350
- Resources2["Bucket"] = "bucket";
103351
- Resources2["File"] = "file";
103352
- })(Resources || (Resources = {}));
103399
+ var AppwriteMigrationResource;
103400
+ (function(AppwriteMigrationResource2) {
103401
+ AppwriteMigrationResource2["User"] = "user";
103402
+ AppwriteMigrationResource2["Team"] = "team";
103403
+ AppwriteMigrationResource2["Membership"] = "membership";
103404
+ AppwriteMigrationResource2["Database"] = "database";
103405
+ AppwriteMigrationResource2["Table"] = "table";
103406
+ AppwriteMigrationResource2["Column"] = "column";
103407
+ AppwriteMigrationResource2["Index"] = "index";
103408
+ AppwriteMigrationResource2["Row"] = "row";
103409
+ AppwriteMigrationResource2["Document"] = "document";
103410
+ AppwriteMigrationResource2["Attribute"] = "attribute";
103411
+ AppwriteMigrationResource2["Collection"] = "collection";
103412
+ AppwriteMigrationResource2["Bucket"] = "bucket";
103413
+ AppwriteMigrationResource2["File"] = "file";
103414
+ AppwriteMigrationResource2["Function"] = "function";
103415
+ AppwriteMigrationResource2["Deployment"] = "deployment";
103416
+ AppwriteMigrationResource2["Environmentvariable"] = "environment-variable";
103417
+ AppwriteMigrationResource2["Site"] = "site";
103418
+ AppwriteMigrationResource2["Sitedeployment"] = "site-deployment";
103419
+ AppwriteMigrationResource2["Sitevariable"] = "site-variable";
103420
+ })(AppwriteMigrationResource || (AppwriteMigrationResource = {}));
103421
+ var FirebaseMigrationResource;
103422
+ (function(FirebaseMigrationResource2) {
103423
+ FirebaseMigrationResource2["User"] = "user";
103424
+ FirebaseMigrationResource2["Database"] = "database";
103425
+ FirebaseMigrationResource2["Table"] = "table";
103426
+ FirebaseMigrationResource2["Column"] = "column";
103427
+ FirebaseMigrationResource2["Row"] = "row";
103428
+ FirebaseMigrationResource2["Document"] = "document";
103429
+ FirebaseMigrationResource2["Attribute"] = "attribute";
103430
+ FirebaseMigrationResource2["Collection"] = "collection";
103431
+ FirebaseMigrationResource2["Bucket"] = "bucket";
103432
+ FirebaseMigrationResource2["File"] = "file";
103433
+ })(FirebaseMigrationResource || (FirebaseMigrationResource = {}));
103434
+ var NHostMigrationResource;
103435
+ (function(NHostMigrationResource2) {
103436
+ NHostMigrationResource2["User"] = "user";
103437
+ NHostMigrationResource2["Database"] = "database";
103438
+ NHostMigrationResource2["Table"] = "table";
103439
+ NHostMigrationResource2["Column"] = "column";
103440
+ NHostMigrationResource2["Index"] = "index";
103441
+ NHostMigrationResource2["Row"] = "row";
103442
+ NHostMigrationResource2["Document"] = "document";
103443
+ NHostMigrationResource2["Attribute"] = "attribute";
103444
+ NHostMigrationResource2["Collection"] = "collection";
103445
+ NHostMigrationResource2["Bucket"] = "bucket";
103446
+ NHostMigrationResource2["File"] = "file";
103447
+ })(NHostMigrationResource || (NHostMigrationResource = {}));
103448
+ var SupabaseMigrationResource;
103449
+ (function(SupabaseMigrationResource2) {
103450
+ SupabaseMigrationResource2["User"] = "user";
103451
+ SupabaseMigrationResource2["Database"] = "database";
103452
+ SupabaseMigrationResource2["Table"] = "table";
103453
+ SupabaseMigrationResource2["Column"] = "column";
103454
+ SupabaseMigrationResource2["Index"] = "index";
103455
+ SupabaseMigrationResource2["Row"] = "row";
103456
+ SupabaseMigrationResource2["Document"] = "document";
103457
+ SupabaseMigrationResource2["Attribute"] = "attribute";
103458
+ SupabaseMigrationResource2["Collection"] = "collection";
103459
+ SupabaseMigrationResource2["Bucket"] = "bucket";
103460
+ SupabaseMigrationResource2["File"] = "file";
103461
+ })(SupabaseMigrationResource || (SupabaseMigrationResource = {}));
103353
103462
  var ProjectUsageRange;
103354
103463
  (function(ProjectUsageRange2) {
103355
103464
  ProjectUsageRange2["OneHour"] = "1h";
@@ -103426,6 +103535,10 @@ var SMTPSecure;
103426
103535
  SMTPSecure2["Tls"] = "tls";
103427
103536
  SMTPSecure2["Ssl"] = "ssl";
103428
103537
  })(SMTPSecure || (SMTPSecure = {}));
103538
+ var Status;
103539
+ (function(Status2) {
103540
+ Status2["Active"] = "active";
103541
+ })(Status || (Status = {}));
103429
103542
  var EmailTemplateType;
103430
103543
  (function(EmailTemplateType2) {
103431
103544
  EmailTemplateType2["Verification"] = "verification";
@@ -103985,6 +104098,17 @@ var BillingPlanGroup;
103985
104098
  BillingPlanGroup2["Pro"] = "pro";
103986
104099
  BillingPlanGroup2["Scale"] = "scale";
103987
104100
  })(BillingPlanGroup || (BillingPlanGroup = {}));
104101
+ var DomainTransferStatusStatus;
104102
+ (function(DomainTransferStatusStatus2) {
104103
+ DomainTransferStatusStatus2["Transferrable"] = "transferrable";
104104
+ DomainTransferStatusStatus2["NotTransferrable"] = "not_transferrable";
104105
+ DomainTransferStatusStatus2["PendingOwner"] = "pending_owner";
104106
+ DomainTransferStatusStatus2["PendingAdmin"] = "pending_admin";
104107
+ DomainTransferStatusStatus2["PendingRegistry"] = "pending_registry";
104108
+ DomainTransferStatusStatus2["Completed"] = "completed";
104109
+ DomainTransferStatusStatus2["Cancelled"] = "cancelled";
104110
+ DomainTransferStatusStatus2["ServiceUnavailable"] = "service_unavailable";
104111
+ })(DomainTransferStatusStatus || (DomainTransferStatusStatus = {}));
103988
104112
 
103989
104113
  // lib/parser.ts
103990
104114
  var import_chalk2 = __toESM(require_source(), 1);
@@ -103996,7 +104120,7 @@ var package_default = {
103996
104120
  type: "module",
103997
104121
  homepage: "https://appwrite.io/support",
103998
104122
  description: "Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API",
103999
- version: "13.6.0",
104123
+ version: "14.0.0",
104000
104124
  license: "BSD-3-Clause",
104001
104125
  main: "dist/index.cjs",
104002
104126
  module: "dist/index.js",
@@ -104027,6 +104151,7 @@ var package_default = {
104027
104151
  "build:lib:esm": "esbuild index.ts --bundle --platform=node --target=node18 --format=esm --loader:.hbs=text --outfile=dist/index.js",
104028
104152
  "build:lib:cjs": "esbuild index.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --outfile=dist/index.cjs",
104029
104153
  "build:cli": "esbuild cli.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --external:fsevents --outfile=dist/cli.cjs",
104154
+ lint: "eslint .",
104030
104155
  format: 'prettier --write "**/*.{js,ts,json,md}"',
104031
104156
  generate: "tsx scripts/generate-commands.ts",
104032
104157
  prepublishOnly: "npm run build",
@@ -104039,7 +104164,7 @@ var package_default = {
104039
104164
  "windows-arm64": "esbuild cli.ts --bundle --loader:.hbs=text --platform=node --target=node18 --format=esm --external:fsevents --outfile=dist/bundle-win-arm64.mjs && pkg dist/bundle-win-arm64.mjs -t node18-win-arm64 -o build/appwrite-cli-win-arm64.exe"
104040
104165
  },
104041
104166
  dependencies: {
104042
- "@appwrite.io/console": "^3.1.0",
104167
+ "@appwrite.io/console": "^4.0.0",
104043
104168
  chalk: "4.1.2",
104044
104169
  chokidar: "^3.6.0",
104045
104170
  "cli-progress": "^3.12.0",
@@ -104058,7 +104183,12 @@ var package_default = {
104058
104183
  zod: "^4.3.5"
104059
104184
  },
104060
104185
  devDependencies: {
104186
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
104187
+ "@typescript-eslint/parser": "^8.0.0",
104061
104188
  "@types/bun": "^1.3.5",
104189
+ eslint: "^9.0.0",
104190
+ "eslint-plugin-unused-imports": "^4.0.0",
104191
+ "typescript-eslint": "^8.0.0",
104062
104192
  "@types/cli-progress": "^3.11.5",
104063
104193
  "@types/inquirer": "^8.2.10",
104064
104194
  "@types/json-bigint": "^1.0.4",
@@ -104090,14 +104220,28 @@ var cliConfig = {
104090
104220
  report: false,
104091
104221
  reportData: {}
104092
104222
  };
104223
+ var toJsonObject = (value) => {
104224
+ if (value && typeof value === "object" && !Array.isArray(value)) {
104225
+ return value;
104226
+ }
104227
+ return null;
104228
+ };
104229
+ var extractReportCommandArgs = (value) => {
104230
+ if (!value || typeof value !== "object") {
104231
+ return [];
104232
+ }
104233
+ const reportData = value;
104234
+ if (!Array.isArray(reportData.data?.args)) {
104235
+ return [];
104236
+ }
104237
+ return reportData.data.args;
104238
+ };
104093
104239
  var drawTable = (data) => {
104094
104240
  if (data.length == 0) {
104095
104241
  console.log("[]");
104096
104242
  return;
104097
104243
  }
104098
- const rows = data.map(
104099
- (item) => item && typeof item === "object" && !Array.isArray(item) ? item : {}
104100
- );
104244
+ const rows = data.map((item) => toJsonObject(item) ?? {});
104101
104245
  const obj = rows.reduce((res, item) => ({ ...res, ...item }), {});
104102
104246
  const keys = Object.keys(obj);
104103
104247
  if (keys.length === 0) {
@@ -104140,7 +104284,7 @@ var drawTable = (data) => {
104140
104284
  } else if (typeof row[key] === "object") {
104141
104285
  rowValues.push(JSON.stringify(row[key]));
104142
104286
  } else {
104143
- rowValues.push(row[key]);
104287
+ rowValues.push(String(row[key]));
104144
104288
  }
104145
104289
  }
104146
104290
  table.push(rowValues);
@@ -104152,7 +104296,7 @@ var drawJSON = (data) => {
104152
104296
  };
104153
104297
  var parseError = (err) => {
104154
104298
  if (cliConfig.report) {
104155
- (async () => {
104299
+ void (async () => {
104156
104300
  let appwriteVersion = "unknown";
104157
104301
  const endpoint = globalConfig2.getEndpoint();
104158
104302
  try {
@@ -104165,7 +104309,8 @@ var parseError = (err) => {
104165
104309
  } catch {
104166
104310
  }
104167
104311
  const version2 = SDK_VERSION;
104168
- const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${cliConfig.reportData.data.args.join(" ")}\``;
104312
+ const commandArgs = extractReportCommandArgs(cliConfig.reportData);
104313
+ const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${commandArgs.join(" ")}\``;
104169
104314
  const yourEnvironment = `CLI version: ${version2}
104170
104315
  Operation System: ${import_os2.default.type()}
104171
104316
  Appwrite version: ${appwriteVersion}
@@ -104217,7 +104362,7 @@ var actionRunner = (fn) => {
104217
104362
  error48(`The '--all' and '--id' flags cannot be used together.`);
104218
104363
  process.exit(1);
104219
104364
  }
104220
- return fn(...args).catch(parseError);
104365
+ return fn(...args).then(() => void 0).catch(parseError);
104221
104366
  };
104222
104367
  };
104223
104368
  var log = (message) => {
@@ -104330,6 +104475,9 @@ async function downloadDeploymentCode(params) {
104330
104475
  {},
104331
104476
  "arrayBuffer"
104332
104477
  );
104478
+ if (!(downloadBuffer instanceof ArrayBuffer)) {
104479
+ throw new Error("Failed to download deployment archive as ArrayBuffer.");
104480
+ }
104333
104481
  try {
104334
104482
  import_fs2.default.writeFileSync(compressedFileName, Buffer.from(downloadBuffer));
104335
104483
  } catch (err) {
@@ -104541,7 +104689,7 @@ var questionsInitProject = [
104541
104689
  name: "organization",
104542
104690
  message: "Choose your organization",
104543
104691
  choices: async () => {
104544
- let client = await sdkForConsole(true);
104692
+ const client = await sdkForConsole(true);
104545
104693
  const { teams } = isCloud() ? await paginate(
104546
104694
  async (opts = {}) => (await getOrganizationsService(opts.sdk)).list(),
104547
104695
  { sdk: client },
@@ -104553,7 +104701,7 @@ var questionsInitProject = [
104553
104701
  100,
104554
104702
  "teams"
104555
104703
  );
104556
- let choices = teams.map((team, idx) => {
104704
+ const choices = teams.map((team, _idx) => {
104557
104705
  return {
104558
104706
  name: `${team.name} (${team["$id"]})`,
104559
104707
  value: team["$id"]
@@ -104602,7 +104750,7 @@ var questionsInitProject = [
104602
104750
  "projects",
104603
104751
  queries
104604
104752
  );
104605
- let choices = projects.map((project) => {
104753
+ const choices = projects.map((project) => {
104606
104754
  return {
104607
104755
  name: `${project.name} (${project["$id"]})`,
104608
104756
  value: {
@@ -104623,13 +104771,13 @@ var questionsInitProject = [
104623
104771
  name: "region",
104624
104772
  message: `Select your ${SDK_TITLE} Cloud region`,
104625
104773
  choices: async () => {
104626
- let client = await sdkForConsole(true);
104774
+ const client = await sdkForConsole(true);
104627
104775
  const endpoint = globalConfig2.getEndpoint() || DEFAULT_ENDPOINT;
104628
- let response = await client.call(
104776
+ const response = await client.call(
104629
104777
  "GET",
104630
104778
  new URL(endpoint + "/console/regions")
104631
104779
  );
104632
- let regions = response.regions || [];
104780
+ const regions = response.regions || [];
104633
104781
  if (!regions.length) {
104634
104782
  throw new Error(
104635
104783
  "No regions found. Please check your network or Appwrite Cloud availability."
@@ -104756,9 +104904,9 @@ var questionGetEndpoint = [
104756
104904
  if (!value) {
104757
104905
  return "Please enter a valid endpoint.";
104758
104906
  }
104759
- let client = new Client().setEndpoint(value);
104907
+ const client = new Client().setEndpoint(value);
104760
104908
  try {
104761
- let response = await client.call(
104909
+ const response = await client.call(
104762
104910
  "get",
104763
104911
  new URL(value + "/health/version")
104764
104912
  );
@@ -104767,7 +104915,7 @@ var questionGetEndpoint = [
104767
104915
  } else {
104768
104916
  throw new Error();
104769
104917
  }
104770
- } catch (error49) {
104918
+ } catch (_error) {
104771
104919
  return "Invalid endpoint or your Appwrite server is not running as expected.";
104772
104920
  }
104773
104921
  }
@@ -104803,9 +104951,9 @@ var questionsPushSites = [
104803
104951
  validate: (value) => validateRequired("site", value),
104804
104952
  when: () => localConfig.getSites().length > 0,
104805
104953
  choices: () => {
104806
- let sites = localConfig.getSites();
104954
+ const sites = localConfig.getSites();
104807
104955
  checkDeployConditions(localConfig);
104808
- let choices = sites.map((site, idx) => {
104956
+ const choices = sites.map((site, _idx) => {
104809
104957
  return {
104810
104958
  name: `${site.name} (${site.$id})`,
104811
104959
  value: site.$id
@@ -104823,9 +104971,9 @@ var questionsPushFunctions = [
104823
104971
  validate: (value) => validateRequired("function", value),
104824
104972
  when: () => localConfig.getFunctions().length > 0,
104825
104973
  choices: () => {
104826
- let functions = localConfig.getFunctions();
104974
+ const functions = localConfig.getFunctions();
104827
104975
  checkDeployConditions(localConfig);
104828
- let choices = functions.map((func, idx) => {
104976
+ const choices = functions.map((func, _idx) => {
104829
104977
  return {
104830
104978
  name: `${func.name} (${func.$id})`,
104831
104979
  value: func.$id
@@ -104843,7 +104991,7 @@ var questionsPushCollections = [
104843
104991
  validate: (value) => validateRequired("collection", value),
104844
104992
  when: () => localConfig.getCollections().length > 0,
104845
104993
  choices: () => {
104846
- let collections = localConfig.getCollections();
104994
+ const collections = localConfig.getCollections();
104847
104995
  checkDeployConditions(localConfig);
104848
104996
  return collections.map((collection) => {
104849
104997
  return {
@@ -104862,7 +105010,7 @@ var questionsPushTables = [
104862
105010
  validate: (value) => validateRequired("table", value),
104863
105011
  when: () => localConfig.getTables().length > 0,
104864
105012
  choices: () => {
104865
- let tables = localConfig.getTables();
105013
+ const tables = localConfig.getTables();
104866
105014
  checkDeployConditions(localConfig);
104867
105015
  return tables.map((table) => {
104868
105016
  return {
@@ -104895,7 +105043,7 @@ var questionsPushBuckets = [
104895
105043
  validate: (value) => validateRequired("bucket", value),
104896
105044
  when: () => localConfig.getBuckets().length > 0,
104897
105045
  choices: () => {
104898
- let buckets = localConfig.getBuckets();
105046
+ const buckets = localConfig.getBuckets();
104899
105047
  checkDeployConditions(localConfig);
104900
105048
  return buckets.map((bucket) => {
104901
105049
  return {
@@ -104914,7 +105062,7 @@ var questionsPushMessagingTopics = [
104914
105062
  validate: (value) => validateRequired("topics", value),
104915
105063
  when: () => localConfig.getMessagingTopics().length > 0,
104916
105064
  choices: () => {
104917
- let topics = localConfig.getMessagingTopics();
105065
+ const topics = localConfig.getMessagingTopics();
104918
105066
  return topics.map((topic) => {
104919
105067
  return {
104920
105068
  name: `${topic.name} (${topic["$id"]})`,
@@ -104945,7 +105093,7 @@ var questionsPushTeams = [
104945
105093
  validate: (value) => validateRequired("team", value),
104946
105094
  when: () => localConfig.getTeams().length > 0,
104947
105095
  choices: () => {
104948
- let teams = localConfig.getTeams();
105096
+ const teams = localConfig.getTeams();
104949
105097
  checkDeployConditions(localConfig);
104950
105098
  return teams.map((team) => {
104951
105099
  return {
@@ -104987,7 +105135,7 @@ var Pools = class {
104987
105135
  return true;
104988
105136
  }
104989
105137
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
104990
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
105138
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
104991
105139
  if (steps > 1 && iteration === 1) {
104992
105140
  this.pollMaxDebounces *= steps;
104993
105141
  log(
@@ -105013,7 +105161,7 @@ var Pools = class {
105013
105161
  return true;
105014
105162
  }
105015
105163
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105016
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
105164
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
105017
105165
  if (steps > 1 && iteration === 1) {
105018
105166
  this.pollMaxDebounces *= steps;
105019
105167
  log(
@@ -105029,7 +105177,10 @@ var Pools = class {
105029
105177
  return false;
105030
105178
  }
105031
105179
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105032
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
105180
+ const steps = Math.max(
105181
+ 1,
105182
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
105183
+ );
105033
105184
  if (steps > 1 && iteration === 1) {
105034
105185
  this.pollMaxDebounces *= steps;
105035
105186
  log(
@@ -105072,7 +105223,10 @@ var Pools = class {
105072
105223
  return false;
105073
105224
  }
105074
105225
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105075
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
105226
+ const steps = Math.max(
105227
+ 1,
105228
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
105229
+ );
105076
105230
  if (steps > 1 && iteration === 1) {
105077
105231
  this.pollMaxDebounces *= steps;
105078
105232
  log(
@@ -105121,7 +105275,7 @@ var Pools = class {
105121
105275
  return false;
105122
105276
  }
105123
105277
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105124
- let steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
105278
+ const steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
105125
105279
  if (steps > 1 && iteration === 1) {
105126
105280
  this.pollMaxDebounces *= steps;
105127
105281
  log(
@@ -105214,7 +105368,7 @@ var Attributes = class {
105214
105368
  }
105215
105369
  return answers2.changes;
105216
105370
  }
105217
- let answers = await import_inquirer.default.prompt(questionPushChanges2);
105371
+ const answers = await import_inquirer.default.prompt(questionPushChanges2);
105218
105372
  if (answers.changes !== "YES" && answers.changes !== "NO") {
105219
105373
  answers.changes = await fixConfirmation();
105220
105374
  }
@@ -105257,8 +105411,8 @@ var Attributes = class {
105257
105411
  const keyName = `${import_chalk4.default.yellow(local.key)} in ${collection.name} (${collection["$id"]})`;
105258
105412
  const action = import_chalk4.default.cyan(recreating ? "recreating" : "changing");
105259
105413
  let reason = "";
105260
- let attribute = recreating ? remote : local;
105261
- for (let key of Object.keys(remote)) {
105414
+ const attribute = recreating ? remote : local;
105415
+ for (const key of Object.keys(remote)) {
105262
105416
  if (!KeysAttributes.has(key)) {
105263
105417
  continue;
105264
105418
  }
@@ -105768,7 +105922,7 @@ var Attributes = class {
105768
105922
  createIndexes = async (indexes, collection) => {
105769
105923
  log(`Creating indexes ...`);
105770
105924
  const databasesService = await getDatabasesService(this.client);
105771
- for (let index of indexes) {
105925
+ for (const index of indexes) {
105772
105926
  await databasesService.createIndex({
105773
105927
  databaseId: collection["databaseId"],
105774
105928
  collectionId: collection["$id"],
@@ -105792,7 +105946,7 @@ var Attributes = class {
105792
105946
  };
105793
105947
  createAttributes = async (attributes, collection) => {
105794
105948
  log(`Creating attributes ...`);
105795
- for (let attribute of attributes) {
105949
+ for (const attribute of attributes) {
105796
105950
  if (attribute.side !== "child") {
105797
105951
  await this.createAttribute(
105798
105952
  collection["databaseId"],
@@ -105816,7 +105970,7 @@ var Attributes = class {
105816
105970
  };
105817
105971
  createColumns = async (columns, table) => {
105818
105972
  log(`Creating columns ...`);
105819
- for (let column of columns) {
105973
+ for (const column of columns) {
105820
105974
  if (column.side !== "child") {
105821
105975
  await this.createAttribute(table["databaseId"], table["$id"], column);
105822
105976
  }
@@ -105851,7 +106005,7 @@ var getConfirmation = async () => {
105851
106005
  }
105852
106006
  return answers2.changes;
105853
106007
  }
105854
- let answers = await import_inquirer2.default.prompt(questionPushChanges);
106008
+ const answers = await import_inquirer2.default.prompt(questionPushChanges);
105855
106009
  if (answers.changes !== "YES" && answers.changes !== "NO") {
105856
106010
  answers.changes = await fixConfirmation();
105857
106011
  }
@@ -105901,7 +106055,7 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105901
106055
  options[secondResourceName] = localResource[secondId];
105902
106056
  }
105903
106057
  const remoteResource = await resourceGetFunction(options);
105904
- for (let [key, value] of Object.entries(
106058
+ for (const [key, value] of Object.entries(
105905
106059
  whitelistKeys(remoteResource, keys)
105906
106060
  )) {
105907
106061
  if (skipKeys.includes(key)) {
@@ -105910,28 +106064,30 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105910
106064
  if (isEmpty(value) && isEmpty(localResource[key])) {
105911
106065
  continue;
105912
106066
  }
105913
- if (Array.isArray(value) && Array.isArray(localResource[key])) {
105914
- if (JSON.stringify(value) !== JSON.stringify(localResource[key])) {
106067
+ const localValue = localResource[key];
106068
+ if (Array.isArray(value) && Array.isArray(localValue)) {
106069
+ if (JSON.stringify(value) !== JSON.stringify(localValue)) {
105915
106070
  changes.push({
105916
106071
  id: localResource["$id"],
105917
106072
  key,
105918
106073
  remote: import_chalk5.default.red(value.join("\n")),
105919
- local: import_chalk5.default.green(localResource[key].join("\n"))
106074
+ local: import_chalk5.default.green(
106075
+ localValue.map((entry) => String(entry)).join("\n")
106076
+ )
105920
106077
  });
105921
106078
  }
105922
- } else if (value !== localResource[key]) {
106079
+ } else if (value !== localValue) {
105923
106080
  changes.push({
105924
106081
  id: localResource["$id"],
105925
106082
  key,
105926
- remote: import_chalk5.default.red(value),
105927
- local: import_chalk5.default.green(localResource[key])
106083
+ remote: import_chalk5.default.red(String(value ?? "")),
106084
+ local: import_chalk5.default.green(String(localValue ?? ""))
105928
106085
  });
105929
106086
  }
105930
106087
  }
105931
106088
  } catch (e) {
105932
- if (Number(e.code) !== 404) {
105933
- throw e;
105934
- }
106089
+ const isNotFound = e instanceof AppwriteException && Number(e.code) === 404;
106090
+ if (!isNotFound) throw e;
105935
106091
  }
105936
106092
  })
105937
106093
  );
@@ -105948,18 +106104,37 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105948
106104
 
105949
106105
  // lib/commands/utils/database-sync.ts
105950
106106
  var import_chalk6 = __toESM(require_source(), 1);
106107
+ var isTablesDBResource = (value) => {
106108
+ if (!value || typeof value !== "object") {
106109
+ return false;
106110
+ }
106111
+ return "$id" in value && typeof value.$id === "string" && "name" in value && typeof value.name === "string" && "enabled" in value && typeof value.enabled === "boolean";
106112
+ };
106113
+ var getSyncErrorMessage = (err) => {
106114
+ if (err instanceof AppwriteException) {
106115
+ return err.message;
106116
+ }
106117
+ if (err instanceof Error) {
106118
+ return err.message;
106119
+ }
106120
+ return String(err);
106121
+ };
105951
106122
  var checkAndApplyTablesDBChanges = async () => {
105952
106123
  log("Checking for tablesDB changes ...");
105953
106124
  const localTablesDBs = localConfig.getTablesDBs();
105954
- const { databases: remoteTablesDBs } = await paginate(
106125
+ const paginatedResult = await paginate(
105955
106126
  async (args) => {
105956
106127
  const tablesDBService = await getTablesDBService();
105957
- return await tablesDBService.list(args.queries || []);
106128
+ const queries = Array.isArray(args.queries) ? args.queries.filter(
106129
+ (query) => typeof query === "string"
106130
+ ) : [];
106131
+ return await tablesDBService.list(queries);
105958
106132
  },
105959
106133
  {},
105960
106134
  100,
105961
106135
  "databases"
105962
106136
  );
106137
+ const remoteTablesDBs = Array.isArray(paginatedResult.databases) ? paginatedResult.databases.filter(isTablesDBResource) : [];
105963
106138
  if (localTablesDBs.length === 0 && remoteTablesDBs.length === 0) {
105964
106139
  return { applied: false, resyncNeeded: false };
105965
106140
  }
@@ -105981,9 +106156,7 @@ var checkAndApplyTablesDBChanges = async () => {
105981
106156
  }
105982
106157
  }
105983
106158
  for (const localDB of localTablesDBs) {
105984
- const remoteDB = remoteTablesDBs.find(
105985
- (db) => db.$id === localDB.$id
105986
- );
106159
+ const remoteDB = remoteTablesDBs.find((db) => db.$id === localDB.$id);
105987
106160
  if (!remoteDB) {
105988
106161
  toCreate.push(localDB);
105989
106162
  changes.push({
@@ -106050,7 +106223,7 @@ var checkAndApplyTablesDBChanges = async () => {
106050
106223
  needsResync = true;
106051
106224
  } catch (e) {
106052
106225
  error48(
106053
- `Failed to delete database ${db.name} ( ${db.$id} ): ${e.message}`
106226
+ `Failed to delete database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106054
106227
  );
106055
106228
  throw new Error(
106056
106229
  `Database sync failed during deletion of ${db.$id}. Some changes may have been applied.`
@@ -106065,7 +106238,7 @@ var checkAndApplyTablesDBChanges = async () => {
106065
106238
  success2(`Created ${db.name} ( ${db.$id} )`);
106066
106239
  } catch (e) {
106067
106240
  error48(
106068
- `Failed to create database ${db.name} ( ${db.$id} ): ${e.message}`
106241
+ `Failed to create database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106069
106242
  );
106070
106243
  throw new Error(
106071
106244
  `Database sync failed during creation of ${db.$id}. Some changes may have been applied.`
@@ -106080,7 +106253,7 @@ var checkAndApplyTablesDBChanges = async () => {
106080
106253
  success2(`Updated ${db.name} ( ${db.$id} )`);
106081
106254
  } catch (e) {
106082
106255
  error48(
106083
- `Failed to update database ${db.name} ( ${db.$id} ): ${e.message}`
106256
+ `Failed to update database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106084
106257
  );
106085
106258
  throw new Error(
106086
106259
  `Database sync failed during update of ${db.$id}. Some changes may have been applied.`
@@ -106314,7 +106487,7 @@ var Push = class {
106314
106487
  }
106315
106488
  if (settings.services) {
106316
106489
  this.log("Applying service statuses ...");
106317
- for (let [service, status] of Object.entries(settings.services)) {
106490
+ for (const [service, status] of Object.entries(settings.services)) {
106318
106491
  await projectsService.updateServiceStatus({
106319
106492
  projectId,
106320
106493
  service,
@@ -106360,7 +106533,7 @@ var Push = class {
106360
106533
  }
106361
106534
  if (settings.auth.methods) {
106362
106535
  this.log("Applying auth methods statuses ...");
106363
- for (let [method, status] of Object.entries(settings.auth.methods)) {
106536
+ for (const [method, status] of Object.entries(settings.auth.methods)) {
106364
106537
  await projectsService.updateAuthStatus({
106365
106538
  projectId,
106366
106539
  method,
@@ -106664,7 +106837,7 @@ var Push = class {
106664
106837
  ([key, value]) => ({ key, value })
106665
106838
  );
106666
106839
  }
106667
- } catch (error49) {
106840
+ } catch (_error) {
106668
106841
  envVariables = [];
106669
106842
  }
106670
106843
  await Promise.all(
@@ -106961,7 +107134,7 @@ var Push = class {
106961
107134
  ([key, value]) => ({ key, value })
106962
107135
  );
106963
107136
  }
106964
- } catch (error49) {
107137
+ } catch (_error) {
106965
107138
  envVariables = [];
106966
107139
  }
106967
107140
  await Promise.all(
@@ -107128,7 +107301,7 @@ var Push = class {
107128
107301
  skipConfirmation,
107129
107302
  this.projectClient
107130
107303
  );
107131
- let tablesChanged = /* @__PURE__ */ new Set();
107304
+ const tablesChanged = /* @__PURE__ */ new Set();
107132
107305
  const errors = [];
107133
107306
  await Promise.all(
107134
107307
  tables.map(async (table) => {
@@ -107182,7 +107355,7 @@ var Push = class {
107182
107355
  }
107183
107356
  })
107184
107357
  );
107185
- for (let table of tables) {
107358
+ for (const table of tables) {
107186
107359
  let columns = table.columns;
107187
107360
  let indexes = table.indexes;
107188
107361
  let hadChanges = false;
@@ -107461,7 +107634,7 @@ var pushSettings = async () => {
107461
107634
  checkDeployConditions(localConfig);
107462
107635
  try {
107463
107636
  const projectsService = await getProjectsService();
107464
- let response = await projectsService.get(
107637
+ const response = await projectsService.get(
107465
107638
  localConfig.getProject().projectId
107466
107639
  );
107467
107640
  const remoteSettings = createSettingsObject(response);
@@ -107494,7 +107667,7 @@ var pushSettings = async () => {
107494
107667
  return;
107495
107668
  }
107496
107669
  }
107497
- } catch (e) {
107670
+ } catch (_e) {
107498
107671
  }
107499
107672
  try {
107500
107673
  log("Pushing project settings ...");
@@ -107544,7 +107717,7 @@ var pushSite = async ({
107544
107717
  );
107545
107718
  return;
107546
107719
  }
107547
- let sites = siteIds.map((id) => {
107720
+ const sites = siteIds.map((id) => {
107548
107721
  const sites2 = localConfig.getSites();
107549
107722
  const site = sites2.find((s) => s.$id === id);
107550
107723
  if (!site) {
@@ -107553,7 +107726,7 @@ var pushSite = async ({
107553
107726
  return site;
107554
107727
  });
107555
107728
  log("Validating sites ...");
107556
- for (let site of sites) {
107729
+ for (const site of sites) {
107557
107730
  if (!site.buildCommand) {
107558
107731
  log(`Site ${site.name} is missing build command.`);
107559
107732
  const answers = await import_inquirer3.default.prompt(questionsGetEntrypoint);
@@ -107664,7 +107837,7 @@ var pushFunction = async ({
107664
107837
  );
107665
107838
  return;
107666
107839
  }
107667
- let functions = functionIds.map((id) => {
107840
+ const functions = functionIds.map((id) => {
107668
107841
  const functions2 = localConfig.getFunctions();
107669
107842
  const func = functions2.find((f) => f.$id === id);
107670
107843
  if (!func) {
@@ -107673,7 +107846,7 @@ var pushFunction = async ({
107673
107846
  return func;
107674
107847
  });
107675
107848
  log("Validating functions ...");
107676
- for (let func of functions) {
107849
+ for (const func of functions) {
107677
107850
  if (!func.entrypoint) {
107678
107851
  log(`Function ${func.name} is missing an entrypoint.`);
107679
107852
  const answers = await import_inquirer3.default.prompt(questionsGetEntrypoint);
@@ -107814,7 +107987,7 @@ var pushTable = async ({
107814
107987
  });
107815
107988
  }
107816
107989
  }
107817
- } catch (e) {
107990
+ } catch (_e) {
107818
107991
  }
107819
107992
  }
107820
107993
  if (tablesToDelete.length > 0) {
@@ -107961,7 +108134,7 @@ var pushCollection = async () => {
107961
108134
  }
107962
108135
  };
107963
108136
  var pushBucket = async () => {
107964
- let bucketIds = [];
108137
+ const bucketIds = [];
107965
108138
  const configBuckets = localConfig.getBuckets();
107966
108139
  if (cliConfig.all) {
107967
108140
  checkDeployConditions(localConfig);
@@ -107980,7 +108153,7 @@ var pushBucket = async () => {
107980
108153
  );
107981
108154
  return;
107982
108155
  }
107983
- let buckets = [];
108156
+ const buckets = [];
107984
108157
  for (const bucketId of bucketIds) {
107985
108158
  const idBuckets = configBuckets.filter((b) => b.$id === bucketId);
107986
108159
  buckets.push(...idBuckets);
@@ -108011,7 +108184,7 @@ var pushBucket = async () => {
108011
108184
  }
108012
108185
  };
108013
108186
  var pushTeam = async () => {
108014
- let teamIds = [];
108187
+ const teamIds = [];
108015
108188
  const configTeams = localConfig.getTeams();
108016
108189
  if (cliConfig.all) {
108017
108190
  checkDeployConditions(localConfig);
@@ -108030,7 +108203,7 @@ var pushTeam = async () => {
108030
108203
  );
108031
108204
  return;
108032
108205
  }
108033
- let teams = [];
108206
+ const teams = [];
108034
108207
  for (const teamId of teamIds) {
108035
108208
  const idTeams = configTeams.filter((t) => t.$id === teamId);
108036
108209
  teams.push(...idTeams);
@@ -108061,7 +108234,7 @@ var pushTeam = async () => {
108061
108234
  }
108062
108235
  };
108063
108236
  var pushMessagingTopic = async () => {
108064
- let topicsIds = [];
108237
+ const topicsIds = [];
108065
108238
  const configTopics = localConfig.getMessagingTopics();
108066
108239
  if (cliConfig.all) {
108067
108240
  checkDeployConditions(localConfig);
@@ -108080,7 +108253,7 @@ var pushMessagingTopic = async () => {
108080
108253
  );
108081
108254
  return;
108082
108255
  }
108083
- let topics = [];
108256
+ const topics = [];
108084
108257
  for (const topicId of topicsIds) {
108085
108258
  const idTopic = configTopics.filter((b) => b.$id === topicId);
108086
108259
  topics.push(...idTopic);
@@ -108664,7 +108837,7 @@ var pullResources = async ({
108664
108837
  delete actions.collections;
108665
108838
  }
108666
108839
  if (cliConfig.all) {
108667
- for (let action of Object.values(actions)) {
108840
+ for (const action of Object.values(actions)) {
108668
108841
  cliConfig.all = true;
108669
108842
  await action({ returnOnZero: true });
108670
108843
  }
@@ -109182,7 +109355,7 @@ var BaseDatabasesGenerator = class {
109182
109355
  var types_ts_default = "import { type Models } from '{{appwriteDep}}';\n\n{{{ENUMS}}}{{{TYPES}}}\ndeclare const __roleStringBrand: unique symbol;\nexport type RoleString = string & { readonly [__roleStringBrand]: never };\n\nexport type RoleBuilder = {\n any: () => RoleString;\n user: (userId: string, status?: string) => RoleString;\n users: (status?: string) => RoleString;\n guests: () => RoleString;\n team: (teamId: string, role?: string) => RoleString;\n member: (memberId: string) => RoleString;\n label: (label: string) => RoleString;\n}\n\nexport type PermissionBuilder = {\n read: (role: RoleString) => string;\n write: (role: RoleString) => string;\n create: (role: RoleString) => string;\n update: (role: RoleString) => string;\n delete: (role: RoleString) => string;\n}\n\nexport type PermissionCallback = (permission: PermissionBuilder, role: RoleBuilder) => string[];\n\nexport type QueryValue = string | number | boolean;\n\nexport type ExtractQueryValue<T> = T extends (infer U)[]\n ? U extends QueryValue ? U : never\n : T extends QueryValue | null ? NonNullable<T> : never;\n\nexport type QueryableKeys<T> = {\n [K in keyof T]: ExtractQueryValue<T[K]> extends never ? never : K;\n}[keyof T];\n\nexport type QueryBuilder<T> = {\n equal: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n notEqual: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n lessThan: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n lessThanEqual: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n greaterThan: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n greaterThanEqual: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n contains: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n search: <K extends QueryableKeys<T>>(field: K, value: string) => string;\n isNull: <K extends QueryableKeys<T>>(field: K) => string;\n isNotNull: <K extends QueryableKeys<T>>(field: K) => string;\n startsWith: <K extends QueryableKeys<T>>(field: K, value: string) => string;\n endsWith: <K extends QueryableKeys<T>>(field: K, value: string) => string;\n between: <K extends QueryableKeys<T>>(field: K, start: ExtractQueryValue<T[K]>, end: ExtractQueryValue<T[K]>) => string;\n select: <K extends keyof T>(fields: K[]) => string;\n orderAsc: <K extends keyof T>(field: K) => string;\n orderDesc: <K extends keyof T>(field: K) => string;\n limit: (value: number) => string;\n offset: (value: number) => string;\n cursorAfter: (documentId: string) => string;\n cursorBefore: (documentId: string) => string;\n or: (...queries: string[]) => string;\n and: (...queries: string[]) => string;\n}\n\nexport type DatabaseId = {{{databaseIdType}}};\n\n{{{DATABASE_TABLES_TYPE}}}\n";
109183
109356
 
109184
109357
  // lib/commands/generators/typescript/templates/databases.ts.hbs
109185
- var databases_ts_default = 'import { Client, TablesDB, ID, Query, type Models, Permission, Role } from \'{{appwriteDep}}\';\nimport type { DatabaseHandle, DatabaseId, DatabaseTableMap, DatabaseTables, QueryBuilder, PermissionBuilder, RoleBuilder, RoleString } from \'./types{{importExt}}\';\n{{#if supportsServerSide}}\nimport { PROJECT_ID, ENDPOINT, API_KEY } from \'./constants{{importExt}}\';\n{{else}}\nimport { PROJECT_ID, ENDPOINT } from \'./constants{{importExt}}\';\n{{/if}}\n\nconst createQueryBuilder = <T>(): QueryBuilder<T> => ({\n equal: (field, value) => Query.equal(String(field), value as any),\n notEqual: (field, value) => Query.notEqual(String(field), value as any),\n lessThan: (field, value) => Query.lessThan(String(field), value as any),\n lessThanEqual: (field, value) => Query.lessThanEqual(String(field), value as any),\n greaterThan: (field, value) => Query.greaterThan(String(field), value as any),\n greaterThanEqual: (field, value) => Query.greaterThanEqual(String(field), value as any),\n contains: (field, value) => Query.contains(String(field), value as any),\n search: (field, value) => Query.search(String(field), value),\n isNull: (field) => Query.isNull(String(field)),\n isNotNull: (field) => Query.isNotNull(String(field)),\n startsWith: (field, value) => Query.startsWith(String(field), value),\n endsWith: (field, value) => Query.endsWith(String(field), value),\n between: (field, start, end) => Query.between(String(field), start as any, end as any),\n select: (fields) => Query.select(fields.map(String)),\n orderAsc: (field) => Query.orderAsc(String(field)),\n orderDesc: (field) => Query.orderDesc(String(field)),\n limit: (value) => Query.limit(value),\n offset: (value) => Query.offset(value),\n cursorAfter: (documentId) => Query.cursorAfter(documentId),\n cursorBefore: (documentId) => Query.cursorBefore(documentId),\n or: (...queries) => Query.or(queries),\n and: (...queries) => Query.and(queries),\n});\n\n{{{TABLE_ID_MAP}}}\n\n{{{TABLES_WITH_RELATIONSHIPS}}}\n\nconst roleBuilder: RoleBuilder = {\n any: () => Role.any() as RoleString,\n user: (userId, status?) => Role.user(userId, status) as RoleString,\n users: (status?) => Role.users(status) as RoleString,\n guests: () => Role.guests() as RoleString,\n team: (teamId, role?) => Role.team(teamId, role) as RoleString,\n member: (memberId) => Role.member(memberId) as RoleString,\n label: (label) => Role.label(label) as RoleString,\n};\n\nconst permissionBuilder: PermissionBuilder = {\n read: (role) => Permission.read(role),\n write: (role) => Permission.write(role),\n create: (role) => Permission.create(role),\n update: (role) => Permission.update(role),\n delete: (role) => Permission.delete(role),\n};\n\nconst resolvePermissions = (callback?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]): string[] | undefined =>\n callback?.(permissionBuilder, roleBuilder);\n\nfunction createTableApi<T extends Models.Row>(\n tablesDB: TablesDB,\n databaseId: string,\n tableId: string,\n) {\n return {\n create: (data: any, options?: { rowId?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.createRow<T>({\n databaseId,\n tableId,\n rowId: options?.rowId ?? ID.unique(),\n data,\n permissions: resolvePermissions(options?.permissions),\n transactionId: options?.transactionId,\n }),\n get: (id: string) =>\n tablesDB.getRow<T>({\n databaseId,\n tableId,\n rowId: id,\n }),\n update: (id: string, data: any, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.updateRow<T>({\n databaseId,\n tableId,\n rowId: id,\n data,\n ...(options?.permissions ? { permissions: resolvePermissions(options.permissions) } : {}),\n transactionId: options?.transactionId,\n }),\n delete: async (id: string, options?: { transactionId?: string }) => {\n await tablesDB.deleteRow({\n databaseId,\n tableId,\n rowId: id,\n transactionId: options?.transactionId,\n });\n },\n list: (options?: { queries?: (q: any) => string[] }) =>\n tablesDB.listRows<T>({\n databaseId,\n tableId,\n queries: options?.queries?.(createQueryBuilder<T>()),\n }),{{{BULK_METHODS}}}\n };\n}\n\n{{{BULK_CHECK}}}\nconst hasOwn = (obj: unknown, key: string): boolean =>\n obj != null && Object.prototype.hasOwnProperty.call(obj, key);\n\nfunction createDatabaseHandle<D extends DatabaseId>(\n tablesDB: TablesDB,\n databaseId: D,\n): DatabaseHandle<D> {\n const tableApiCache = new Map<string, unknown>();\n const dbMap = tableIdMap[databaseId];\n\n return {\n use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T): DatabaseTableMap[D][T] => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n\n if (!tableApiCache.has(tableId)) {\n const resolvedTableId = dbMap[tableId];\n const api = createTableApi(tablesDB, databaseId, resolvedTableId);\n {{{BULK_REMOVAL}}}\n tableApiCache.set(tableId, api);\n }\n return tableApiCache.get(tableId) as DatabaseTableMap[D][T];\n },\n{{#if supportsServerSide}}\n create: (tableId: string, name: string, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean; columns?: any[]; indexes?: any[] }) =>\n tablesDB.createTable({\n databaseId,\n tableId,\n name,\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n columns: options?.columns,\n indexes: options?.indexes,\n }),\n update: (tableId: string, options?: { name?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean }) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n return tablesDB.updateTable({\n databaseId,\n tableId: resolvedTableId,\n name: options?.name ?? tableId, // TODO: remove this fallback once fixed in other SDKs\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n });\n },\n delete: async (tableId: string) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n await tablesDB.deleteTable({\n databaseId,\n tableId: resolvedTableId,\n });\n },\n{{/if}}\n };\n}\n\nfunction createDatabasesApi(tablesDB: TablesDB): DatabaseTables {\n const dbCache = new Map<DatabaseId, ReturnType<typeof createDatabaseHandle>>();\n\n return {\n use: (databaseId: DatabaseId) => {\n if (!hasOwn(tableIdMap, databaseId)) {\n throw new Error(`Unknown database "${databaseId}"`);\n }\n\n if (!dbCache.has(databaseId)) {\n dbCache.set(databaseId, createDatabaseHandle(tablesDB, databaseId));\n }\n return dbCache.get(databaseId);\n },\n{{#if supportsServerSide}}\n create: (databaseId: string, name: string, options?: { enabled?: boolean }) =>\n tablesDB.create({\n databaseId,\n name,\n enabled: options?.enabled,\n }),\n update: (databaseId: DatabaseId, options?: { name?: string; enabled?: boolean }) => {\n return tablesDB.update({\n databaseId,\n name: options?.name ?? databaseId,\n enabled: options?.enabled,\n });\n },\n delete: async (databaseId: DatabaseId) => {\n await tablesDB.delete({\n databaseId,\n });\n },\n{{/if}}\n } as DatabaseTables;\n}\n\n// Initialize client\nconst client = new Client()\n .setEndpoint(ENDPOINT)\n .setProject(PROJECT_ID){{#if supportsServerSide}}\n .setKey(API_KEY){{/if}};\n\nconst tablesDB = new TablesDB(client);\n\nexport const databases: DatabaseTables = createDatabasesApi(tablesDB);\n';
109358
+ var databases_ts_default = 'import { Client, TablesDB, ID, Query, type Models, Permission, Role } from \'{{appwriteDep}}\';\nimport type { DatabaseHandle, DatabaseId, DatabaseTableMap, DatabaseTables, QueryBuilder, QueryValue, PermissionBuilder, RoleBuilder, RoleString } from \'./types{{importExt}}\';\n{{#if supportsServerSide}}\nimport { PROJECT_ID, ENDPOINT, API_KEY } from \'./constants{{importExt}}\';\n{{else}}\nimport { PROJECT_ID, ENDPOINT } from \'./constants{{importExt}}\';\n{{/if}}\n\nconst createQueryBuilder = <T>(): QueryBuilder<T> => ({\n equal: (field, value) => Query.equal(String(field), value as QueryValue),\n notEqual: (field, value) => Query.notEqual(String(field), value as QueryValue),\n lessThan: (field, value) => Query.lessThan(String(field), value as QueryValue),\n lessThanEqual: (field, value) => Query.lessThanEqual(String(field), value as QueryValue),\n greaterThan: (field, value) => Query.greaterThan(String(field), value as QueryValue),\n greaterThanEqual: (field, value) => Query.greaterThanEqual(String(field), value as QueryValue),\n contains: (field, value) => Query.contains(String(field), value as string | QueryValue[]),\n search: (field, value) => Query.search(String(field), value),\n isNull: (field) => Query.isNull(String(field)),\n isNotNull: (field) => Query.isNotNull(String(field)),\n startsWith: (field, value) => Query.startsWith(String(field), value),\n endsWith: (field, value) => Query.endsWith(String(field), value),\n between: (field, start, end) => Query.between(String(field), start as string | number, end as string | number),\n select: (fields) => Query.select(fields.map(String)),\n orderAsc: (field) => Query.orderAsc(String(field)),\n orderDesc: (field) => Query.orderDesc(String(field)),\n limit: (value) => Query.limit(value),\n offset: (value) => Query.offset(value),\n cursorAfter: (documentId) => Query.cursorAfter(documentId),\n cursorBefore: (documentId) => Query.cursorBefore(documentId),\n or: (...queries) => Query.or(queries),\n and: (...queries) => Query.and(queries),\n});\n\n{{{TABLE_ID_MAP}}}\n\n{{{TABLES_WITH_RELATIONSHIPS}}}\n\nconst roleBuilder: RoleBuilder = {\n any: () => Role.any() as RoleString,\n user: (userId, status?) => Role.user(userId, status) as RoleString,\n users: (status?) => Role.users(status) as RoleString,\n guests: () => Role.guests() as RoleString,\n team: (teamId, role?) => Role.team(teamId, role) as RoleString,\n member: (memberId) => Role.member(memberId) as RoleString,\n label: (label) => Role.label(label) as RoleString,\n};\n\nconst permissionBuilder: PermissionBuilder = {\n read: (role) => Permission.read(role),\n write: (role) => Permission.write(role),\n create: (role) => Permission.create(role),\n update: (role) => Permission.update(role),\n delete: (role) => Permission.delete(role),\n};\n\nconst resolvePermissions = (callback?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]): string[] | undefined =>\n callback?.(permissionBuilder, roleBuilder);\n\nfunction createTableApi<T extends Models.Row>(\n tablesDB: TablesDB,\n databaseId: string,\n tableId: string,\n) {\n return {\n create: (data: Omit<T, keyof Models.Row>, options?: { rowId?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.createRow<T>({\n databaseId,\n tableId,\n rowId: options?.rowId ?? ID.unique(),\n data: data as T extends Models.DefaultRow ? Partial<Models.Row> & Record<string, unknown> : Partial<Models.Row> & Omit<T, keyof Models.Row>,\n permissions: resolvePermissions(options?.permissions),\n transactionId: options?.transactionId,\n }),\n get: (id: string) =>\n tablesDB.getRow<T>({\n databaseId,\n tableId,\n rowId: id,\n }),\n update: (id: string, data: Partial<Omit<T, keyof Models.Row>>, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.updateRow<T>({\n databaseId,\n tableId,\n rowId: id,\n data: data as T extends Models.DefaultRow ? Partial<Models.Row> & Record<string, unknown> : Partial<Models.Row> & Partial<Omit<T, keyof Models.Row>>,\n ...(options?.permissions ? { permissions: resolvePermissions(options.permissions) } : {}),\n transactionId: options?.transactionId,\n }),\n delete: async (id: string, options?: { transactionId?: string }) => {\n await tablesDB.deleteRow({\n databaseId,\n tableId,\n rowId: id,\n transactionId: options?.transactionId,\n });\n },\n list: (options?: { queries?: (q: QueryBuilder<T>) => string[] }) =>\n tablesDB.listRows<T>({\n databaseId,\n tableId,\n queries: options?.queries?.(createQueryBuilder<T>()),\n }),{{{BULK_METHODS}}}\n };\n}\n\n{{{BULK_CHECK}}}\nconst hasOwn = (obj: unknown, key: string): boolean =>\n obj != null && Object.prototype.hasOwnProperty.call(obj, key);\n\nfunction createDatabaseHandle<D extends DatabaseId>(\n tablesDB: TablesDB,\n databaseId: D,\n): DatabaseHandle<D> {\n const tableApiCache = new Map<string, unknown>();\n const dbMap = tableIdMap[databaseId];\n\n return {\n use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T): DatabaseTableMap[D][T] => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n\n if (!tableApiCache.has(tableId)) {\n const resolvedTableId = dbMap[tableId];\n const api = createTableApi(tablesDB, databaseId, resolvedTableId);\n {{{BULK_REMOVAL}}}\n tableApiCache.set(tableId, api);\n }\n return tableApiCache.get(tableId) as DatabaseTableMap[D][T];\n },\n{{#if supportsServerSide}}\n create: (tableId: string, name: string, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean; columns?: object[]; indexes?: object[] }) =>\n tablesDB.createTable({\n databaseId,\n tableId,\n name,\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n columns: options?.columns,\n indexes: options?.indexes,\n }),\n update: (tableId: string, options?: { name?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean }) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n return tablesDB.updateTable({\n databaseId,\n tableId: resolvedTableId,\n name: options?.name,\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n });\n },\n delete: async (tableId: string) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n await tablesDB.deleteTable({\n databaseId,\n tableId: resolvedTableId,\n });\n },\n{{/if}}\n };\n}\n\nfunction createDatabasesApi(tablesDB: TablesDB): DatabaseTables {\n const dbCache = new Map<DatabaseId, ReturnType<typeof createDatabaseHandle>>();\n\n return {\n use: (databaseId: DatabaseId) => {\n if (!hasOwn(tableIdMap, databaseId)) {\n throw new Error(`Unknown database "${databaseId}"`);\n }\n\n if (!dbCache.has(databaseId)) {\n dbCache.set(databaseId, createDatabaseHandle(tablesDB, databaseId));\n }\n return dbCache.get(databaseId);\n },\n{{#if supportsServerSide}}\n create: (databaseId: string, name: string, options?: { enabled?: boolean }) =>\n tablesDB.create({\n databaseId,\n name,\n enabled: options?.enabled,\n }),\n update: (databaseId: DatabaseId, options?: { name?: string; enabled?: boolean }) => {\n return tablesDB.update({\n databaseId,\n name: options?.name ?? databaseId,\n enabled: options?.enabled,\n });\n },\n delete: async (databaseId: DatabaseId) => {\n await tablesDB.delete({\n databaseId,\n });\n },\n{{/if}}\n } as DatabaseTables;\n}\n\n// Initialize client\nconst client = new Client()\n .setEndpoint(ENDPOINT)\n .setProject(PROJECT_ID){{#if supportsServerSide}}\n .setKey(API_KEY){{/if}};\n\nconst tablesDB = new TablesDB(client);\n\nexport const databases: DatabaseTables = createDatabasesApi(tablesDB);\n';
109186
109359
 
109187
109360
  // lib/commands/generators/typescript/templates/index.ts.hbs
109188
109361
  var index_ts_default = '/**\n * {{sdkTitle}} Generated SDK\n *\n * This file is auto-generated. Do not edit manually.\n * Re-run `{{executableName}} generate` to regenerate.\n */\n\nexport { databases } from "./databases{{importExt}}";\nexport * from "./types{{importExt}}";\n';
@@ -109349,7 +109522,7 @@ ${dbReturnTypes}
109349
109522
 
109350
109523
  export type DatabaseHandle<D extends DatabaseId> = {
109351
109524
  use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => DatabaseTableMap[D][T];
109352
- ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: any[]; indexes?: any[] }) => Promise<Models.Table>;
109525
+ ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: object[]; indexes?: object[] }) => Promise<Models.Table>;
109353
109526
  update: <T extends keyof DatabaseTableMap[D] & string>(tableId: T, options?: { name?: string; permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean }) => Promise<Models.Table>;
109354
109527
  delete: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => Promise<void>;` : ""}
109355
109528
  };
@@ -109361,12 +109534,11 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109361
109534
  delete: <D extends DatabaseId>(databaseId: D) => Promise<void>;` : ""}
109362
109535
  };`;
109363
109536
  }
109364
- generateTypesFile(config2) {
109537
+ generateTypesFile(config2, appwriteDep) {
109365
109538
  const entities = config2.tables?.length ? config2.tables : config2.collections;
109366
109539
  if (!entities || entities.length === 0) {
109367
109540
  return "// No tables or collections found in configuration\n";
109368
109541
  }
109369
- const appwriteDep = getAppwriteDependency();
109370
109542
  const enums = this.generateEnums(entities);
109371
109543
  const types = entities.map((entity) => this.generateTableType(entity, entities)).join("\n\n");
109372
109544
  const entitiesByDb = this.groupEntitiesByDb(entities);
@@ -109416,26 +109588,26 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109416
109588
  generateBulkMethods(supportsBulk) {
109417
109589
  if (!supportsBulk) return "";
109418
109590
  return `
109419
- createMany: (rows: any[], options?: { transactionId?: string }) =>
109591
+ createMany: (rows: object[], options?: { transactionId?: string }) =>
109420
109592
  tablesDB.createRows({
109421
109593
  databaseId,
109422
109594
  tableId,
109423
109595
  rows,
109424
109596
  transactionId: options?.transactionId,
109425
109597
  }),
109426
- updateMany: (data: any, options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
109598
+ updateMany: (data: object, options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
109427
109599
  tablesDB.updateRows({
109428
109600
  databaseId,
109429
109601
  tableId,
109430
109602
  data,
109431
- queries: options?.queries?.(createQueryBuilder()),
109603
+ queries: options?.queries?.(createQueryBuilder<T>()),
109432
109604
  transactionId: options?.transactionId,
109433
109605
  }),
109434
- deleteMany: (options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
109606
+ deleteMany: (options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
109435
109607
  tablesDB.deleteRows({
109436
109608
  databaseId,
109437
109609
  tableId,
109438
- queries: options?.queries?.(createQueryBuilder()),
109610
+ queries: options?.queries?.(createQueryBuilder<T>()),
109439
109611
  transactionId: options?.transactionId,
109440
109612
  }),`;
109441
109613
  }
@@ -109449,18 +109621,17 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109449
109621
  return `
109450
109622
  // Remove bulk methods for tables with relationships
109451
109623
  if (!hasBulkMethods(databaseId, tableId)) {
109452
- delete (api as any).createMany;
109453
- delete (api as any).updateMany;
109454
- delete (api as any).deleteMany;
109624
+ delete (api as Record<string, unknown>).createMany;
109625
+ delete (api as Record<string, unknown>).updateMany;
109626
+ delete (api as Record<string, unknown>).deleteMany;
109455
109627
  }`;
109456
109628
  }
109457
- generateDatabasesFile(config2, importExt) {
109629
+ generateDatabasesFile(config2, importExt, appwriteDep) {
109458
109630
  const entities = config2.tables?.length ? config2.tables : config2.collections;
109459
109631
  if (!entities || entities.length === 0) {
109460
109632
  return "// No tables or collections found in configuration\n";
109461
109633
  }
109462
109634
  const entitiesByDb = this.groupEntitiesByDb(entities);
109463
- const appwriteDep = getAppwriteDependency();
109464
109635
  const supportsServerSide = supportsServerSideMethods(
109465
109636
  appwriteDep,
109466
109637
  this.serverSideOverride
@@ -109483,8 +109654,7 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109483
109654
  importExt
109484
109655
  });
109485
109656
  }
109486
- generateConstantsFile(config2) {
109487
- const appwriteDep = getAppwriteDependency();
109657
+ generateConstantsFile(config2, appwriteDep) {
109488
109658
  const supportsServerSide = supportsServerSideMethods(
109489
109659
  appwriteDep,
109490
109660
  this.serverSideOverride
@@ -109496,11 +109666,12 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109496
109666
  requiresApiKey: supportsServerSide
109497
109667
  });
109498
109668
  }
109499
- async generate(config2) {
109669
+ async generate(config2, options) {
109500
109670
  if (!config2.projectId) {
109501
109671
  throw new Error("Project ID is required in configuration");
109502
109672
  }
109503
- const importExt = detectImportExtension();
109673
+ const appwriteDep = options?.appwriteImportSource ?? getAppwriteDependency();
109674
+ const importExt = options?.importExtension ?? detectImportExtension();
109504
109675
  const hasEntities = config2.tables && config2.tables.length > 0 || config2.collections && config2.collections.length > 0;
109505
109676
  if (!hasEntities) {
109506
109677
  console.log(
@@ -109510,14 +109681,14 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109510
109681
  dbContent: "// No tables or collections found in configuration\n",
109511
109682
  typesContent: "// No tables or collections found in configuration\n",
109512
109683
  indexContent: this.generateIndexFile(importExt),
109513
- constantsContent: this.generateConstantsFile(config2)
109684
+ constantsContent: this.generateConstantsFile(config2, appwriteDep)
109514
109685
  };
109515
109686
  }
109516
109687
  return {
109517
- dbContent: this.generateDatabasesFile(config2, importExt),
109518
- typesContent: this.generateTypesFile(config2),
109688
+ dbContent: this.generateDatabasesFile(config2, importExt, appwriteDep),
109689
+ typesContent: this.generateTypesFile(config2, appwriteDep),
109519
109690
  indexContent: this.generateIndexFile(importExt),
109520
- constantsContent: this.generateConstantsFile(config2)
109691
+ constantsContent: this.generateConstantsFile(config2, appwriteDep)
109521
109692
  };
109522
109693
  }
109523
109694
  };