appwrite-cli 13.6.0 → 13.6.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 (75) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +2 -2
  3. package/cli.ts +3 -3
  4. package/dist/bundle-win-arm64.mjs +336 -212
  5. package/dist/cli.cjs +336 -212
  6. package/dist/index.cjs +156 -104
  7. package/dist/index.js +156 -104
  8. package/dist/lib/commands/config-validations.d.ts +1 -1
  9. package/dist/lib/commands/config-validations.d.ts.map +1 -1
  10. package/dist/lib/commands/errors.d.ts +4 -4
  11. package/dist/lib/commands/errors.d.ts.map +1 -1
  12. package/dist/lib/commands/generate.d.ts.map +1 -1
  13. package/dist/lib/commands/generators/base.d.ts +5 -0
  14. package/dist/lib/commands/generators/base.d.ts.map +1 -1
  15. package/dist/lib/commands/generic.d.ts.map +1 -1
  16. package/dist/lib/commands/init.d.ts.map +1 -1
  17. package/dist/lib/commands/run.d.ts.map +1 -1
  18. package/dist/lib/commands/types.d.ts.map +1 -1
  19. package/dist/lib/commands/update.d.ts.map +1 -1
  20. package/dist/lib/commands/utils/change-approval.d.ts +3 -3
  21. package/dist/lib/commands/utils/change-approval.d.ts.map +1 -1
  22. package/dist/lib/commands/utils/database-sync.d.ts.map +1 -1
  23. package/dist/lib/commands/utils/deployment.d.ts +16 -4
  24. package/dist/lib/commands/utils/deployment.d.ts.map +1 -1
  25. package/dist/lib/commands/utils/pools.d.ts.map +1 -1
  26. package/dist/lib/constants.d.ts +1 -1
  27. package/dist/lib/emulation/docker.d.ts.map +1 -1
  28. package/dist/lib/json.d.ts +1 -1
  29. package/dist/lib/json.d.ts.map +1 -1
  30. package/dist/lib/paginate.d.ts +5 -6
  31. package/dist/lib/paginate.d.ts.map +1 -1
  32. package/dist/lib/parser.d.ts +5 -4
  33. package/dist/lib/parser.d.ts.map +1 -1
  34. package/dist/lib/spinner.d.ts +1 -1
  35. package/dist/lib/spinner.d.ts.map +1 -1
  36. package/dist/lib/utils.d.ts +6 -1
  37. package/dist/lib/utils.d.ts.map +1 -1
  38. package/dist/lib/validations.d.ts +1 -1
  39. package/dist/lib/validations.d.ts.map +1 -1
  40. package/eslint.config.js +45 -0
  41. package/install.ps1 +2 -2
  42. package/install.sh +1 -1
  43. package/lib/client.ts +3 -3
  44. package/lib/commands/config-validations.ts +1 -1
  45. package/lib/commands/config.ts +2 -2
  46. package/lib/commands/errors.ts +2 -2
  47. package/lib/commands/generate.ts +8 -6
  48. package/lib/commands/generators/base.ts +6 -0
  49. package/lib/commands/generators/typescript/databases.ts +9 -9
  50. package/lib/commands/generators/typescript/templates/databases.ts.hbs +16 -16
  51. package/lib/commands/generic.ts +21 -16
  52. package/lib/commands/init.ts +147 -61
  53. package/lib/commands/pull.ts +1 -1
  54. package/lib/commands/push.ts +19 -19
  55. package/lib/commands/run.ts +15 -9
  56. package/lib/commands/types.ts +18 -8
  57. package/lib/commands/update.ts +24 -16
  58. package/lib/commands/utils/attributes.ts +6 -6
  59. package/lib/commands/utils/change-approval.ts +26 -19
  60. package/lib/commands/utils/database-sync.ts +58 -18
  61. package/lib/commands/utils/deployment.ts +22 -5
  62. package/lib/commands/utils/pools.ts +11 -5
  63. package/lib/config.ts +1 -1
  64. package/lib/constants.ts +1 -1
  65. package/lib/emulation/docker.ts +5 -6
  66. package/lib/emulation/utils.ts +2 -2
  67. package/lib/json.ts +15 -7
  68. package/lib/paginate.ts +30 -20
  69. package/lib/parser.ts +46 -15
  70. package/lib/questions.ts +38 -38
  71. package/lib/spinner.ts +5 -1
  72. package/lib/utils.ts +15 -3
  73. package/lib/validations.ts +1 -1
  74. package/package.json +7 -1
  75. package/scoop/appwrite.config.json +3 -3
@@ -2360,7 +2360,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2360
2360
  }
2361
2361
  return positiveOption || option2;
2362
2362
  };
2363
- const getErrorMessage = (option2) => {
2363
+ const getErrorMessage2 = (option2) => {
2364
2364
  const bestOption = findBestOptionFromValue(option2);
2365
2365
  const optionKey = bestOption.attributeName();
2366
2366
  const source = this.getOptionValueSource(optionKey);
@@ -2369,7 +2369,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2369
2369
  }
2370
2370
  return `option '${bestOption.flags}'`;
2371
2371
  };
2372
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2372
+ const message = `error: ${getErrorMessage2(option)} cannot be used with ${getErrorMessage2(conflictingOption)}`;
2373
2373
  this.error(message, { code: "commander.conflictingOption" });
2374
2374
  }
2375
2375
  /**
@@ -4315,9 +4315,9 @@ var require_source = __commonJS({
4315
4315
  }
4316
4316
  });
4317
4317
 
4318
- // node_modules/escape-string-regexp/index.js
4318
+ // node_modules/figures/node_modules/escape-string-regexp/index.js
4319
4319
  var require_escape_string_regexp = __commonJS({
4320
- "node_modules/escape-string-regexp/index.js"(exports, module) {
4320
+ "node_modules/figures/node_modules/escape-string-regexp/index.js"(exports, module) {
4321
4321
  "use strict";
4322
4322
  var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
4323
4323
  module.exports = function(str) {
@@ -21962,9 +21962,9 @@ var require_stream_duplex = __commonJS({
21962
21962
  }
21963
21963
  });
21964
21964
 
21965
- // node_modules/string_decoder/node_modules/safe-buffer/index.js
21965
+ // node_modules/safe-buffer/index.js
21966
21966
  var require_safe_buffer = __commonJS({
21967
- "node_modules/string_decoder/node_modules/safe-buffer/index.js"(exports, module) {
21967
+ "node_modules/safe-buffer/index.js"(exports, module) {
21968
21968
  var buffer = __require("buffer");
21969
21969
  var Buffer2 = buffer.Buffer;
21970
21970
  function copyProps(src, dst) {
@@ -61213,6 +61213,20 @@ var require_lodash = __commonJS({
61213
61213
  }
61214
61214
  });
61215
61215
 
61216
+ // node_modules/inquirer-search-list/node_modules/chalk/node_modules/escape-string-regexp/index.js
61217
+ var require_escape_string_regexp2 = __commonJS({
61218
+ "node_modules/inquirer-search-list/node_modules/chalk/node_modules/escape-string-regexp/index.js"(exports, module) {
61219
+ "use strict";
61220
+ var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
61221
+ module.exports = function(str) {
61222
+ if (typeof str !== "string") {
61223
+ throw new TypeError("Expected a string");
61224
+ }
61225
+ return str.replace(matchOperatorsRe, "\\$&");
61226
+ };
61227
+ }
61228
+ });
61229
+
61216
61230
  // node_modules/inquirer-search-list/node_modules/chalk/node_modules/ansi-styles/node_modules/color-convert/node_modules/color-name/index.js
61217
61231
  var require_color_name2 = __commonJS({
61218
61232
  "node_modules/inquirer-search-list/node_modules/chalk/node_modules/ansi-styles/node_modules/color-convert/node_modules/color-name/index.js"(exports, module) {
@@ -62579,7 +62593,7 @@ var require_templates2 = __commonJS({
62579
62593
  var require_chalk = __commonJS({
62580
62594
  "node_modules/inquirer-search-list/node_modules/chalk/index.js"(exports, module) {
62581
62595
  "use strict";
62582
- var escapeStringRegexp = require_escape_string_regexp();
62596
+ var escapeStringRegexp = require_escape_string_regexp2();
62583
62597
  var ansiStyles = require_ansi_styles2();
62584
62598
  var stdoutColor = require_supports_color2().stdout;
62585
62599
  var template = require_templates2();
@@ -62742,11 +62756,25 @@ var require_chalk = __commonJS({
62742
62756
  }
62743
62757
  });
62744
62758
 
62759
+ // node_modules/inquirer-search-list/node_modules/figures/node_modules/escape-string-regexp/index.js
62760
+ var require_escape_string_regexp3 = __commonJS({
62761
+ "node_modules/inquirer-search-list/node_modules/figures/node_modules/escape-string-regexp/index.js"(exports, module) {
62762
+ "use strict";
62763
+ var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
62764
+ module.exports = function(str) {
62765
+ if (typeof str !== "string") {
62766
+ throw new TypeError("Expected a string");
62767
+ }
62768
+ return str.replace(matchOperatorsRe, "\\$&");
62769
+ };
62770
+ }
62771
+ });
62772
+
62745
62773
  // node_modules/inquirer-search-list/node_modules/figures/index.js
62746
62774
  var require_figures2 = __commonJS({
62747
62775
  "node_modules/inquirer-search-list/node_modules/figures/index.js"(exports, module) {
62748
62776
  "use strict";
62749
- var escapeStringRegexp = require_escape_string_regexp();
62777
+ var escapeStringRegexp = require_escape_string_regexp3();
62750
62778
  var platform = process.platform;
62751
62779
  var main = {
62752
62780
  tick: "\u2714",
@@ -82342,9 +82370,9 @@ var require_is_glob = __commonJS({
82342
82370
  }
82343
82371
  });
82344
82372
 
82345
- // node_modules/glob-parent/index.js
82373
+ // node_modules/chokidar/node_modules/glob-parent/index.js
82346
82374
  var require_glob_parent = __commonJS({
82347
- "node_modules/glob-parent/index.js"(exports, module) {
82375
+ "node_modules/chokidar/node_modules/glob-parent/index.js"(exports, module) {
82348
82376
  "use strict";
82349
82377
  var isGlob = require_is_glob();
82350
82378
  var pathPosixDirname = __require("path").posix.dirname;
@@ -92067,7 +92095,7 @@ var package_default = {
92067
92095
  type: "module",
92068
92096
  homepage: "https://appwrite.io/support",
92069
92097
  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",
92070
- version: "13.6.0",
92098
+ version: "13.6.1",
92071
92099
  license: "BSD-3-Clause",
92072
92100
  main: "dist/index.cjs",
92073
92101
  module: "dist/index.js",
@@ -92098,6 +92126,7 @@ var package_default = {
92098
92126
  "build:lib:esm": "esbuild index.ts --bundle --platform=node --target=node18 --format=esm --loader:.hbs=text --outfile=dist/index.js",
92099
92127
  "build:lib:cjs": "esbuild index.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --outfile=dist/index.cjs",
92100
92128
  "build:cli": "esbuild cli.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --external:fsevents --outfile=dist/cli.cjs",
92129
+ lint: "eslint .",
92101
92130
  format: 'prettier --write "**/*.{js,ts,json,md}"',
92102
92131
  generate: "tsx scripts/generate-commands.ts",
92103
92132
  prepublishOnly: "npm run build",
@@ -92129,7 +92158,12 @@ var package_default = {
92129
92158
  zod: "^4.3.5"
92130
92159
  },
92131
92160
  devDependencies: {
92161
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
92162
+ "@typescript-eslint/parser": "^8.0.0",
92132
92163
  "@types/bun": "^1.3.5",
92164
+ eslint: "^9.0.0",
92165
+ "eslint-plugin-unused-imports": "^4.0.0",
92166
+ "typescript-eslint": "^8.0.0",
92133
92167
  "@types/cli-progress": "^3.11.5",
92134
92168
  "@types/inquirer": "^8.2.10",
92135
92169
  "@types/json-bigint": "^1.0.4",
@@ -106052,7 +106086,7 @@ var int64Schema = external_exports.preprocess(
106052
106086
  const valueOfResult = val.valueOf();
106053
106087
  const bigIntVal = BigInt(valueOfResult);
106054
106088
  return bigIntVal;
106055
- } catch (e) {
106089
+ } catch (_e) {
106056
106090
  return void 0;
106057
106091
  }
106058
106092
  }
@@ -106062,7 +106096,7 @@ var int64Schema = external_exports.preprocess(
106062
106096
  if (typeof val === "string") {
106063
106097
  try {
106064
106098
  return BigInt(val);
106065
- } catch (e) {
106099
+ } catch (_e) {
106066
106100
  return void 0;
106067
106101
  }
106068
106102
  }
@@ -106344,7 +106378,7 @@ import childProcess from "child_process";
106344
106378
  // lib/constants.ts
106345
106379
  var SDK_TITLE = "Appwrite";
106346
106380
  var SDK_TITLE_LOWER = "appwrite";
106347
- var SDK_VERSION = "13.6.0";
106381
+ var SDK_VERSION = "13.6.1";
106348
106382
  var SDK_NAME = "Command Line";
106349
106383
  var SDK_PLATFORM = "console";
106350
106384
  var SDK_LANGUAGE = "cli";
@@ -106396,6 +106430,12 @@ var createSettingsObject = (project2) => {
106396
106430
  }
106397
106431
  };
106398
106432
  };
106433
+ var getErrorMessage = (error49) => {
106434
+ if (error49 instanceof Error) {
106435
+ return error49.message;
106436
+ }
106437
+ return String(error49);
106438
+ };
106399
106439
  async function getLatestVersion() {
106400
106440
  try {
106401
106441
  const response = await (0, import_undici.fetch)(NPM_REGISTRY_URL);
@@ -106426,7 +106466,7 @@ function getAllFiles(folder) {
106426
106466
  let stats;
106427
106467
  try {
106428
106468
  stats = fs.statSync(pathAbsolute);
106429
- } catch (error49) {
106469
+ } catch (_error) {
106430
106470
  continue;
106431
106471
  }
106432
106472
  if (stats.isDirectory()) {
@@ -106471,7 +106511,7 @@ function systemHasCommand(command) {
106471
106511
  return true;
106472
106512
  }
106473
106513
  var checkDeployConditions = (localConfig2) => {
106474
- if (Object.keys(localConfig2.data).length === 0) {
106514
+ if (localConfig2.keys().length === 0) {
106475
106515
  throw new Error(
106476
106516
  "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."
106477
106517
  );
@@ -106619,7 +106659,7 @@ var Config = class {
106619
106659
  try {
106620
106660
  const file2 = fs2.readFileSync(this.path).toString();
106621
106661
  this.data = JSONBig.parse(file2);
106622
- } catch (e) {
106662
+ } catch (_e) {
106623
106663
  this.data = {};
106624
106664
  }
106625
106665
  }
@@ -132243,6 +132283,22 @@ var cliConfig = {
132243
132283
  report: false,
132244
132284
  reportData: {}
132245
132285
  };
132286
+ var toJsonObject = (value) => {
132287
+ if (value && typeof value === "object" && !Array.isArray(value)) {
132288
+ return value;
132289
+ }
132290
+ return null;
132291
+ };
132292
+ var extractReportCommandArgs = (value) => {
132293
+ if (!value || typeof value !== "object") {
132294
+ return [];
132295
+ }
132296
+ const reportData = value;
132297
+ if (!Array.isArray(reportData.data?.args)) {
132298
+ return [];
132299
+ }
132300
+ return reportData.data.args;
132301
+ };
132246
132302
  var parse3 = (data) => {
132247
132303
  if (cliConfig.json) {
132248
132304
  drawJSON(data);
@@ -132263,7 +132319,8 @@ var parse3 = (data) => {
132263
132319
  console.log(`${import_chalk.default.yellow.bold(key)} : ${data[key]}`);
132264
132320
  } else {
132265
132321
  console.log(`${import_chalk.default.yellow.bold.underline(key)}`);
132266
- drawTable([data[key]]);
132322
+ const tableRow = toJsonObject(data[key]) ?? {};
132323
+ drawTable([tableRow]);
132267
132324
  }
132268
132325
  } else {
132269
132326
  console.log(`${import_chalk.default.yellow.bold(key)} : ${data[key]}`);
@@ -132275,9 +132332,7 @@ var drawTable = (data) => {
132275
132332
  console.log("[]");
132276
132333
  return;
132277
132334
  }
132278
- const rows = data.map(
132279
- (item) => item && typeof item === "object" && !Array.isArray(item) ? item : {}
132280
- );
132335
+ const rows = data.map((item) => toJsonObject(item) ?? {});
132281
132336
  const obj = rows.reduce((res, item) => ({ ...res, ...item }), {});
132282
132337
  const keys = Object.keys(obj);
132283
132338
  if (keys.length === 0) {
@@ -132320,7 +132375,7 @@ var drawTable = (data) => {
132320
132375
  } else if (typeof row[key] === "object") {
132321
132376
  rowValues.push(JSON.stringify(row[key]));
132322
132377
  } else {
132323
- rowValues.push(row[key]);
132378
+ rowValues.push(String(row[key]));
132324
132379
  }
132325
132380
  }
132326
132381
  table.push(rowValues);
@@ -132332,7 +132387,7 @@ var drawJSON = (data) => {
132332
132387
  };
132333
132388
  var parseError = (err) => {
132334
132389
  if (cliConfig.report) {
132335
- (async () => {
132390
+ void (async () => {
132336
132391
  let appwriteVersion = "unknown";
132337
132392
  const endpoint = globalConfig2.getEndpoint();
132338
132393
  try {
@@ -132345,7 +132400,8 @@ var parseError = (err) => {
132345
132400
  } catch {
132346
132401
  }
132347
132402
  const version4 = SDK_VERSION;
132348
- const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${cliConfig.reportData.data.args.join(" ")}\``;
132403
+ const commandArgs = extractReportCommandArgs(cliConfig.reportData);
132404
+ const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${commandArgs.join(" ")}\``;
132349
132405
  const yourEnvironment = `CLI version: ${version4}
132350
132406
  Operation System: ${os2.type()}
132351
132407
  Appwrite version: ${appwriteVersion}
@@ -132397,7 +132453,7 @@ var actionRunner = (fn) => {
132397
132453
  error48(`The '--all' and '--id' flags cannot be used together.`);
132398
132454
  process.exit(1);
132399
132455
  }
132400
- return fn(...args).catch(parseError);
132456
+ return fn(...args).then(() => void 0).catch(parseError);
132401
132457
  };
132402
132458
  };
132403
132459
  var parseInteger = (value) => {
@@ -132583,19 +132639,22 @@ async function paginate(action, args = {}, limit = 100, wrapper = "", queries =
132583
132639
  ]
132584
132640
  });
132585
132641
  if (wrapper === "") {
132586
- if (response.length === 0) {
132642
+ const listResponse = response;
132643
+ if (listResponse.length === 0) {
132587
132644
  break;
132588
132645
  }
132589
- results = results.concat(response);
132646
+ results = results.concat(listResponse);
132590
132647
  } else {
132591
- if (response[wrapper].length === 0) {
132648
+ const wrappedResponse = response;
132649
+ const wrappedResults = wrappedResponse[wrapper] ?? [];
132650
+ if (wrappedResults.length === 0) {
132651
+ break;
132652
+ }
132653
+ results = results.concat(wrappedResults);
132654
+ total = wrappedResponse.total;
132655
+ if (results.length >= total) {
132592
132656
  break;
132593
132657
  }
132594
- results = results.concat(response[wrapper]);
132595
- }
132596
- total = response.total;
132597
- if (results.length >= total) {
132598
- break;
132599
132658
  }
132600
132659
  pageNumber++;
132601
132660
  }
@@ -132782,7 +132841,7 @@ var questionsInitProject = [
132782
132841
  name: "organization",
132783
132842
  message: "Choose your organization",
132784
132843
  choices: async () => {
132785
- let client2 = await sdkForConsole(true);
132844
+ const client2 = await sdkForConsole(true);
132786
132845
  const { teams: teams2 } = isCloud() ? await paginate(
132787
132846
  async (opts = {}) => (await getOrganizationsService(opts.sdk)).list(),
132788
132847
  { sdk: client2 },
@@ -132794,7 +132853,7 @@ var questionsInitProject = [
132794
132853
  100,
132795
132854
  "teams"
132796
132855
  );
132797
- let choices = teams2.map((team, idx) => {
132856
+ const choices = teams2.map((team, _idx) => {
132798
132857
  return {
132799
132858
  name: `${team.name} (${team["$id"]})`,
132800
132859
  value: team["$id"]
@@ -132843,7 +132902,7 @@ var questionsInitProject = [
132843
132902
  "projects",
132844
132903
  queries
132845
132904
  );
132846
- let choices = projects2.map((project2) => {
132905
+ const choices = projects2.map((project2) => {
132847
132906
  return {
132848
132907
  name: `${project2.name} (${project2["$id"]})`,
132849
132908
  value: {
@@ -132864,13 +132923,13 @@ var questionsInitProject = [
132864
132923
  name: "region",
132865
132924
  message: `Select your ${SDK_TITLE} Cloud region`,
132866
132925
  choices: async () => {
132867
- let client2 = await sdkForConsole(true);
132926
+ const client2 = await sdkForConsole(true);
132868
132927
  const endpoint = globalConfig2.getEndpoint() || DEFAULT_ENDPOINT;
132869
- let response = await client2.call(
132928
+ const response = await client2.call(
132870
132929
  "GET",
132871
132930
  new URL(endpoint + "/console/regions")
132872
132931
  );
132873
- let regions = response.regions || [];
132932
+ const regions = response.regions || [];
132874
132933
  if (!regions.length) {
132875
132934
  throw new Error(
132876
132935
  "No regions found. Please check your network or Appwrite Cloud availability."
@@ -133012,9 +133071,9 @@ var questionsCreateFunction = [
133012
133071
  name: "runtime",
133013
133072
  message: "What runtime would you like to use?",
133014
133073
  choices: async () => {
133015
- let response = await (await getFunctionsService()).listRuntimes();
133016
- let runtimes = response["runtimes"];
133017
- let choices = runtimes.map((runtime, idx) => {
133074
+ const response = await (await getFunctionsService()).listRuntimes();
133075
+ const runtimes = response["runtimes"];
133076
+ const choices = runtimes.map((runtime, _idx) => {
133018
133077
  return {
133019
133078
  name: `${runtime.name} (${runtime["$id"]})`,
133020
133079
  value: {
@@ -133034,9 +133093,9 @@ var questionsCreateFunction = [
133034
133093
  name: "specification",
133035
133094
  message: "What specification would you like to use?",
133036
133095
  choices: async () => {
133037
- let response = await (await getFunctionsService()).listSpecifications();
133038
- let specifications = response["specifications"];
133039
- let choices = specifications.map((spec, idx) => {
133096
+ const response = await (await getFunctionsService()).listSpecifications();
133097
+ const specifications = response["specifications"];
133098
+ const choices = specifications.map((spec, _idx) => {
133040
133099
  return {
133041
133100
  name: `${spec.cpus} CPU, ${spec.memory}MB RAM`,
133042
133101
  value: spec.slug,
@@ -133113,7 +133172,7 @@ var questionsCreateCollection = [
133113
133172
  message: "Choose the collection database",
133114
133173
  choices: async () => {
133115
133174
  const databases2 = localConfig.getDatabases();
133116
- let choices = databases2.map((database, idx) => {
133175
+ const choices = databases2.map((database, _idx) => {
133117
133176
  return {
133118
133177
  name: `${database.name} (${database.$id})`,
133119
133178
  value: database.$id
@@ -133177,7 +133236,7 @@ var questionsCreateTable = [
133177
133236
  message: "Choose the table database",
133178
133237
  choices: async () => {
133179
133238
  const databases2 = localConfig.getTablesDBs();
133180
- let choices = databases2.map((database, idx) => {
133239
+ const choices = databases2.map((database, _idx) => {
133181
133240
  return {
133182
133241
  name: `${database.name} (${database.$id})`,
133183
133242
  value: database.$id
@@ -133311,9 +133370,9 @@ var questionGetEndpoint = [
133311
133370
  if (!value) {
133312
133371
  return "Please enter a valid endpoint.";
133313
133372
  }
133314
- let client2 = new Client().setEndpoint(value);
133373
+ const client2 = new Client().setEndpoint(value);
133315
133374
  try {
133316
- let response = await client2.call(
133375
+ const response = await client2.call(
133317
133376
  "get",
133318
133377
  new URL(value + "/health/version")
133319
133378
  );
@@ -133322,7 +133381,7 @@ var questionGetEndpoint = [
133322
133381
  } else {
133323
133382
  throw new Error();
133324
133383
  }
133325
- } catch (error49) {
133384
+ } catch (_error) {
133326
133385
  return "Invalid endpoint or your Appwrite server is not running as expected.";
133327
133386
  }
133328
133387
  }
@@ -133400,9 +133459,9 @@ var questionsPushSites = [
133400
133459
  validate: (value) => validateRequired("site", value),
133401
133460
  when: () => localConfig.getSites().length > 0,
133402
133461
  choices: () => {
133403
- let sites2 = localConfig.getSites();
133462
+ const sites2 = localConfig.getSites();
133404
133463
  checkDeployConditions(localConfig);
133405
- let choices = sites2.map((site, idx) => {
133464
+ const choices = sites2.map((site, _idx) => {
133406
133465
  return {
133407
133466
  name: `${site.name} (${site.$id})`,
133408
133467
  value: site.$id
@@ -133420,9 +133479,9 @@ var questionsPushFunctions = [
133420
133479
  validate: (value) => validateRequired("function", value),
133421
133480
  when: () => localConfig.getFunctions().length > 0,
133422
133481
  choices: () => {
133423
- let functions2 = localConfig.getFunctions();
133482
+ const functions2 = localConfig.getFunctions();
133424
133483
  checkDeployConditions(localConfig);
133425
- let choices = functions2.map((func, idx) => {
133484
+ const choices = functions2.map((func, _idx) => {
133426
133485
  return {
133427
133486
  name: `${func.name} (${func.$id})`,
133428
133487
  value: func.$id
@@ -133440,7 +133499,7 @@ var questionsPushCollections = [
133440
133499
  validate: (value) => validateRequired("collection", value),
133441
133500
  when: () => localConfig.getCollections().length > 0,
133442
133501
  choices: () => {
133443
- let collections = localConfig.getCollections();
133502
+ const collections = localConfig.getCollections();
133444
133503
  checkDeployConditions(localConfig);
133445
133504
  return collections.map((collection) => {
133446
133505
  return {
@@ -133459,7 +133518,7 @@ var questionsPushTables = [
133459
133518
  validate: (value) => validateRequired("table", value),
133460
133519
  when: () => localConfig.getTables().length > 0,
133461
133520
  choices: () => {
133462
- let tables = localConfig.getTables();
133521
+ const tables = localConfig.getTables();
133463
133522
  checkDeployConditions(localConfig);
133464
133523
  return tables.map((table) => {
133465
133524
  return {
@@ -133492,7 +133551,7 @@ var questionsPushBuckets = [
133492
133551
  validate: (value) => validateRequired("bucket", value),
133493
133552
  when: () => localConfig.getBuckets().length > 0,
133494
133553
  choices: () => {
133495
- let buckets = localConfig.getBuckets();
133554
+ const buckets = localConfig.getBuckets();
133496
133555
  checkDeployConditions(localConfig);
133497
133556
  return buckets.map((bucket) => {
133498
133557
  return {
@@ -133511,7 +133570,7 @@ var questionsPushMessagingTopics = [
133511
133570
  validate: (value) => validateRequired("topics", value),
133512
133571
  when: () => localConfig.getMessagingTopics().length > 0,
133513
133572
  choices: () => {
133514
- let topics = localConfig.getMessagingTopics();
133573
+ const topics = localConfig.getMessagingTopics();
133515
133574
  return topics.map((topic) => {
133516
133575
  return {
133517
133576
  name: `${topic.name} (${topic["$id"]})`,
@@ -133542,7 +133601,7 @@ var questionsPushTeams = [
133542
133601
  validate: (value) => validateRequired("team", value),
133543
133602
  when: () => localConfig.getTeams().length > 0,
133544
133603
  choices: () => {
133545
- let teams2 = localConfig.getTeams();
133604
+ const teams2 = localConfig.getTeams();
133546
133605
  checkDeployConditions(localConfig);
133547
133606
  return teams2.map((team) => {
133548
133607
  return {
@@ -133559,7 +133618,7 @@ var questionsListFactors = [
133559
133618
  name: "factor",
133560
133619
  message: "Your account is protected by multi-factor authentication. Please choose one for verification.",
133561
133620
  choices: async () => {
133562
- let client2 = await sdkForConsole(false);
133621
+ const client2 = await sdkForConsole(false);
133563
133622
  const accountClient2 = new Account(client2);
133564
133623
  const factors = await accountClient2.listMfaFactors();
133565
133624
  const choices = [
@@ -133604,13 +133663,13 @@ var questionsRunFunctions = [
133604
133663
  message: "Which function would you like to develop locally?",
133605
133664
  validate: (value) => validateRequired("function", value),
133606
133665
  choices: () => {
133607
- let functions2 = localConfig.getFunctions();
133666
+ const functions2 = localConfig.getFunctions();
133608
133667
  if (functions2.length === 0) {
133609
133668
  throw new Error(
133610
133669
  `No functions found. Use '${EXECUTABLE_NAME} pull functions' to synchronize existing one, or use '${EXECUTABLE_NAME} init function' to create a new one.`
133611
133670
  );
133612
133671
  }
133613
- let choices = functions2.map((func, idx) => {
133672
+ const choices = functions2.map((func, _idx) => {
133614
133673
  return {
133615
133674
  name: `${func.name} (${func.$id})`,
133616
133675
  value: func.$id
@@ -133638,9 +133697,9 @@ var questionsCreateSite = [
133638
133697
  name: "framework",
133639
133698
  message: "What framework would you like to use?",
133640
133699
  choices: async () => {
133641
- let response = await (await getSitesService()).listFrameworks();
133642
- let frameworks = response["frameworks"];
133643
- let choices = frameworks.map((framework) => {
133700
+ const response = await (await getSitesService()).listFrameworks();
133701
+ const frameworks = response["frameworks"];
133702
+ const choices = frameworks.map((framework) => {
133644
133703
  return {
133645
133704
  name: `${framework.name} (${framework.key})`,
133646
133705
  value: framework
@@ -133654,9 +133713,9 @@ var questionsCreateSite = [
133654
133713
  name: "specification",
133655
133714
  message: "What specification would you like to use?",
133656
133715
  choices: async () => {
133657
- let response = await (await getSitesService()).listSpecifications();
133658
- let specifications = response["specifications"];
133659
- let choices = specifications.map((spec) => {
133716
+ const response = await (await getSitesService()).listSpecifications();
133717
+ const specifications = response["specifications"];
133718
+ const choices = specifications.map((spec) => {
133660
133719
  return {
133661
133720
  name: `${spec.cpus} CPU, ${spec.memory}MB RAM`,
133662
133721
  value: spec.slug,
@@ -133840,7 +133899,7 @@ var Client3 = class _Client {
133840
133899
  let json3 = void 0;
133841
133900
  try {
133842
133901
  json3 = JSON.parse(text2);
133843
- } catch (error49) {
133902
+ } catch (_error) {
133844
133903
  throw new AppwriteException(text2, response.status, "", text2);
133845
133904
  }
133846
133905
  if (path16 !== "/account" && json3.code === 401 && json3.type === "user_more_factors_required") {
@@ -133874,7 +133933,7 @@ var Client3 = class _Client {
133874
133933
  let json2 = void 0;
133875
133934
  try {
133876
133935
  json2 = JSONBig.parse(text);
133877
- } catch (error49) {
133936
+ } catch (_error) {
133878
133937
  return text;
133879
133938
  }
133880
133939
  return json2;
@@ -133945,11 +134004,11 @@ var completeMfaLogin = async ({
133945
134004
  };
133946
134005
  var deleteServerSession = async (sessionId) => {
133947
134006
  try {
133948
- let client2 = await sdkForConsole();
133949
- let accountClient2 = new Account(client2);
134007
+ const client2 = await sdkForConsole();
134008
+ const accountClient2 = new Account(client2);
133950
134009
  await accountClient2.deleteSession(sessionId);
133951
134010
  return true;
133952
- } catch (e) {
134011
+ } catch (_e) {
133953
134012
  return false;
133954
134013
  }
133955
134014
  };
@@ -134034,7 +134093,7 @@ var loginCommand = async ({
134034
134093
  globalConfig2.setEndpoint(configEndpoint);
134035
134094
  globalConfig2.setEmail(answers.email);
134036
134095
  const legacyClient = createLegacyConsoleClient(configEndpoint);
134037
- let client2 = await sdkForConsole(false);
134096
+ const client2 = await sdkForConsole(false);
134038
134097
  let accountClient2 = new Account(client2);
134039
134098
  let account2;
134040
134099
  try {
@@ -134084,8 +134143,8 @@ var whoami = new Command("whoami").description(commandDescriptions["whoami"]).ac
134084
134143
  error48("No user is signed in. To sign in, run 'appwrite login'");
134085
134144
  return;
134086
134145
  }
134087
- let client2 = await sdkForConsole(false);
134088
- let accountClient2 = new Account(client2);
134146
+ const client2 = await sdkForConsole(false);
134147
+ const accountClient2 = new Account(client2);
134089
134148
  let account2;
134090
134149
  try {
134091
134150
  account2 = await accountClient2.get();
@@ -134209,7 +134268,7 @@ var client = new Command("client").description(commandDescriptions["client"]).co
134209
134268
  const tail = cookieValue.length > 8 ? cookieValue.slice(-8) : cookieValue || "********";
134210
134269
  maskedCookie = `${cookieName}=...${tail}`;
134211
134270
  }
134212
- let config2 = {
134271
+ const config2 = {
134213
134272
  endpoint: globalConfig2.getEndpoint(),
134214
134273
  key: maskedKey,
134215
134274
  cookie: maskedCookie,
@@ -134222,16 +134281,16 @@ var client = new Command("client").description(commandDescriptions["client"]).co
134222
134281
  if (endpoint !== void 0) {
134223
134282
  try {
134224
134283
  const id = id_default2.unique();
134225
- let url2 = new URL(endpoint);
134284
+ const url2 = new URL(endpoint);
134226
134285
  if (url2.protocol !== "http:" && url2.protocol !== "https:") {
134227
134286
  throw new Error();
134228
134287
  }
134229
- let clientInstance = new Client().setEndpoint(endpoint);
134288
+ const clientInstance = new Client().setEndpoint(endpoint);
134230
134289
  clientInstance.setProject("console");
134231
134290
  if (selfSigned || globalConfig2.getSelfSigned()) {
134232
134291
  clientInstance.setSelfSigned(true);
134233
134292
  }
134234
- let response = await clientInstance.call(
134293
+ const response = await clientInstance.call(
134235
134294
  "GET",
134236
134295
  new URL(endpoint + "/health/version")
134237
134296
  );
@@ -134382,6 +134441,9 @@ async function downloadDeploymentCode(params) {
134382
134441
  {},
134383
134442
  "arrayBuffer"
134384
134443
  );
134444
+ if (!(downloadBuffer instanceof ArrayBuffer)) {
134445
+ throw new Error("Failed to download deployment archive as ArrayBuffer.");
134446
+ }
134385
134447
  try {
134386
134448
  fs3.writeFileSync(compressedFileName, Buffer.from(downloadBuffer));
134387
134449
  } catch (err) {
@@ -134460,7 +134522,7 @@ var getConfirmation = async () => {
134460
134522
  }
134461
134523
  return answers2.changes;
134462
134524
  }
134463
- let answers = await import_inquirer2.default.prompt(questionPushChanges);
134525
+ const answers = await import_inquirer2.default.prompt(questionPushChanges);
134464
134526
  if (answers.changes !== "YES" && answers.changes !== "NO") {
134465
134527
  answers.changes = await fixConfirmation();
134466
134528
  }
@@ -134510,7 +134572,7 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
134510
134572
  options[secondResourceName] = localResource[secondId];
134511
134573
  }
134512
134574
  const remoteResource = await resourceGetFunction(options);
134513
- for (let [key, value] of Object.entries(
134575
+ for (const [key, value] of Object.entries(
134514
134576
  whitelistKeys(remoteResource, keys)
134515
134577
  )) {
134516
134578
  if (skipKeys.includes(key)) {
@@ -134519,28 +134581,30 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
134519
134581
  if (isEmpty(value) && isEmpty(localResource[key])) {
134520
134582
  continue;
134521
134583
  }
134522
- if (Array.isArray(value) && Array.isArray(localResource[key])) {
134523
- if (JSON.stringify(value) !== JSON.stringify(localResource[key])) {
134584
+ const localValue = localResource[key];
134585
+ if (Array.isArray(value) && Array.isArray(localValue)) {
134586
+ if (JSON.stringify(value) !== JSON.stringify(localValue)) {
134524
134587
  changes.push({
134525
134588
  id: localResource["$id"],
134526
134589
  key,
134527
134590
  remote: import_chalk4.default.red(value.join("\n")),
134528
- local: import_chalk4.default.green(localResource[key].join("\n"))
134591
+ local: import_chalk4.default.green(
134592
+ localValue.map((entry) => String(entry)).join("\n")
134593
+ )
134529
134594
  });
134530
134595
  }
134531
- } else if (value !== localResource[key]) {
134596
+ } else if (value !== localValue) {
134532
134597
  changes.push({
134533
134598
  id: localResource["$id"],
134534
134599
  key,
134535
- remote: import_chalk4.default.red(value),
134536
- local: import_chalk4.default.green(localResource[key])
134600
+ remote: import_chalk4.default.red(String(value ?? "")),
134601
+ local: import_chalk4.default.green(String(localValue ?? ""))
134537
134602
  });
134538
134603
  }
134539
134604
  }
134540
134605
  } catch (e) {
134541
- if (Number(e.code) !== 404) {
134542
- throw e;
134543
- }
134606
+ const isNotFound = e instanceof AppwriteException && Number(e.code) === 404;
134607
+ if (!isNotFound) throw e;
134544
134608
  }
134545
134609
  })
134546
134610
  );
@@ -135063,7 +135127,7 @@ var pullResources = async ({
135063
135127
  delete actions.collections;
135064
135128
  }
135065
135129
  if (cliConfig.all) {
135066
- for (let action of Object.values(actions)) {
135130
+ for (const action of Object.values(actions)) {
135067
135131
  cliConfig.all = true;
135068
135132
  await action({ returnOnZero: true });
135069
135133
  }
@@ -135302,7 +135366,6 @@ var initProject = async ({
135302
135366
  projectId,
135303
135367
  projectName
135304
135368
  } = {}) => {
135305
- let response = {};
135306
135369
  try {
135307
135370
  if (globalConfig2.getEndpoint() === "" || globalConfig2.getCookie() === "") {
135308
135371
  throw new Error(
@@ -135312,33 +135375,39 @@ var initProject = async ({
135312
135375
  const client2 = await sdkForConsole();
135313
135376
  const accountClient2 = new Account(client2);
135314
135377
  await accountClient2.get();
135315
- } catch (e) {
135378
+ } catch (_e) {
135316
135379
  error48(
135317
135380
  `Error Session not found. Please run '${EXECUTABLE_NAME} login' to create a session`
135318
135381
  );
135319
135382
  process.exit(1);
135320
135383
  }
135321
- let answers = {};
135384
+ let answers;
135322
135385
  if (!organizationId && !projectId && !projectName) {
135323
135386
  answers = await import_inquirer4.default.prompt(questionsInitProject);
135324
135387
  if (answers.override === false) {
135325
135388
  process.exit(1);
135326
135389
  }
135327
135390
  } else {
135328
- answers.start = "existing";
135329
- answers.project = {};
135330
- answers.organization = {};
135331
- answers.organization = organizationId ?? (await import_inquirer4.default.prompt([questionsInitProject[2]])).organization;
135332
- answers.project.name = projectName ?? (await import_inquirer4.default.prompt([questionsInitProject[3]])).project;
135333
- answers.project = projectId ?? (await import_inquirer4.default.prompt([questionsInitProject[4]])).id;
135391
+ const selectedOrganization = organizationId ?? (await import_inquirer4.default.prompt([questionsInitProject[2]])).organization;
135392
+ const selectedProjectName = projectName ?? (await import_inquirer4.default.prompt([questionsInitProject[3]])).project;
135393
+ const selectedProjectId = projectId ?? (await import_inquirer4.default.prompt([questionsInitProject[4]])).id;
135394
+ answers = {
135395
+ start: "existing",
135396
+ project: selectedProjectId,
135397
+ organization: selectedOrganization
135398
+ };
135334
135399
  try {
135335
135400
  const projectsService = await getProjectsService();
135336
- await projectsService.get(projectId);
135401
+ const existingProject = await projectsService.get(selectedProjectId);
135402
+ answers.project = existingProject;
135337
135403
  } catch (e) {
135338
- if (e.code === 404) {
135339
- answers.start = "new";
135340
- answers.id = answers.project;
135341
- answers.project = answers.project.name;
135404
+ if (e instanceof AppwriteException && e.code === 404) {
135405
+ answers = {
135406
+ start: "new",
135407
+ id: selectedProjectId,
135408
+ project: selectedProjectName,
135409
+ organization: selectedOrganization
135410
+ };
135342
135411
  } else {
135343
135412
  throw e;
135344
135413
  }
@@ -135347,10 +135416,26 @@ var initProject = async ({
135347
135416
  localConfig.clear();
135348
135417
  const url2 = new URL(DEFAULT_ENDPOINT);
135349
135418
  if (answers.start === "new") {
135419
+ let projectIdToCreate;
135420
+ let projectNameToCreate;
135421
+ switch (typeof answers.project) {
135422
+ case "string":
135423
+ projectIdToCreate = answers.id ?? answers.project;
135424
+ projectNameToCreate = answers.project;
135425
+ break;
135426
+ case "object":
135427
+ projectIdToCreate = answers.id ?? answers.project.$id;
135428
+ projectNameToCreate = answers.project.name ?? answers.project.$id;
135429
+ break;
135430
+ default:
135431
+ projectIdToCreate = answers.id;
135432
+ projectNameToCreate = "";
135433
+ break;
135434
+ }
135350
135435
  const projectsService = await getProjectsService();
135351
- response = await projectsService.create(
135352
- answers.id,
135353
- answers.project,
135436
+ const response = await projectsService.create(
135437
+ projectIdToCreate,
135438
+ projectNameToCreate,
135354
135439
  answers.organization,
135355
135440
  answers.region
135356
135441
  );
@@ -135361,10 +135446,22 @@ var initProject = async ({
135361
135446
  );
135362
135447
  }
135363
135448
  } else {
135364
- localConfig.setProject(answers.project["$id"]);
135365
- if (isCloud()) {
135449
+ let selectedProject;
135450
+ switch (typeof answers.project) {
135451
+ case "string":
135452
+ selectedProject = { $id: answers.project };
135453
+ break;
135454
+ case "object":
135455
+ selectedProject = answers.project;
135456
+ break;
135457
+ default:
135458
+ selectedProject = { $id: "" };
135459
+ break;
135460
+ }
135461
+ localConfig.setProject(selectedProject.$id);
135462
+ if (isCloud() && selectedProject.region) {
135366
135463
  localConfig.setEndpoint(
135367
- `https://${answers.project["region"]}.${url2.host}${url2.pathname}`
135464
+ `https://${selectedProject.region}.${url2.host}${url2.pathname}`
135368
135465
  );
135369
135466
  }
135370
135467
  }
@@ -135372,8 +135469,10 @@ var initProject = async ({
135372
135469
  `Project successfully ${answers.start === "existing" ? "linked" : "created"}. Details are now stored in appwrite.config.json file.`
135373
135470
  );
135374
135471
  if (answers.start === "existing") {
135375
- answers = await import_inquirer4.default.prompt(questionsInitProjectAutopull);
135376
- if (answers.autopull) {
135472
+ const autopullAnswers = await import_inquirer4.default.prompt(
135473
+ questionsInitProjectAutopull
135474
+ );
135475
+ if (autopullAnswers.autopull) {
135377
135476
  cliConfig.all = true;
135378
135477
  cliConfig.force = true;
135379
135478
  await pullResources({
@@ -135513,7 +135612,6 @@ var initFunction = async () => {
135513
135612
  fs5.mkdirSync(functionDir, { mode: 511 });
135514
135613
  fs5.mkdirSync(templatesDir, { mode: 511 });
135515
135614
  const repo = "https://github.com/appwrite/templates";
135516
- const api = `https://api.github.com/repos/appwrite/templates/contents/${answers.runtime.name}`;
135517
135615
  let selected = { template: "starter" };
135518
135616
  const sparse = (selected ? `${answers.runtime.name}/${selected.template}` : answers.runtime.name).toLowerCase();
135519
135617
  let gitInitCommands = `git clone --single-branch --depth 1 --sparse ${repo} .`;
@@ -135532,17 +135630,18 @@ var initFunction = async () => {
135532
135630
  cwd: templatesDir
135533
135631
  });
135534
135632
  } catch (err) {
135535
- if (err.message.includes("error: unknown option")) {
135633
+ const errorMessage = err instanceof Error ? err.message : String(err);
135634
+ if (errorMessage.includes("error: unknown option")) {
135536
135635
  throw new Error(
135537
- `${err.message}
135636
+ `${errorMessage}
135538
135637
 
135539
135638
  Suggestion: Try updating your git to the latest version, then trying to run this command again.`
135540
135639
  );
135541
- } else if (err.message.includes(
135640
+ } else if (errorMessage.includes(
135542
135641
  "is not recognized as an internal or external command,"
135543
- ) || err.message.includes("command not found")) {
135642
+ ) || errorMessage.includes("command not found")) {
135544
135643
  throw new Error(
135545
- `${err.message}
135644
+ `${errorMessage}
135546
135645
 
135547
135646
  Suggestion: It appears that git is not installed, try installing git then trying to run this command again.`
135548
135647
  );
@@ -135564,9 +135663,9 @@ Suggestion: It appears that git is not installed, try installing git then trying
135564
135663
  }
135565
135664
  }
135566
135665
  const copyRecursiveSync = (src, dest) => {
135567
- let exists = fs5.existsSync(src);
135568
- let stats = exists && fs5.statSync(src);
135569
- let isDirectory = exists && stats && stats.isDirectory();
135666
+ const exists = fs5.existsSync(src);
135667
+ const stats = exists && fs5.statSync(src);
135668
+ const isDirectory = exists && stats && stats.isDirectory();
135570
135669
  if (isDirectory) {
135571
135670
  if (!fs5.existsSync(dest)) {
135572
135671
  fs5.mkdirSync(dest);
@@ -135594,7 +135693,7 @@ Suggestion: It appears that git is not installed, try installing git then trying
135594
135693
  newReadmeFile[0] = `# ${answers.name}`;
135595
135694
  newReadmeFile.splice(1, 2);
135596
135695
  fs5.writeFileSync(readmePath, newReadmeFile.join("\n"));
135597
- let data = {
135696
+ const data = {
135598
135697
  $id: functionId,
135599
135698
  name: answers.name,
135600
135699
  runtime: answers.runtime.id,
@@ -135650,14 +135749,15 @@ var initSite = async () => {
135650
135749
  }
135651
135750
  templateDetails = response.templates[0];
135652
135751
  } catch (err) {
135752
+ const errorMessage = err instanceof Error ? err.message : String(err);
135653
135753
  throw new Error(
135654
- `Failed to fetch template for framework ${answers.framework.key}: ${err.message}`
135754
+ `Failed to fetch template for framework ${answers.framework.key}: ${errorMessage}`
135655
135755
  );
135656
135756
  }
135657
135757
  fs5.mkdirSync(siteDir, { mode: 511 });
135658
135758
  fs5.mkdirSync(templatesDir, { mode: 511 });
135659
135759
  const repo = `https://github.com/${templateDetails.providerOwner}/${templateDetails.providerRepositoryId}`;
135660
- let selected = {
135760
+ const selected = {
135661
135761
  template: templateDetails.frameworks[0].providerRootDirectory
135662
135762
  };
135663
135763
  let dirSetupCommands = "";
@@ -135682,12 +135782,12 @@ var initSite = async () => {
135682
135782
  git config remote.origin.tagopt --no-tags
135683
135783
  `.trim();
135684
135784
  }
135685
- let windowsGitCloneCommands = `
135785
+ const windowsGitCloneCommands = `
135686
135786
  $tag = (git ls-remote --tags origin "${templateDetails.providerVersion}" | Select-Object -Last 1) -replace '.*refs/tags/', ''
135687
135787
  git fetch --depth=1 origin "refs/tags/$tag"
135688
135788
  git checkout FETCH_HEAD
135689
135789
  `.trim();
135690
- let unixGitCloneCommands = `
135790
+ const unixGitCloneCommands = `
135691
135791
  git fetch --depth=1 origin refs/tags/$(git ls-remote --tags origin "${templateDetails.providerVersion}" | tail -n 1 | awk -F '/' '{print $3}')
135692
135792
  git checkout FETCH_HEAD
135693
135793
  `.trim();
@@ -135705,17 +135805,18 @@ var initSite = async () => {
135705
135805
  shell: usedShell
135706
135806
  });
135707
135807
  } catch (err) {
135708
- if (err.message.includes("error: unknown option")) {
135808
+ const errorMessage = err instanceof Error ? err.message : String(err);
135809
+ if (errorMessage.includes("error: unknown option")) {
135709
135810
  throw new Error(
135710
- `${err.message}
135811
+ `${errorMessage}
135711
135812
 
135712
135813
  Suggestion: Try updating your git to the latest version, then trying to run this command again.`
135713
135814
  );
135714
- } else if (err.message.includes(
135815
+ } else if (errorMessage.includes(
135715
135816
  "is not recognized as an internal or external command,"
135716
- ) || err.message.includes("command not found")) {
135817
+ ) || errorMessage.includes("command not found")) {
135717
135818
  throw new Error(
135718
- `${err.message}
135819
+ `${errorMessage}
135719
135820
 
135720
135821
  Suggestion: It appears that git is not installed, try installing git then trying to run this command again.`
135721
135822
  );
@@ -135736,24 +135837,22 @@ Suggestion: It appears that git is not installed, try installing git then trying
135736
135837
  newReadmeFile[0] = `# ${answers.name}`;
135737
135838
  newReadmeFile.splice(1, 2);
135738
135839
  fs5.writeFileSync(readmePath, newReadmeFile.join("\n"));
135739
- let vars = (templateDetails.variables ?? []).map((variable) => {
135740
- let value = variable.value;
135840
+ const vars = {};
135841
+ for (const variable of templateDetails.variables ?? []) {
135842
+ let value = variable.value ?? "";
135741
135843
  const replacements = {
135742
135844
  "{apiEndpoint}": globalConfig2.getEndpoint(),
135743
- "{projectId}": localConfig.getProject().projectId,
135744
- "{projectName}": localConfig.getProject().projectName
135845
+ "{projectId}": localConfig.getProject().projectId ?? "",
135846
+ "{projectName}": localConfig.getProject().projectName ?? ""
135745
135847
  };
135746
135848
  for (const placeholder in replacements) {
135747
- if (value?.includes(placeholder)) {
135849
+ if (value.includes(placeholder)) {
135748
135850
  value = value.replace(placeholder, replacements[placeholder]);
135749
135851
  }
135750
135852
  }
135751
- return {
135752
- key: variable.name,
135753
- value
135754
- };
135755
- });
135756
- let data = {
135853
+ vars[variable.name] = value;
135854
+ }
135855
+ const data = {
135757
135856
  $id: siteId,
135758
135857
  name: answers.name,
135759
135858
  framework: answers.framework.key,
@@ -137220,12 +137319,10 @@ var typesCommand = actionRunner(
137220
137319
  log(`Directory: ${outputDirectory} does not exist, creating...`);
137221
137320
  fs10.mkdirSync(outputDirectory, { recursive: true });
137222
137321
  }
137223
- let tables = localConfig.getTables();
137322
+ const tables = localConfig.getTables();
137224
137323
  let collections = [];
137225
- let dataSource = "tables";
137226
137324
  if (tables.length === 0) {
137227
137325
  collections = localConfig.getCollections();
137228
- dataSource = "collections";
137229
137326
  if (collections.length === 0) {
137230
137327
  const configFileName = path9.basename(localConfig.path);
137231
137328
  throw new Error(
@@ -137680,9 +137777,8 @@ async function dockerStart(func, variables, port) {
137680
137777
  try {
137681
137778
  await waitUntilPortOpen(port);
137682
137779
  } catch (err) {
137683
- error48(
137684
- "Failed to start function with error: " + (err.message ? err.message : err.toString())
137685
- );
137780
+ const message = err instanceof Error ? err.message : String(err);
137781
+ error48(`Failed to start function with error: ${message}`);
137686
137782
  return;
137687
137783
  }
137688
137784
  success2(`Visit http://localhost:${port}/ to execute your function.`);
@@ -137849,7 +137945,7 @@ var runFunction = async ({
137849
137945
  });
137850
137946
  } catch (err) {
137851
137947
  warn(
137852
- "Remote variables not fetched. Production environment variables will not be available. Reason: " + err.message
137948
+ "Remote variables not fetched. Production environment variables will not be available. Reason: " + getErrorMessage(err)
137853
137949
  );
137854
137950
  }
137855
137951
  }
@@ -137873,7 +137969,7 @@ var runFunction = async ({
137873
137969
  await JwtManager.setup(userId, func.scopes ?? []);
137874
137970
  } catch (err) {
137875
137971
  warn(
137876
- "Dynamic API key not generated. Header x-appwrite-key will not be set. Reason: " + err.message
137972
+ "Dynamic API key not generated. Header x-appwrite-key will not be set. Reason: " + getErrorMessage(err)
137877
137973
  );
137878
137974
  }
137879
137975
  const headers = {};
@@ -138373,7 +138469,7 @@ var Spinner = class _Spinner {
138373
138469
  static stop() {
138374
138470
  _Spinner.updatesBar.stop();
138375
138471
  }
138376
- static formatter(options, params, payload) {
138472
+ static formatter(_options, _params, payload) {
138377
138473
  const status = payload.status.padEnd(12);
138378
138474
  const middle = `${payload.resource} (${payload.id})`.padEnd(40);
138379
138475
  let prefix = import_chalk8.default.cyan(payload.prefix ?? "\u29D7");
@@ -138458,7 +138554,7 @@ var Pools = class {
138458
138554
  return true;
138459
138555
  }
138460
138556
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
138461
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
138557
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
138462
138558
  if (steps > 1 && iteration === 1) {
138463
138559
  this.pollMaxDebounces *= steps;
138464
138560
  log(
@@ -138484,7 +138580,7 @@ var Pools = class {
138484
138580
  return true;
138485
138581
  }
138486
138582
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
138487
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
138583
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
138488
138584
  if (steps > 1 && iteration === 1) {
138489
138585
  this.pollMaxDebounces *= steps;
138490
138586
  log(
@@ -138500,7 +138596,10 @@ var Pools = class {
138500
138596
  return false;
138501
138597
  }
138502
138598
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
138503
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
138599
+ const steps = Math.max(
138600
+ 1,
138601
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
138602
+ );
138504
138603
  if (steps > 1 && iteration === 1) {
138505
138604
  this.pollMaxDebounces *= steps;
138506
138605
  log(
@@ -138543,7 +138642,10 @@ var Pools = class {
138543
138642
  return false;
138544
138643
  }
138545
138644
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
138546
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
138645
+ const steps = Math.max(
138646
+ 1,
138647
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
138648
+ );
138547
138649
  if (steps > 1 && iteration === 1) {
138548
138650
  this.pollMaxDebounces *= steps;
138549
138651
  log(
@@ -138592,7 +138694,7 @@ var Pools = class {
138592
138694
  return false;
138593
138695
  }
138594
138696
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
138595
- let steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
138697
+ const steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
138596
138698
  if (steps > 1 && iteration === 1) {
138597
138699
  this.pollMaxDebounces *= steps;
138598
138700
  log(
@@ -138685,7 +138787,7 @@ var Attributes = class {
138685
138787
  }
138686
138788
  return answers2.changes;
138687
138789
  }
138688
- let answers = await import_inquirer6.default.prompt(questionPushChanges2);
138790
+ const answers = await import_inquirer6.default.prompt(questionPushChanges2);
138689
138791
  if (answers.changes !== "YES" && answers.changes !== "NO") {
138690
138792
  answers.changes = await fixConfirmation();
138691
138793
  }
@@ -138728,8 +138830,8 @@ var Attributes = class {
138728
138830
  const keyName = `${import_chalk9.default.yellow(local.key)} in ${collection.name} (${collection["$id"]})`;
138729
138831
  const action = import_chalk9.default.cyan(recreating ? "recreating" : "changing");
138730
138832
  let reason = "";
138731
- let attribute = recreating ? remote : local;
138732
- for (let key of Object.keys(remote)) {
138833
+ const attribute = recreating ? remote : local;
138834
+ for (const key of Object.keys(remote)) {
138733
138835
  if (!KeysAttributes.has(key)) {
138734
138836
  continue;
138735
138837
  }
@@ -139239,7 +139341,7 @@ var Attributes = class {
139239
139341
  createIndexes = async (indexes, collection) => {
139240
139342
  log(`Creating indexes ...`);
139241
139343
  const databasesService = await getDatabasesService(this.client);
139242
- for (let index of indexes) {
139344
+ for (const index of indexes) {
139243
139345
  await databasesService.createIndex({
139244
139346
  databaseId: collection["databaseId"],
139245
139347
  collectionId: collection["$id"],
@@ -139263,7 +139365,7 @@ var Attributes = class {
139263
139365
  };
139264
139366
  createAttributes = async (attributes, collection) => {
139265
139367
  log(`Creating attributes ...`);
139266
- for (let attribute of attributes) {
139368
+ for (const attribute of attributes) {
139267
139369
  if (attribute.side !== "child") {
139268
139370
  await this.createAttribute(
139269
139371
  collection["databaseId"],
@@ -139287,7 +139389,7 @@ var Attributes = class {
139287
139389
  };
139288
139390
  createColumns = async (columns, table) => {
139289
139391
  log(`Creating columns ...`);
139290
- for (let column of columns) {
139392
+ for (const column of columns) {
139291
139393
  if (column.side !== "child") {
139292
139394
  await this.createAttribute(table["databaseId"], table["$id"], column);
139293
139395
  }
@@ -139309,18 +139411,37 @@ var Attributes = class {
139309
139411
 
139310
139412
  // lib/commands/utils/database-sync.ts
139311
139413
  var import_chalk10 = __toESM(require_source(), 1);
139414
+ var isTablesDBResource = (value) => {
139415
+ if (!value || typeof value !== "object") {
139416
+ return false;
139417
+ }
139418
+ return "$id" in value && typeof value.$id === "string" && "name" in value && typeof value.name === "string" && "enabled" in value && typeof value.enabled === "boolean";
139419
+ };
139420
+ var getSyncErrorMessage = (err) => {
139421
+ if (err instanceof AppwriteException) {
139422
+ return err.message;
139423
+ }
139424
+ if (err instanceof Error) {
139425
+ return err.message;
139426
+ }
139427
+ return String(err);
139428
+ };
139312
139429
  var checkAndApplyTablesDBChanges = async () => {
139313
139430
  log("Checking for tablesDB changes ...");
139314
139431
  const localTablesDBs = localConfig.getTablesDBs();
139315
- const { databases: remoteTablesDBs } = await paginate(
139432
+ const paginatedResult = await paginate(
139316
139433
  async (args) => {
139317
139434
  const tablesDBService = await getTablesDBService();
139318
- return await tablesDBService.list(args.queries || []);
139435
+ const queries = Array.isArray(args.queries) ? args.queries.filter(
139436
+ (query) => typeof query === "string"
139437
+ ) : [];
139438
+ return await tablesDBService.list(queries);
139319
139439
  },
139320
139440
  {},
139321
139441
  100,
139322
139442
  "databases"
139323
139443
  );
139444
+ const remoteTablesDBs = Array.isArray(paginatedResult.databases) ? paginatedResult.databases.filter(isTablesDBResource) : [];
139324
139445
  if (localTablesDBs.length === 0 && remoteTablesDBs.length === 0) {
139325
139446
  return { applied: false, resyncNeeded: false };
139326
139447
  }
@@ -139342,9 +139463,7 @@ var checkAndApplyTablesDBChanges = async () => {
139342
139463
  }
139343
139464
  }
139344
139465
  for (const localDB of localTablesDBs) {
139345
- const remoteDB = remoteTablesDBs.find(
139346
- (db) => db.$id === localDB.$id
139347
- );
139466
+ const remoteDB = remoteTablesDBs.find((db) => db.$id === localDB.$id);
139348
139467
  if (!remoteDB) {
139349
139468
  toCreate.push(localDB);
139350
139469
  changes.push({
@@ -139411,7 +139530,7 @@ var checkAndApplyTablesDBChanges = async () => {
139411
139530
  needsResync = true;
139412
139531
  } catch (e) {
139413
139532
  error48(
139414
- `Failed to delete database ${db.name} ( ${db.$id} ): ${e.message}`
139533
+ `Failed to delete database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
139415
139534
  );
139416
139535
  throw new Error(
139417
139536
  `Database sync failed during deletion of ${db.$id}. Some changes may have been applied.`
@@ -139426,7 +139545,7 @@ var checkAndApplyTablesDBChanges = async () => {
139426
139545
  success2(`Created ${db.name} ( ${db.$id} )`);
139427
139546
  } catch (e) {
139428
139547
  error48(
139429
- `Failed to create database ${db.name} ( ${db.$id} ): ${e.message}`
139548
+ `Failed to create database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
139430
139549
  );
139431
139550
  throw new Error(
139432
139551
  `Database sync failed during creation of ${db.$id}. Some changes may have been applied.`
@@ -139441,7 +139560,7 @@ var checkAndApplyTablesDBChanges = async () => {
139441
139560
  success2(`Updated ${db.name} ( ${db.$id} )`);
139442
139561
  } catch (e) {
139443
139562
  error48(
139444
- `Failed to update database ${db.name} ( ${db.$id} ): ${e.message}`
139563
+ `Failed to update database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
139445
139564
  );
139446
139565
  throw new Error(
139447
139566
  `Database sync failed during update of ${db.$id}. Some changes may have been applied.`
@@ -139675,7 +139794,7 @@ var Push = class {
139675
139794
  }
139676
139795
  if (settings.services) {
139677
139796
  this.log("Applying service statuses ...");
139678
- for (let [service, status] of Object.entries(settings.services)) {
139797
+ for (const [service, status] of Object.entries(settings.services)) {
139679
139798
  await projectsService.updateServiceStatus({
139680
139799
  projectId,
139681
139800
  service,
@@ -139721,7 +139840,7 @@ var Push = class {
139721
139840
  }
139722
139841
  if (settings.auth.methods) {
139723
139842
  this.log("Applying auth methods statuses ...");
139724
- for (let [method, status] of Object.entries(settings.auth.methods)) {
139843
+ for (const [method, status] of Object.entries(settings.auth.methods)) {
139725
139844
  await projectsService.updateAuthStatus({
139726
139845
  projectId,
139727
139846
  method,
@@ -140025,7 +140144,7 @@ var Push = class {
140025
140144
  ([key, value]) => ({ key, value })
140026
140145
  );
140027
140146
  }
140028
- } catch (error49) {
140147
+ } catch (_error) {
140029
140148
  envVariables = [];
140030
140149
  }
140031
140150
  await Promise.all(
@@ -140322,7 +140441,7 @@ var Push = class {
140322
140441
  ([key, value]) => ({ key, value })
140323
140442
  );
140324
140443
  }
140325
- } catch (error49) {
140444
+ } catch (_error) {
140326
140445
  envVariables = [];
140327
140446
  }
140328
140447
  await Promise.all(
@@ -140489,7 +140608,7 @@ var Push = class {
140489
140608
  skipConfirmation,
140490
140609
  this.projectClient
140491
140610
  );
140492
- let tablesChanged = /* @__PURE__ */ new Set();
140611
+ const tablesChanged = /* @__PURE__ */ new Set();
140493
140612
  const errors = [];
140494
140613
  await Promise.all(
140495
140614
  tables.map(async (table) => {
@@ -140543,7 +140662,7 @@ var Push = class {
140543
140662
  }
140544
140663
  })
140545
140664
  );
140546
- for (let table of tables) {
140665
+ for (const table of tables) {
140547
140666
  let columns = table.columns;
140548
140667
  let indexes = table.indexes;
140549
140668
  let hadChanges = false;
@@ -140822,7 +140941,7 @@ var pushSettings = async () => {
140822
140941
  checkDeployConditions(localConfig);
140823
140942
  try {
140824
140943
  const projectsService = await getProjectsService();
140825
- let response = await projectsService.get(
140944
+ const response = await projectsService.get(
140826
140945
  localConfig.getProject().projectId
140827
140946
  );
140828
140947
  const remoteSettings = createSettingsObject(response);
@@ -140855,7 +140974,7 @@ var pushSettings = async () => {
140855
140974
  return;
140856
140975
  }
140857
140976
  }
140858
- } catch (e) {
140977
+ } catch (_e) {
140859
140978
  }
140860
140979
  try {
140861
140980
  log("Pushing project settings ...");
@@ -140905,7 +141024,7 @@ var pushSite = async ({
140905
141024
  );
140906
141025
  return;
140907
141026
  }
140908
- let sites2 = siteIds.map((id) => {
141027
+ const sites2 = siteIds.map((id) => {
140909
141028
  const sites3 = localConfig.getSites();
140910
141029
  const site = sites3.find((s) => s.$id === id);
140911
141030
  if (!site) {
@@ -140914,7 +141033,7 @@ var pushSite = async ({
140914
141033
  return site;
140915
141034
  });
140916
141035
  log("Validating sites ...");
140917
- for (let site of sites2) {
141036
+ for (const site of sites2) {
140918
141037
  if (!site.buildCommand) {
140919
141038
  log(`Site ${site.name} is missing build command.`);
140920
141039
  const answers = await import_inquirer7.default.prompt(questionsGetEntrypoint);
@@ -141025,7 +141144,7 @@ var pushFunction = async ({
141025
141144
  );
141026
141145
  return;
141027
141146
  }
141028
- let functions2 = functionIds.map((id) => {
141147
+ const functions2 = functionIds.map((id) => {
141029
141148
  const functions3 = localConfig.getFunctions();
141030
141149
  const func = functions3.find((f) => f.$id === id);
141031
141150
  if (!func) {
@@ -141034,7 +141153,7 @@ var pushFunction = async ({
141034
141153
  return func;
141035
141154
  });
141036
141155
  log("Validating functions ...");
141037
- for (let func of functions2) {
141156
+ for (const func of functions2) {
141038
141157
  if (!func.entrypoint) {
141039
141158
  log(`Function ${func.name} is missing an entrypoint.`);
141040
141159
  const answers = await import_inquirer7.default.prompt(questionsGetEntrypoint);
@@ -141175,7 +141294,7 @@ var pushTable = async ({
141175
141294
  });
141176
141295
  }
141177
141296
  }
141178
- } catch (e) {
141297
+ } catch (_e) {
141179
141298
  }
141180
141299
  }
141181
141300
  if (tablesToDelete.length > 0) {
@@ -141322,7 +141441,7 @@ var pushCollection = async () => {
141322
141441
  }
141323
141442
  };
141324
141443
  var pushBucket = async () => {
141325
- let bucketIds = [];
141444
+ const bucketIds = [];
141326
141445
  const configBuckets = localConfig.getBuckets();
141327
141446
  if (cliConfig.all) {
141328
141447
  checkDeployConditions(localConfig);
@@ -141341,7 +141460,7 @@ var pushBucket = async () => {
141341
141460
  );
141342
141461
  return;
141343
141462
  }
141344
- let buckets = [];
141463
+ const buckets = [];
141345
141464
  for (const bucketId of bucketIds) {
141346
141465
  const idBuckets = configBuckets.filter((b) => b.$id === bucketId);
141347
141466
  buckets.push(...idBuckets);
@@ -141372,7 +141491,7 @@ var pushBucket = async () => {
141372
141491
  }
141373
141492
  };
141374
141493
  var pushTeam = async () => {
141375
- let teamIds = [];
141494
+ const teamIds = [];
141376
141495
  const configTeams = localConfig.getTeams();
141377
141496
  if (cliConfig.all) {
141378
141497
  checkDeployConditions(localConfig);
@@ -141391,7 +141510,7 @@ var pushTeam = async () => {
141391
141510
  );
141392
141511
  return;
141393
141512
  }
141394
- let teams2 = [];
141513
+ const teams2 = [];
141395
141514
  for (const teamId of teamIds) {
141396
141515
  const idTeams = configTeams.filter((t) => t.$id === teamId);
141397
141516
  teams2.push(...idTeams);
@@ -141422,7 +141541,7 @@ var pushTeam = async () => {
141422
141541
  }
141423
141542
  };
141424
141543
  var pushMessagingTopic = async () => {
141425
- let topicsIds = [];
141544
+ const topicsIds = [];
141426
141545
  const configTopics = localConfig.getMessagingTopics();
141427
141546
  if (cliConfig.all) {
141428
141547
  checkDeployConditions(localConfig);
@@ -141441,7 +141560,7 @@ var pushMessagingTopic = async () => {
141441
141560
  );
141442
141561
  return;
141443
141562
  }
141444
- let topics = [];
141563
+ const topics = [];
141445
141564
  for (const topicId of topicsIds) {
141446
141565
  const idTopic = configTopics.filter((b) => b.$id === topicId);
141447
141566
  topics.push(...idTopic);
@@ -141517,7 +141636,7 @@ var isInstalledViaNpm = () => {
141517
141636
  return true;
141518
141637
  }
141519
141638
  return false;
141520
- } catch (e) {
141639
+ } catch (_e) {
141521
141640
  return false;
141522
141641
  }
141523
141642
  };
@@ -141525,7 +141644,7 @@ var isInstalledViaHomebrew = () => {
141525
141644
  try {
141526
141645
  const scriptPath = process.argv[1];
141527
141646
  return scriptPath.includes("/opt/homebrew/") || scriptPath.includes("/usr/local/Cellar/");
141528
- } catch (e) {
141647
+ } catch (_e) {
141529
141648
  return false;
141530
141649
  }
141531
141650
  };
@@ -141555,13 +141674,14 @@ var updateViaNpm = async () => {
141555
141674
  success2("Updated to latest version via npm!");
141556
141675
  hint("Run 'appwrite --version' to verify the new version.");
141557
141676
  } catch (e) {
141558
- if (e.message.includes("EEXIST") || e.message.includes("file already exists")) {
141677
+ const message = getErrorMessage(e);
141678
+ if (message.includes("EEXIST") || message.includes("file already exists")) {
141559
141679
  console.log("");
141560
141680
  success2("Latest version is already installed via npm!");
141561
141681
  hint("The CLI is up to date. Run 'appwrite --version' to verify.");
141562
141682
  } else {
141563
141683
  console.log("");
141564
- error48(`Failed to update via npm: ${e.message}`);
141684
+ error48(`Failed to update via npm: ${message}`);
141565
141685
  hint(`Try running: npm install -g ${NPM_PACKAGE_NAME}@latest --force`);
141566
141686
  }
141567
141687
  }
@@ -141573,13 +141693,14 @@ var updateViaHomebrew = async () => {
141573
141693
  success2("Updated to latest version via Homebrew!");
141574
141694
  hint("Run 'appwrite --version' to verify the new version.");
141575
141695
  } catch (e) {
141576
- if (e.message.includes("already installed") || e.message.includes("up-to-date")) {
141696
+ const message = getErrorMessage(e);
141697
+ if (message.includes("already installed") || message.includes("up-to-date")) {
141577
141698
  console.log("");
141578
141699
  success2("Latest version is already installed via Homebrew!");
141579
141700
  hint("The CLI is up to date. Run 'appwrite --version' to verify.");
141580
141701
  } else {
141581
141702
  console.log("");
141582
- error48(`Failed to update via Homebrew: ${e.message}`);
141703
+ error48(`Failed to update via Homebrew: ${message}`);
141583
141704
  hint("Try running: brew upgrade appwrite");
141584
141705
  }
141585
141706
  }
@@ -141654,8 +141775,9 @@ var updateCli = async ({ manual } = {}) => {
141654
141775
  await chooseUpdateMethod(latestVersion);
141655
141776
  }
141656
141777
  } catch (e) {
141778
+ const message = getErrorMessage(e);
141657
141779
  console.log("");
141658
- error48(`Failed to check for updates: ${e.message}`);
141780
+ error48(`Failed to check for updates: ${message}`);
141659
141781
  hint(`You can manually check for updates at: ${GITHUB_RELEASES_URL}`);
141660
141782
  }
141661
141783
  };
@@ -141828,7 +141950,7 @@ var BaseDatabasesGenerator = class {
141828
141950
  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";
141829
141951
 
141830
141952
  // lib/commands/generators/typescript/templates/databases.ts.hbs
141831
- 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';
141953
+ 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';
141832
141954
 
141833
141955
  // lib/commands/generators/typescript/templates/index.ts.hbs
141834
141956
  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';
@@ -141995,7 +142117,7 @@ ${dbReturnTypes}
141995
142117
 
141996
142118
  export type DatabaseHandle<D extends DatabaseId> = {
141997
142119
  use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => DatabaseTableMap[D][T];
141998
- ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: any[]; indexes?: any[] }) => Promise<Models.Table>;
142120
+ ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: object[]; indexes?: object[] }) => Promise<Models.Table>;
141999
142121
  update: <T extends keyof DatabaseTableMap[D] & string>(tableId: T, options?: { name?: string; permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean }) => Promise<Models.Table>;
142000
142122
  delete: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => Promise<void>;` : ""}
142001
142123
  };
@@ -142062,26 +142184,26 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
142062
142184
  generateBulkMethods(supportsBulk) {
142063
142185
  if (!supportsBulk) return "";
142064
142186
  return `
142065
- createMany: (rows: any[], options?: { transactionId?: string }) =>
142187
+ createMany: (rows: object[], options?: { transactionId?: string }) =>
142066
142188
  tablesDB.createRows({
142067
142189
  databaseId,
142068
142190
  tableId,
142069
142191
  rows,
142070
142192
  transactionId: options?.transactionId,
142071
142193
  }),
142072
- updateMany: (data: any, options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
142194
+ updateMany: (data: object, options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
142073
142195
  tablesDB.updateRows({
142074
142196
  databaseId,
142075
142197
  tableId,
142076
142198
  data,
142077
- queries: options?.queries?.(createQueryBuilder()),
142199
+ queries: options?.queries?.(createQueryBuilder<T>()),
142078
142200
  transactionId: options?.transactionId,
142079
142201
  }),
142080
- deleteMany: (options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
142202
+ deleteMany: (options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
142081
142203
  tablesDB.deleteRows({
142082
142204
  databaseId,
142083
142205
  tableId,
142084
- queries: options?.queries?.(createQueryBuilder()),
142206
+ queries: options?.queries?.(createQueryBuilder<T>()),
142085
142207
  transactionId: options?.transactionId,
142086
142208
  }),`;
142087
142209
  }
@@ -142095,9 +142217,9 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
142095
142217
  return `
142096
142218
  // Remove bulk methods for tables with relationships
142097
142219
  if (!hasBulkMethods(databaseId, tableId)) {
142098
- delete (api as any).createMany;
142099
- delete (api as any).updateMany;
142100
- delete (api as any).deleteMany;
142220
+ delete (api as Record<string, unknown>).createMany;
142221
+ delete (api as Record<string, unknown>).updateMany;
142222
+ delete (api as Record<string, unknown>).deleteMany;
142101
142223
  }`;
142102
142224
  }
142103
142225
  generateDatabasesFile(config2, importExt) {
@@ -142244,8 +142366,9 @@ var generateAction = async (options) => {
142244
142366
  }
142245
142367
  } catch (err) {
142246
142368
  const supported = getSupportedLanguages().join(", ");
142369
+ const message = err instanceof Error ? err.message : String(err);
142247
142370
  error48(
142248
- `${err.message}
142371
+ `${message}
142249
142372
  Use --language to specify the target language. Supported: ${supported}`
142250
142373
  );
142251
142374
  process.exit(1);
@@ -142300,7 +142423,8 @@ Use --language to specify the target language. Supported: ${supported}`
142300
142423
  );
142301
142424
  }
142302
142425
  } catch (err) {
142303
- error48(`Failed to generate SDK: ${err.message}`);
142426
+ const message = err instanceof Error ? err.message : String(err);
142427
+ error48(`Failed to generate SDK: ${message}`);
142304
142428
  process.exit(1);
142305
142429
  }
142306
142430
  };
@@ -146288,12 +146412,12 @@ async function checkVersion() {
146288
146412
  } else {
146289
146413
  process.stdout.write(import_chalk13.default.blue("\n\u{1F680} You are running a pre-release or development version.") + "\n");
146290
146414
  }
146291
- } catch (error49) {
146415
+ } catch (_error) {
146292
146416
  process.stdout.write(import_chalk13.default.gray("\n(Unable to check for updates)") + "\n");
146293
146417
  }
146294
146418
  }
146295
146419
  if (process.argv.includes("-v") || process.argv.includes("--version")) {
146296
- (async () => {
146420
+ void (async () => {
146297
146421
  await checkVersion();
146298
146422
  process.exit(0);
146299
146423
  })();