@gadgetinc/ggt 0.4.10 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +165 -93
  2. package/lib/__generated__/graphql.js +66 -1
  3. package/lib/__generated__/graphql.js.map +1 -1
  4. package/lib/commands/deploy.js +328 -230
  5. package/lib/commands/deploy.js.map +1 -1
  6. package/lib/commands/dev.js +445 -0
  7. package/lib/commands/dev.js.map +1 -0
  8. package/lib/commands/list.js +27 -19
  9. package/lib/commands/list.js.map +1 -1
  10. package/lib/commands/login.js +15 -11
  11. package/lib/commands/login.js.map +1 -1
  12. package/lib/commands/logout.js +5 -5
  13. package/lib/commands/logout.js.map +1 -1
  14. package/lib/commands/open.js +200 -0
  15. package/lib/commands/open.js.map +1 -0
  16. package/lib/commands/pull.js +128 -0
  17. package/lib/commands/pull.js.map +1 -0
  18. package/lib/commands/push.js +126 -0
  19. package/lib/commands/push.js.map +1 -0
  20. package/lib/commands/root.js +46 -28
  21. package/lib/commands/root.js.map +1 -1
  22. package/lib/commands/status.js +61 -0
  23. package/lib/commands/status.js.map +1 -0
  24. package/lib/commands/version.js +6 -6
  25. package/lib/commands/version.js.map +1 -1
  26. package/lib/commands/whoami.js +6 -6
  27. package/lib/commands/whoami.js.map +1 -1
  28. package/lib/ggt.js +33 -8
  29. package/lib/ggt.js.map +1 -1
  30. package/lib/main.js +5 -0
  31. package/lib/main.js.map +1 -0
  32. package/lib/services/app/api/api.js +191 -0
  33. package/lib/services/app/api/api.js.map +1 -0
  34. package/lib/services/app/api/operation.js +12 -0
  35. package/lib/services/app/api/operation.js.map +1 -0
  36. package/lib/services/app/app.js +44 -10
  37. package/lib/services/app/app.js.map +1 -1
  38. package/lib/services/app/{edit/client.js → client.js} +29 -19
  39. package/lib/services/app/client.js.map +1 -0
  40. package/lib/services/app/edit/edit.js +67 -31
  41. package/lib/services/app/edit/edit.js.map +1 -1
  42. package/lib/services/app/edit/operation.js +4 -3
  43. package/lib/services/app/edit/operation.js.map +1 -1
  44. package/lib/services/app/{edit/error.js → error.js} +6 -6
  45. package/lib/services/app/error.js.map +1 -0
  46. package/lib/services/command/arg.js +4 -4
  47. package/lib/services/command/arg.js.map +1 -1
  48. package/lib/services/command/command.js +9 -7
  49. package/lib/services/command/command.js.map +1 -1
  50. package/lib/services/command/context.js +82 -20
  51. package/lib/services/command/context.js.map +1 -1
  52. package/lib/services/config/config.js +4 -7
  53. package/lib/services/config/config.js.map +1 -1
  54. package/lib/services/config/env.js +1 -1
  55. package/lib/services/config/env.js.map +1 -1
  56. package/lib/services/filesync/changes.js +76 -37
  57. package/lib/services/filesync/changes.js.map +1 -1
  58. package/lib/services/filesync/conflicts.js +10 -9
  59. package/lib/services/filesync/conflicts.js.map +1 -1
  60. package/lib/services/filesync/directory.js +16 -1
  61. package/lib/services/filesync/directory.js.map +1 -1
  62. package/lib/services/filesync/error.js +96 -27
  63. package/lib/services/filesync/error.js.map +1 -1
  64. package/lib/services/filesync/filesync.js +448 -490
  65. package/lib/services/filesync/filesync.js.map +1 -1
  66. package/lib/services/filesync/hashes.js +8 -5
  67. package/lib/services/filesync/hashes.js.map +1 -1
  68. package/lib/services/filesync/strategy.js +59 -0
  69. package/lib/services/filesync/strategy.js.map +1 -0
  70. package/lib/services/filesync/sync-json.js +475 -0
  71. package/lib/services/filesync/sync-json.js.map +1 -0
  72. package/lib/services/http/auth.js +30 -1
  73. package/lib/services/http/auth.js.map +1 -1
  74. package/lib/services/http/http.js +5 -0
  75. package/lib/services/http/http.js.map +1 -1
  76. package/lib/services/output/confirm.js +149 -0
  77. package/lib/services/output/confirm.js.map +1 -0
  78. package/lib/services/output/footer.js +22 -0
  79. package/lib/services/output/footer.js.map +1 -0
  80. package/lib/services/output/log/format/pretty.js +2 -1
  81. package/lib/services/output/log/format/pretty.js.map +1 -1
  82. package/lib/services/output/log/logger.js +13 -5
  83. package/lib/services/output/log/logger.js.map +1 -1
  84. package/lib/services/output/log/structured.js +2 -2
  85. package/lib/services/output/log/structured.js.map +1 -1
  86. package/lib/services/output/output.js +197 -0
  87. package/lib/services/output/output.js.map +1 -0
  88. package/lib/services/output/print.js +31 -0
  89. package/lib/services/output/print.js.map +1 -0
  90. package/lib/services/output/problems.js +84 -0
  91. package/lib/services/output/problems.js.map +1 -0
  92. package/lib/services/output/prompt.js +173 -40
  93. package/lib/services/output/prompt.js.map +1 -1
  94. package/lib/services/output/report.js +63 -19
  95. package/lib/services/output/report.js.map +1 -1
  96. package/lib/services/output/select.js +198 -0
  97. package/lib/services/output/select.js.map +1 -0
  98. package/lib/services/output/spinner.js +141 -0
  99. package/lib/services/output/spinner.js.map +1 -0
  100. package/lib/services/output/sprint.js +38 -15
  101. package/lib/services/output/sprint.js.map +1 -1
  102. package/lib/services/output/symbols.js +23 -0
  103. package/lib/services/output/symbols.js.map +1 -0
  104. package/lib/services/output/table.js +98 -0
  105. package/lib/services/output/table.js.map +1 -0
  106. package/lib/services/output/timestamp.js +12 -0
  107. package/lib/services/output/timestamp.js.map +1 -0
  108. package/lib/services/output/update.js +29 -9
  109. package/lib/services/output/update.js.map +1 -1
  110. package/lib/services/user/session.js +4 -0
  111. package/lib/services/user/session.js.map +1 -1
  112. package/lib/services/user/user.js +15 -10
  113. package/lib/services/user/user.js.map +1 -1
  114. package/lib/services/util/assert.js +11 -0
  115. package/lib/services/util/assert.js.map +1 -0
  116. package/lib/services/util/boolean.js +2 -2
  117. package/lib/services/util/boolean.js.map +1 -1
  118. package/lib/services/util/function.js +45 -7
  119. package/lib/services/util/function.js.map +1 -1
  120. package/lib/services/util/is.js +23 -2
  121. package/lib/services/util/is.js.map +1 -1
  122. package/lib/services/util/json.js +16 -13
  123. package/lib/services/util/json.js.map +1 -1
  124. package/lib/services/util/object.js +2 -2
  125. package/lib/services/util/object.js.map +1 -1
  126. package/lib/services/util/promise.js +5 -2
  127. package/lib/services/util/promise.js.map +1 -1
  128. package/lib/services/util/types.js.map +1 -1
  129. package/npm-shrinkwrap.json +3415 -2973
  130. package/package.json +47 -40
  131. package/bin/dev.cmd +0 -3
  132. package/bin/dev.js +0 -14
  133. package/bin/run.cmd +0 -3
  134. package/bin/run.js +0 -5
  135. package/lib/commands/sync.js +0 -284
  136. package/lib/commands/sync.js.map +0 -1
  137. package/lib/services/app/edit/client.js.map +0 -1
  138. package/lib/services/app/edit/error.js.map +0 -1
  139. package/lib/services/output/log/printer.js +0 -120
  140. package/lib/services/output/log/printer.js.map +0 -1
  141. package/lib/services/output/stream.js +0 -54
  142. package/lib/services/output/stream.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/services/filesync/filesync.ts"],"sourcesContent":["import dayjs from \"dayjs\";\nimport { execa } from \"execa\";\nimport { findUp } from \"find-up\";\nimport fs from \"fs-extra\";\nimport ms from \"ms\";\nimport assert from \"node:assert\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport pMap from \"p-map\";\nimport PQueue from \"p-queue\";\nimport pRetry from \"p-retry\";\nimport type { Promisable } from \"type-fest\";\nimport { z } from \"zod\";\nimport { FileSyncEncoding, type FileSyncChangedEventInput, type FileSyncDeletedEventInput } from \"../../__generated__/graphql.js\";\nimport type { App } from \"../app/app.js\";\nimport { getApps } from \"../app/app.js\";\nimport { AppArg } from \"../app/arg.js\";\nimport { Edit } from \"../app/edit/edit.js\";\nimport { EditError } from \"../app/edit/error.js\";\nimport {\n FILE_SYNC_COMPARISON_HASHES_QUERY,\n FILE_SYNC_FILES_QUERY,\n FILE_SYNC_HASHES_QUERY,\n PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n} from \"../app/edit/operation.js\";\nimport { ArgError, type ArgsDefinition } from \"../command/arg.js\";\nimport type { Context } from \"../command/context.js\";\nimport { config, homePath } from \"../config/config.js\";\nimport { select } from \"../output/prompt.js\";\nimport { sprint } from \"../output/sprint.js\";\nimport { getUserOrLogin } from \"../user/user.js\";\nimport { sortBySimilar } from \"../util/collection.js\";\nimport { noop } from \"../util/function.js\";\nimport { isGraphQLErrors, isGraphQLResult, isObject, isString } from \"../util/is.js\";\nimport { Changes, printChanges } from \"./changes.js\";\nimport { getConflicts, printConflicts, withoutConflictingChanges } from \"./conflicts.js\";\nimport { Directory, supportsPermissions, swallowEnoent, type Hashes } from \"./directory.js\";\nimport { InvalidSyncFileError, TooManySyncAttemptsError } from \"./error.js\";\nimport type { File } from \"./file.js\";\nimport { getChanges, isEqualHashes, type ChangesWithHash } from \"./hashes.js\";\n\nexport type FileSyncHashes = {\n inSync: boolean;\n filesVersionHashes: Hashes;\n localHashes: Hashes;\n gadgetHashes: Hashes;\n gadgetFilesVersion: bigint;\n};\n\nexport class FileSync {\n readonly edit: Edit;\n\n /**\n * A FIFO async callback queue that ensures we process filesync events\n * in the order we receive them.\n */\n private _syncOperations = new PQueue({ concurrency: 1 });\n\n private constructor(\n /**\n * The {@linkcode Context} that was used to initialize this\n * {@linkcode FileSync} instance.\n */\n readonly ctx: Context<FileSyncArgs>,\n\n /**\n * The directory that is being synced to.\n */\n readonly directory: Directory,\n\n /**\n * The Gadget application that is being synced to.\n */\n readonly app: App,\n\n /**\n * The state of the filesystem.\n *\n * This is persisted to `.gadget/sync.json` within the {@linkcode directory}.\n */\n private _syncJson: { app: string; filesVersion: string; mtime: number },\n ) {\n this.ctx = ctx.child({ fields: () => ({ filesync: { directory: this.directory.path, filesVersion: this.filesVersion } }) });\n this.edit = new Edit(this.ctx);\n }\n\n /**\n * The last filesVersion that was written to the filesystem.\n *\n * This determines if the filesystem in Gadget is ahead of the\n * filesystem on the local machine.\n */\n get filesVersion(): bigint {\n return BigInt(this._syncJson.filesVersion);\n }\n\n /**\n * The largest mtime that was seen on the filesystem.\n *\n * This is used to determine if any files have changed since the last\n * sync. This does not include the mtime of files that are ignored.\n */\n get mtime(): number {\n return this._syncJson.mtime;\n }\n\n /**\n * Initializes a {@linkcode FileSync} instance.\n * - Ensures the directory exists.\n * - Ensures the directory is empty or contains a `.gadget/sync.json` file (unless `options.force` is `true`)\n * - Ensures an app is specified (either via `options.app` or by prompting the user)\n * - Ensures the specified app matches the app the directory was previously synced to (unless `options.force` is `true`)\n */\n static async init(ctx: Context<FileSyncArgs>): Promise<FileSync> {\n ctx = ctx.child({ name: \"filesync\" });\n\n const user = await getUserOrLogin(ctx);\n const apps = await getApps(ctx);\n if (apps.length === 0) {\n throw new ArgError(\n sprint`\n You (${user.email}) don't have have any Gadget applications.\n\n Visit https://gadget.new to create one!\n `,\n );\n }\n\n let dir = ctx.args._[0];\n if (!dir) {\n // the user didn't specify a directory\n const filepath = await findUp(\".gadget/sync.json\");\n if (filepath) {\n // we found a .gadget/sync.json file, use its parent directory\n dir = path.join(filepath, \"../..\");\n } else {\n // we didn't find a .gadget/sync.json file, use the current directory\n dir = process.cwd();\n }\n }\n\n if (config.windows && dir.startsWith(\"~/\")) {\n // `~` doesn't expand to the home directory on Windows\n dir = homePath(dir.slice(2));\n }\n\n // ensure the root directory is an absolute path and exists\n const wasEmptyOrNonExistent = await isEmptyOrNonExistentDir(dir);\n await fs.ensureDir((dir = path.resolve(dir)));\n\n // try to load the .gadget/sync.json file\n const state = await fs\n .readJson(path.join(dir, \".gadget/sync.json\"))\n .then((json) =>\n z\n .object({\n app: z.string(),\n filesVersion: z.string(),\n mtime: z.number(),\n })\n .parse(json),\n )\n .catch(noop);\n\n let appSlug = ctx.args[\"--app\"] || state?.app;\n if (!appSlug) {\n // the user didn't specify an app, suggest some apps that they can sync to\n appSlug = await select(ctx, {\n message: \"Select the app to sync to\",\n choices: apps.map((x) => x.slug),\n });\n }\n\n // try to find the appSlug in their list of apps\n const app = apps.find((app) => app.slug === appSlug);\n if (!app) {\n // the specified appSlug doesn't exist in their list of apps,\n // either they misspelled it or they don't have access to it\n // anymore, suggest some apps that are similar to the one they\n // specified\n const similarAppSlugs = sortBySimilar(\n appSlug,\n apps.map((app) => app.slug),\n ).slice(0, 5);\n\n throw new ArgError(\n sprint`\n Unknown application:\n\n ${appSlug}\n\n Did you mean one of these?\n\n\n `.concat(` • ${similarAppSlugs.join(\"\\n • \")}`),\n );\n }\n\n ctx.app = app;\n const directory = await Directory.init(dir);\n\n if (!state) {\n // the .gadget/sync.json file didn't exist or contained invalid json\n if (wasEmptyOrNonExistent || ctx.args[\"--force\"]) {\n // the directory was empty or the user passed --force\n // either way, create a fresh .gadget/sync.json file\n return new FileSync(ctx, directory, app, { app: app.slug, filesVersion: \"0\", mtime: 0 });\n }\n\n // the directory isn't empty and the user didn't pass --force\n throw new InvalidSyncFileError(dir, app.slug);\n }\n\n // the .gadget/sync.json file exists\n if (state.app === app.slug) {\n // the .gadget/sync.json file is for the same app that the user specified\n return new FileSync(ctx, directory, app, state);\n }\n\n // the .gadget/sync.json file is for a different app\n if (ctx.args[\"--force\"]) {\n // the user passed --force, so use the app they specified and overwrite everything\n return new FileSync(ctx, directory, app, { app: app.slug, filesVersion: \"0\", mtime: 0 });\n }\n\n // the user didn't pass --force, so throw an error\n throw new ArgError(sprint`\n You were about to sync the following app to the following directory:\n\n {dim ${app.slug}} → {dim ${dir}}\n\n However, that directory has already been synced with this app:\n\n {dim ${state.app}}\n\n If you're sure that you want to sync:\n\n {dim ${app.slug}} → {dim ${dir}}\n\n Then run {dim ggt sync} again with the {dim --force} flag.\n `);\n }\n\n /**\n * Waits for all pending and ongoing filesync operations to complete.\n */\n async idle(): Promise<void> {\n await this._syncOperations.onIdle();\n }\n\n /**\n * Sends file changes to the Gadget.\n *\n * @param options - The options to use.\n * @param options.changes - The changes to send.\n * @returns A promise that resolves when the changes have been sent.\n */\n async sendChangesToGadget({ changes }: { changes: Changes }): Promise<void> {\n await this._syncOperations.add(async () => {\n try {\n await this._sendChangesToGadget({ changes });\n } catch (error) {\n swallowFilesVersionMismatch(this.ctx, error);\n // we either sent the wrong expectedFilesVersion or we received\n // a filesVersion that is greater than the expectedFilesVersion\n // + 1, so we need to stop what we're doing and get in sync\n await this.sync();\n }\n });\n }\n\n /**\n * Subscribes to file changes on Gadget and executes the provided\n * callbacks before and after the changes occur.\n *\n * @param options - The options to use.\n * @param options.beforeChanges - A callback that is called before the changes occur.\n * @param options.afterChanges - A callback that is called after the changes occur.\n * @param options.onError - A callback that is called if an error occurs.\n * @returns A function that unsubscribes from changes on Gadget.\n */\n subscribeToGadgetChanges({\n beforeChanges = noop,\n afterChanges = noop,\n onError,\n }: {\n beforeChanges?: (data: { changed: string[]; deleted: string[] }) => Promisable<void>;\n afterChanges?: (data: { changes: Changes }) => Promisable<void>;\n onError: (error: unknown) => void;\n }): () => void {\n return this.edit.subscribe({\n subscription: REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n // the reason this is a function rather than a static value is\n // so that it will be re-evaluated if the connection is lost and\n // then re-established. this ensures that we send our current\n // filesVersion rather than the one that was sent when we first\n // subscribed\n variables: () => ({ localFilesVersion: String(this.filesVersion) }),\n onError,\n onData: ({ remoteFileSyncEvents: { changed, deleted, remoteFilesVersion } }) => {\n this._syncOperations\n .add(async () => {\n if (BigInt(remoteFilesVersion) < this.filesVersion) {\n this.ctx.log.warn(\"skipping received changes because files version is outdated\", { filesVersion: remoteFilesVersion });\n return;\n }\n\n this.ctx.log.debug(\"received files\", {\n remoteFilesVersion,\n changed: changed.map((change) => change.path),\n deleted: deleted.map((change) => change.path),\n });\n\n const filterIgnoredFiles = (file: { path: string }): boolean => {\n const ignored = this.directory.ignores(file.path);\n if (ignored) {\n this.ctx.log.warn(\"skipping received change because file is ignored\", { path: file.path });\n }\n return !ignored;\n };\n\n changed = changed.filter(filterIgnoredFiles);\n deleted = deleted.filter(filterIgnoredFiles);\n\n if (changed.length === 0 && deleted.length === 0) {\n await this._save(remoteFilesVersion);\n return;\n }\n\n await beforeChanges({\n changed: changed.map((file) => file.path),\n deleted: deleted.map((file) => file.path),\n });\n\n const changes = await this._writeToLocalFilesystem({\n filesVersion: remoteFilesVersion,\n files: changed,\n delete: deleted.map((file) => file.path),\n });\n\n if (changes.size > 0) {\n printChanges(this.ctx, {\n message: sprint`← Received {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n changes,\n tense: \"past\",\n limit: 10,\n });\n }\n\n await afterChanges({ changes });\n })\n .catch(onError);\n },\n });\n }\n\n /**\n * Ensures the local filesystem is in sync with Gadget's filesystem.\n * - All non-conflicting changes are automatically merged.\n * - Conflicts are resolved by prompting the user to either keep their local changes or keep Gadget's changes.\n * - This function will not return until the filesystem is in sync.\n */\n async sync({ maxAttempts = 10 }: { maxAttempts?: number } = {}): Promise<void> {\n let attempt = 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, no-constant-condition\n while (true) {\n const { inSync, ...hashes } = await this.hashes();\n\n if (inSync) {\n this._syncOperations.clear();\n this.ctx.log.info(\"filesystem is in sync\", { attempt });\n await this._save(hashes.gadgetFilesVersion);\n return;\n }\n\n if (attempt++ >= maxAttempts) {\n throw new TooManySyncAttemptsError(maxAttempts);\n }\n\n try {\n this.ctx.log.info(\"syncing\", { attempt, ...hashes });\n await this._sync(hashes);\n } catch (error) {\n swallowFilesVersionMismatch(this.ctx, error);\n // we either sent the wrong expectedFilesVersion or we received\n // a filesVersion that is greater than the expectedFilesVersion\n // + 1, so try again\n }\n }\n }\n\n async _sync({ filesVersionHashes, localHashes, gadgetHashes, gadgetFilesVersion }: Omit<FileSyncHashes, \"inSync\">): Promise<void> {\n let localChanges = getChanges(this.ctx, { from: filesVersionHashes, to: localHashes, existing: gadgetHashes, ignore: [\".gadget/\"] });\n let gadgetChanges = getChanges(this.ctx, { from: filesVersionHashes, to: gadgetHashes, existing: localHashes });\n\n if (localChanges.size === 0 && gadgetChanges.size === 0) {\n // the local filesystem is missing .gadget/ files\n gadgetChanges = getChanges(this.ctx, { from: localHashes, to: gadgetHashes });\n assertAllGadgetFiles({ gadgetChanges });\n }\n\n assert(localChanges.size > 0 || gadgetChanges.size > 0, \"there must be changes if hashes don't match\");\n\n const conflicts = getConflicts({ localChanges, gadgetChanges });\n if (conflicts.size > 0) {\n this.ctx.log.debug(\"conflicts detected\", { conflicts });\n\n let preference = this.ctx.args[\"--prefer\"];\n if (!preference) {\n printConflicts(this.ctx, {\n message: sprint`{bold You have conflicting changes with Gadget}`,\n conflicts,\n });\n\n preference = await select(this.ctx, {\n message: \"How would you like to resolve these conflicts?\",\n choices: Object.values(ConflictPreference),\n });\n }\n\n switch (preference) {\n case ConflictPreference.CANCEL: {\n process.exit(0);\n break;\n }\n case ConflictPreference.LOCAL: {\n gadgetChanges = withoutConflictingChanges({ conflicts, changes: gadgetChanges });\n break;\n }\n case ConflictPreference.GADGET: {\n localChanges = withoutConflictingChanges({ conflicts, changes: localChanges });\n break;\n }\n }\n }\n\n if (gadgetChanges.size > 0) {\n await this._getChangesFromGadget({ changes: gadgetChanges, filesVersion: gadgetFilesVersion });\n }\n\n if (localChanges.size > 0) {\n await this._sendChangesToGadget({ changes: localChanges, expectedFilesVersion: gadgetFilesVersion });\n }\n }\n\n async hashes(): Promise<FileSyncHashes> {\n const [localHashes, { filesVersionHashes, gadgetHashes, gadgetFilesVersion }] = await Promise.all([\n // get the hashes of our local files\n this.directory.hashes(),\n // get the hashes of our local filesVersion and the latest filesVersion\n (async () => {\n let gadgetFilesVersion: bigint;\n let gadgetHashes: Hashes;\n let filesVersionHashes: Hashes;\n\n if (this.filesVersion === 0n) {\n // this is the first time we're syncing, so just get the\n // hashes of the latest filesVersion\n const { fileSyncHashes } = await this.edit.query({ query: FILE_SYNC_HASHES_QUERY });\n gadgetFilesVersion = BigInt(fileSyncHashes.filesVersion);\n gadgetHashes = fileSyncHashes.hashes;\n filesVersionHashes = {};\n } else {\n // this isn't the first time we're syncing, so get the hashes\n // of the files at our local filesVersion and the latest\n // filesVersion\n const { fileSyncComparisonHashes } = await this.edit.query({\n query: FILE_SYNC_COMPARISON_HASHES_QUERY,\n variables: { filesVersion: String(this.filesVersion) },\n });\n gadgetFilesVersion = BigInt(fileSyncComparisonHashes.latestFilesVersionHashes.filesVersion);\n gadgetHashes = fileSyncComparisonHashes.latestFilesVersionHashes.hashes;\n filesVersionHashes = fileSyncComparisonHashes.filesVersionHashes.hashes;\n }\n\n return { filesVersionHashes, gadgetHashes, gadgetFilesVersion };\n })(),\n ]);\n\n return {\n filesVersionHashes,\n localHashes,\n gadgetHashes,\n gadgetFilesVersion,\n inSync: isEqualHashes(this.ctx, localHashes, gadgetHashes),\n };\n }\n\n private async _getChangesFromGadget({\n filesVersion,\n changes,\n }: {\n filesVersion: bigint;\n changes: Changes | ChangesWithHash;\n }): Promise<void> {\n this.ctx.log.debug(\"getting changes from gadget\", { filesVersion, changes });\n const created = changes.created();\n const updated = changes.updated();\n\n let files: File[] = [];\n if (created.length > 0 || updated.length > 0) {\n const { fileSyncFiles } = await this.edit.query({\n query: FILE_SYNC_FILES_QUERY,\n variables: {\n paths: [...created, ...updated],\n filesVersion: String(filesVersion),\n encoding: FileSyncEncoding.Base64,\n },\n });\n\n files = fileSyncFiles.files;\n }\n\n await this._writeToLocalFilesystem({\n filesVersion,\n files,\n delete: changes.deleted(),\n });\n\n printChanges(this.ctx, {\n changes,\n tense: \"past\",\n message: sprint`← Received {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n });\n }\n\n private async _sendChangesToGadget({\n expectedFilesVersion = this.filesVersion,\n changes,\n printLimit,\n }: {\n expectedFilesVersion?: bigint;\n changes: Changes;\n printLimit?: number;\n }): Promise<void> {\n this.ctx.log.debug(\"sending changes to gadget\", { expectedFilesVersion, changes });\n const changed: FileSyncChangedEventInput[] = [];\n const deleted: FileSyncDeletedEventInput[] = [];\n\n await pMap(changes, async ([normalizedPath, change]) => {\n if (change.type === \"delete\") {\n deleted.push({ path: normalizedPath });\n return;\n }\n\n const absolutePath = this.directory.absolute(normalizedPath);\n\n let stats;\n try {\n stats = await fs.stat(absolutePath);\n } catch (error) {\n swallowEnoent(error);\n this.ctx.log.debug(\"skipping change because file doesn't exist\", { path: normalizedPath });\n return;\n }\n\n let content = \"\";\n if (stats.isFile()) {\n content = await fs.readFile(absolutePath, FileSyncEncoding.Base64);\n }\n\n let oldPath;\n if (change.type === \"create\" && change.oldPath) {\n oldPath = change.oldPath;\n }\n\n changed.push({\n content,\n oldPath,\n path: normalizedPath,\n mode: stats.mode,\n encoding: FileSyncEncoding.Base64,\n });\n });\n\n if (changed.length === 0 && deleted.length === 0) {\n this.ctx.log.debug(\"skipping send because there are no changes\");\n return;\n }\n\n const {\n publishFileSyncEvents: { remoteFilesVersion, problems },\n } = await this.edit.mutate({\n mutation: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: {\n input: {\n expectedRemoteFilesVersion: String(expectedFilesVersion),\n changed,\n deleted,\n },\n },\n http: {\n retry: {\n // we can retry this request because\n // expectedRemoteFilesVersion makes it idempotent\n methods: [\"POST\"],\n calculateDelay: ({ error, computedValue }) => {\n if (isFilesVersionMismatchError(error.response?.body)) {\n // don't retry if we get a files version mismatch error\n return 0;\n }\n return computedValue;\n },\n },\n },\n });\n\n printChanges(this.ctx, {\n changes,\n tense: \"past\",\n message: sprint`→ Sent {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n limit: printLimit,\n });\n\n if (BigInt(remoteFilesVersion) > expectedFilesVersion + 1n) {\n // we can't save the remoteFilesVersion because we haven't\n // received the intermediate filesVersions yet\n throw new Error(\"Files version mismatch\");\n }\n\n if (problems.length > 0) {\n const problemGroup: Record<string, string[]> = {};\n problems.forEach((problem) => {\n if (!(problem.path in problemGroup)) {\n problemGroup[problem.path] = [];\n }\n problemGroup[problem.path]?.push(problem.message);\n });\n\n this.ctx.log.println2`{red Gadget has detected the following fatal errors with your files:}`;\n Object.entries(problemGroup).forEach(([path, messages]) => {\n this.ctx.log.println`{red [${path}]}`;\n messages.forEach((message) => {\n this.ctx.log.println`{red - ${message}}`;\n });\n });\n this.ctx.log.println(\"\");\n this.ctx.log.println2`{red Your app will not be operational until all fatal errors are fixed.}`;\n }\n\n await this._save(remoteFilesVersion);\n }\n\n private async _writeToLocalFilesystem(options: { filesVersion: bigint | string; files: File[]; delete: string[] }): Promise<Changes> {\n const filesVersion = BigInt(options.filesVersion);\n assert(filesVersion >= this.filesVersion, \"filesVersion must be greater than or equal to current filesVersion\");\n\n this.ctx.log.debug(\"writing to local filesystem\", {\n filesVersion,\n files: options.files.map((file) => file.path),\n delete: options.delete,\n });\n\n const created: string[] = [];\n const updated: string[] = [];\n\n await pMap(options.delete, async (filepath) => {\n const currentPath = this.directory.absolute(filepath);\n const backupPath = this.directory.absolute(\".gadget/backup\", this.directory.relative(filepath));\n\n // rather than `rm -rf`ing files, we move them to\n // `.gadget/backup/` so that users can recover them if something\n // goes wrong. We've seen a lot of EBUSY/EINVAL errors when moving\n // files so we retry a few times.\n await pRetry(\n async () => {\n try {\n // remove the current backup file in case it exists and is a\n // different type (file vs directory)\n await fs.remove(backupPath);\n await fs.move(currentPath, backupPath);\n } catch (error) {\n // replicate the behavior of `rm -rf` and ignore ENOENT\n swallowEnoent(error);\n }\n },\n {\n // windows tends to run into these issues way more often than\n // mac/linux, so we retry more times\n retries: config.windows ? 4 : 2,\n minTimeout: ms(\"100ms\"),\n onFailedAttempt: (error) => {\n this.ctx.log.warn(\"failed to move file to backup\", { error, currentPath, backupPath });\n },\n },\n );\n });\n\n await pMap(options.files, async (file) => {\n const absolutePath = this.directory.absolute(file.path);\n if (await fs.pathExists(absolutePath)) {\n updated.push(file.path);\n } else {\n created.push(file.path);\n }\n\n if (file.path.endsWith(\"/\")) {\n await fs.ensureDir(absolutePath);\n } else {\n await fs.outputFile(absolutePath, Buffer.from(file.content, file.encoding));\n }\n\n if (supportsPermissions) {\n // the os's default umask makes setting the mode during creation\n // not work, so an additional fs.chmod call is necessary to\n // ensure the file has the correct mode\n await fs.chmod(absolutePath, file.mode & 0o777);\n }\n\n if (absolutePath === this.directory.absolute(\".ignore\")) {\n await this.directory.loadIgnoreFile();\n }\n });\n\n await this._save(String(filesVersion));\n\n const changes = new Changes([\n ...created.map((path) => [path, { type: \"create\" }] as const),\n ...updated.map((path) => [path, { type: \"update\" }] as const),\n ...options.delete.map((path) => [path, { type: \"delete\" }] as const),\n ]);\n\n if (changes.has(\"yarn.lock\")) {\n this.ctx.log.info(\"running yarn install --check-files\");\n await execa(\"yarn\", [\"install\", \"--check-files\"], { cwd: this.directory.path })\n .then(() => this.ctx.log.info(\"yarn install complete\"))\n .catch((error: unknown) => this.ctx.log.error(\"yarn install failed\", { error }));\n }\n\n return changes;\n }\n\n /**\n * Updates {@linkcode _syncJson} and saves it to `.gadget/sync.json`.\n */\n private async _save(filesVersion: string | bigint): Promise<void> {\n this._syncJson = { ...this._syncJson, mtime: Date.now() + 1, filesVersion: String(filesVersion) };\n this.ctx.log.debug(\"saving .gadget/sync.json\");\n await fs.outputJSON(this.directory.absolute(\".gadget/sync.json\"), this._syncJson, { spaces: 2 });\n }\n}\n\n/**\n * Checks if a directory is empty or non-existent.\n *\n * @param dir - The directory path to check.\n * @returns A Promise that resolves to a boolean indicating whether the directory is empty or non-existent.\n */\nexport const isEmptyOrNonExistentDir = async (dir: string): Promise<boolean> => {\n try {\n for await (const _ of await fs.opendir(dir, { bufferSize: 1 })) {\n return false;\n }\n return true;\n } catch (error) {\n swallowEnoent(error);\n return true;\n }\n};\n\nexport const assertAllGadgetFiles = ({ gadgetChanges }: { gadgetChanges: Changes }): void => {\n assert(\n gadgetChanges.created().length > 0 || gadgetChanges.deleted().length > 0 || gadgetChanges.updated().length > 0,\n \"expected gadgetChanges to have changes\",\n );\n\n const allGadgetFiles = Array.from(gadgetChanges.keys()).every((path) => path.startsWith(\".gadget/\"));\n assert(allGadgetFiles, \"expected all gadgetChanges to be .gadget/ files\");\n};\n\nexport const ConflictPreference = Object.freeze({\n CANCEL: \"Cancel (Ctrl+C)\",\n LOCAL: \"Keep my conflicting changes\",\n GADGET: \"Keep Gadget's conflicting changes\",\n});\n\nexport type ConflictPreference = (typeof ConflictPreference)[keyof typeof ConflictPreference];\n\nexport const ConflictPreferenceArg = (value: string, name: string): ConflictPreference => {\n if ([\"local\", \"gadget\"].includes(value)) {\n return ConflictPreference[value.toUpperCase() as keyof typeof ConflictPreference];\n }\n\n throw new ArgError(sprint`\n ${name} must be {bold local} or {bold gadget}\n\n {bold EXAMPLES:}\n ${name} local\n ${name} gadget\n `);\n};\n\nexport const FileSyncArgs = {\n \"--app\": { type: AppArg, alias: \"-a\" },\n \"--prefer\": ConflictPreferenceArg,\n \"--force\": Boolean,\n} satisfies ArgsDefinition;\n\nexport type FileSyncArgs = typeof FileSyncArgs;\n\nexport const isFilesVersionMismatchError = (error: unknown): boolean => {\n if (error instanceof EditError) {\n error = error.cause;\n }\n if (isGraphQLResult(error)) {\n error = error.errors;\n }\n if (isGraphQLErrors(error)) {\n error = error[0];\n }\n return isObject(error) && \"message\" in error && isString(error.message) && error.message.includes(\"Files version mismatch\");\n};\n\nconst swallowFilesVersionMismatch = (ctx: Context, error: unknown): void => {\n if (isFilesVersionMismatchError(error)) {\n ctx.log.debug(\"swallowing files version mismatch\", { error });\n return;\n }\n throw error;\n};\n"],"names":["dayjs","execa","findUp","fs","ms","assert","path","process","pMap","PQueue","pRetry","z","FileSyncEncoding","getApps","AppArg","Edit","EditError","FILE_SYNC_COMPARISON_HASHES_QUERY","FILE_SYNC_FILES_QUERY","FILE_SYNC_HASHES_QUERY","PUBLISH_FILE_SYNC_EVENTS_MUTATION","REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION","ArgError","config","homePath","select","sprint","getUserOrLogin","sortBySimilar","noop","isGraphQLErrors","isGraphQLResult","isObject","isString","Changes","printChanges","getConflicts","printConflicts","withoutConflictingChanges","Directory","supportsPermissions","swallowEnoent","InvalidSyncFileError","TooManySyncAttemptsError","getChanges","isEqualHashes","FileSync","filesVersion","BigInt","_syncJson","mtime","init","ctx","child","name","user","apps","length","email","dir","args","_","filepath","join","cwd","windows","startsWith","slice","wasEmptyOrNonExistent","isEmptyOrNonExistentDir","ensureDir","resolve","state","readJson","then","json","object","app","string","number","parse","catch","appSlug","message","choices","map","x","slug","find","similarAppSlugs","concat","directory","idle","_syncOperations","onIdle","sendChangesToGadget","changes","add","_sendChangesToGadget","error","swallowFilesVersionMismatch","sync","subscribeToGadgetChanges","beforeChanges","afterChanges","onError","edit","subscribe","subscription","variables","localFilesVersion","String","onData","remoteFileSyncEvents","changed","deleted","remoteFilesVersion","log","warn","debug","change","filterIgnoredFiles","file","ignored","ignores","filter","_save","_writeToLocalFilesystem","files","delete","size","format","tense","limit","maxAttempts","attempt","inSync","hashes","clear","info","gadgetFilesVersion","_sync","filesVersionHashes","localHashes","gadgetHashes","localChanges","from","to","existing","ignore","gadgetChanges","assertAllGadgetFiles","conflicts","preference","Object","values","ConflictPreference","CANCEL","exit","LOCAL","GADGET","_getChangesFromGadget","expectedFilesVersion","Promise","all","fileSyncHashes","query","fileSyncComparisonHashes","latestFilesVersionHashes","created","updated","fileSyncFiles","paths","encoding","Base64","printLimit","normalizedPath","type","push","absolutePath","absolute","stats","stat","content","isFile","readFile","oldPath","mode","publishFileSyncEvents","problems","mutate","mutation","input","expectedRemoteFilesVersion","http","retry","methods","calculateDelay","computedValue","isFilesVersionMismatchError","response","body","Error","problemGroup","forEach","problem","println2","entries","messages","println","options","currentPath","backupPath","relative","remove","move","retries","minTimeout","onFailedAttempt","pathExists","endsWith","outputFile","Buffer","chmod","loadIgnoreFile","has","Date","now","outputJSON","spaces","concurrency","fields","filesync","opendir","bufferSize","allGadgetFiles","Array","keys","every","freeze","ConflictPreferenceArg","value","includes","toUpperCase","FileSyncArgs","alias","Boolean","cause","errors"],"mappings":";AAAA,OAAOA,WAAW,QAAQ;AAC1B,SAASC,KAAK,QAAQ,QAAQ;AAC9B,SAASC,MAAM,QAAQ,UAAU;AACjC,OAAOC,QAAQ,WAAW;AAC1B,OAAOC,QAAQ,KAAK;AACpB,OAAOC,YAAY,cAAc;AACjC,OAAOC,UAAU,YAAY;AAC7B,OAAOC,aAAa,eAAe;AACnC,OAAOC,UAAU,QAAQ;AACzB,OAAOC,YAAY,UA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tB;IACA,IAAI1N,gBAAgBqE,QAAQ;QAC1BA,QAAQA,KAAK,CAAC,EAAE;IAClB;IACA,OAAOnE,SAASmE,UAAU,aAAaA,SAASlE,SAASkE,MAAMhB,OAAO,KAAKgB,MAAMhB,OAAO,CAAC+J,QAAQ,CAAC;AACpG,EAAE;AAEF,MAAM9I,8BAA8B,CAAChD,KAAc+C;IACjD,IAAIoG,4BAA4BpG,QAAQ;QACtC/C,IAAIiE,GAAG,CAACE,KAAK,CAAC,qCAAqC;YAAEpB;QAAM;QAC3D;IACF;IACA,MAAMA;AACR"}
1
+ {"version":3,"sources":["../../../src/services/filesync/filesync.ts"],"sourcesContent":["import { execa } from \"execa\";\nimport fs from \"fs-extra\";\nimport ms from \"ms\";\nimport assert from \"node:assert\";\nimport process from \"node:process\";\nimport pMap from \"p-map\";\nimport PQueue from \"p-queue\";\nimport pRetry from \"p-retry\";\nimport pluralize from \"pluralize\";\nimport type { Promisable } from \"type-fest\";\nimport { FileSyncEncoding, type FileSyncChangedEventInput, type FileSyncDeletedEventInput } from \"../../__generated__/graphql.js\";\nimport type { DevArgs } from \"../../commands/dev.js\";\nimport type { PullArgs } from \"../../commands/pull.js\";\nimport { type EditSubscription } from \"../app/edit/edit.js\";\nimport {\n FILE_SYNC_COMPARISON_HASHES_QUERY,\n FILE_SYNC_FILES_QUERY,\n FILE_SYNC_HASHES_QUERY,\n PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n} from \"../app/edit/operation.js\";\nimport type { Context } from \"../command/context.js\";\nimport { config } from \"../config/config.js\";\nimport { confirm } from \"../output/confirm.js\";\nimport { println } from \"../output/print.js\";\nimport { filesyncProblemsToProblems, sprintProblems } from \"../output/problems.js\";\nimport { EdgeCaseError } from \"../output/report.js\";\nimport { select } from \"../output/select.js\";\nimport { spin, type spinner } from \"../output/spinner.js\";\nimport { sprint, sprintln } from \"../output/sprint.js\";\nimport { symbol } from \"../output/symbols.js\";\nimport { ts } from \"../output/timestamp.js\";\nimport { noop } from \"../util/function.js\";\nimport { serializeError } from \"../util/object.js\";\nimport { Changes, printChanges, sprintChanges, type PrintChangesOptions } from \"./changes.js\";\nimport { getConflicts, printConflicts, withoutConflictingChanges } from \"./conflicts.js\";\nimport { supportsPermissions, swallowEnoent, type Hashes } from \"./directory.js\";\nimport { TooManyMergeAttemptsError, isFilesVersionMismatchError, swallowFilesVersionMismatch } from \"./error.js\";\nimport type { File } from \"./file.js\";\nimport { getNecessaryChanges, isEqualHashes, type ChangesWithHash } from \"./hashes.js\";\nimport { MergeConflictPreference } from \"./strategy.js\";\nimport { type SyncJson, type SyncJsonArgs } from \"./sync-json.js\";\n\n/**\n * The maximum attempts to automatically merge local and environment\n * file changes when a FilesVersionMismatchError is encountered before\n * throwing a {@linkcode TooManyMergeAttemptsError}.\n */\nexport const MAX_MERGE_ATTEMPTS = 10;\n\n/**\n * The maximum length of file content that can be pushed to Gadget in a\n * single request.\n */\nexport const MAX_PUSH_CONTENT_LENGTH = 50 * 1024 * 1024; // 50mb\n\nexport type FileSyncHashes = {\n /**\n * Whether the local filesystem is in sync with the environment's\n * filesystem.\n */\n inSync: boolean;\n\n /**\n * Whether the local filesystem and the environment's filesystem have\n * both changed since the last sync.\n */\n bothChanged: boolean;\n\n /**\n * Whether only .gadget/ files have changed on the environment's\n * filesystem.\n */\n onlyDotGadgetFilesChanged: boolean;\n\n /**\n * The hashes of the files at the local filesVersion.\n */\n localFilesVersionHashes: Hashes;\n\n /**\n * The hashes of the files on the local filesystem.\n */\n localHashes: Hashes;\n\n /**\n * The changes the local filesystem has made since the last sync.\n */\n localChanges: ChangesWithHash;\n\n /**\n * The changes the local filesystem needs to push to make the\n * environment's filesystem in sync with the local filesystem.\n *\n * NOTE: If the environment's filesystem has changed since the last\n * sync, these changes will undo those changes.\n */\n localChangesToPush: Changes | ChangesWithHash;\n\n /**\n * The filesVersion of the environment's filesystem.\n */\n environmentFilesVersion: bigint;\n\n /**\n * The hashes of the files on the environment's filesystem.\n */\n environmentHashes: Hashes;\n\n /**\n * The changes the environment's filesystem has made since the last\n * sync.\n */\n environmentChanges: ChangesWithHash;\n\n /**\n * The changes the local filesystem needs to pull from the\n * environment's filesystem to be in sync with the environment's\n * filesystem.\n *\n * NOTE: If the local filesystem has changed since the last sync,\n * these changes will undo those changes.\n */\n environmentChangesToPull: Changes | ChangesWithHash;\n};\n\nexport class FileSync {\n /**\n * A FIFO async callback queue that ensures we process filesync events\n * in the order we receive them.\n */\n private _syncOperations = new PQueue({ concurrency: 1 });\n\n constructor(readonly syncJson: SyncJson) {}\n\n async hashes(ctx: Context<SyncJsonArgs>): Promise<FileSyncHashes> {\n const spinner = spin({ ensureEmptyLineAbove: true })`\n Calculating file changes.\n `;\n\n try {\n const [localHashes, { localFilesVersionHashes, environmentHashes, environmentFilesVersion }] = await Promise.all([\n // get the hashes of our local files\n this.syncJson.directory.hashes(),\n // get the hashes of our local filesVersion and the latest filesVersion\n (async () => {\n let localFilesVersionHashes: Hashes;\n let environmentHashes: Hashes;\n let environmentFilesVersion: bigint;\n\n if (this.syncJson.filesVersion === 0n) {\n // we're either syncing for the first time or we're syncing a\n // non-empty directory without a `.gadget/sync.json` file,\n // regardless get the hashes of the latest filesVersion\n const { fileSyncHashes } = await this.syncJson.edit.query({ query: FILE_SYNC_HASHES_QUERY });\n environmentFilesVersion = BigInt(fileSyncHashes.filesVersion);\n environmentHashes = fileSyncHashes.hashes;\n localFilesVersionHashes = {}; // represents an empty directory\n } else {\n // this isn't the first time we're syncing, so get the\n // hashes of the files at our local filesVersion and the\n // latest filesVersion\n const { fileSyncComparisonHashes } = await this.syncJson.edit.query({\n query: FILE_SYNC_COMPARISON_HASHES_QUERY,\n variables: { filesVersion: String(this.syncJson.filesVersion) },\n });\n\n localFilesVersionHashes = fileSyncComparisonHashes.filesVersionHashes.hashes;\n environmentHashes = fileSyncComparisonHashes.latestFilesVersionHashes.hashes;\n environmentFilesVersion = BigInt(fileSyncComparisonHashes.latestFilesVersionHashes.filesVersion);\n }\n\n return { localFilesVersionHashes, environmentHashes, environmentFilesVersion };\n })(),\n ]);\n\n const inSync = isEqualHashes(ctx, localHashes, environmentHashes);\n\n const localChanges = getNecessaryChanges(ctx, {\n from: localFilesVersionHashes,\n to: localHashes,\n existing: environmentHashes,\n ignore: [\".gadget/\"], // gadget manages these files\n });\n\n let environmentChanges = getNecessaryChanges(ctx, {\n from: localFilesVersionHashes,\n to: environmentHashes,\n existing: localHashes,\n });\n\n if (!inSync && localChanges.size === 0 && environmentChanges.size === 0) {\n // we're not in sync, but neither the local filesystem nor the\n // environment's filesystem have any changes; this is only\n // possible if the local filesystem has modified .gadget/ files\n environmentChanges = getNecessaryChanges(ctx, { from: localHashes, to: environmentHashes });\n assert(environmentChanges.size > 0, \"expected environmentChanges to have changes\");\n assert(\n Array.from(environmentChanges.keys()).every((path) => path.startsWith(\".gadget/\")),\n \"expected all environmentChanges to be .gadget/ files\",\n );\n }\n\n assert(inSync || localChanges.size > 0 || environmentChanges.size > 0, \"there must be changes if hashes don't match\");\n\n const localChangesToPush = getNecessaryChanges(ctx, { from: environmentHashes, to: localHashes, ignore: [\".gadget/\"] });\n const environmentChangesToPull = getNecessaryChanges(ctx, { from: localHashes, to: environmentHashes });\n\n const onlyDotGadgetFilesChanged = Array.from(environmentChangesToPull.keys()).every((filepath) => filepath.startsWith(\".gadget/\"));\n const bothChanged = localChanges.size > 0 && environmentChanges.size > 0 && !onlyDotGadgetFilesChanged;\n\n if (inSync) {\n spinner.succeed`Your files are up to date. ${ts()}`;\n } else {\n spinner.succeed`Calculated file changes. ${ts()}`;\n }\n\n return {\n inSync,\n localFilesVersionHashes,\n localHashes,\n localChanges,\n localChangesToPush,\n environmentHashes,\n environmentChanges,\n environmentChangesToPull,\n environmentFilesVersion,\n onlyDotGadgetFilesChanged,\n bothChanged,\n };\n } catch (error) {\n spinner.fail();\n throw error;\n }\n }\n\n async print(ctx: Context<SyncJsonArgs>, { hashes }: { hashes?: FileSyncHashes } = {}): Promise<void> {\n const { inSync, localChanges, environmentChanges, onlyDotGadgetFilesChanged, bothChanged } = hashes ?? (await this.hashes(ctx));\n if (inSync) {\n // the spinner in hashes will have already printed that we're in sync\n return;\n }\n\n if (localChanges.size > 0) {\n printChanges(ctx, {\n changes: localChanges,\n tense: \"past\",\n title: sprint`Your local files {underline have} changed.`,\n });\n } else {\n println({ ensureEmptyLineAbove: true })`\n Your local files {underline have not} changed.\n `;\n }\n\n if (environmentChanges.size > 0 && !onlyDotGadgetFilesChanged) {\n printChanges(ctx, {\n changes: environmentChanges,\n tense: \"past\",\n title: sprint`Your environment's files {underline have}${bothChanged ? \" also\" : \"\"} changed.`,\n });\n } else {\n println({ ensureEmptyLineAbove: true })`\n Your environment's files {underline have not} changed.\n `;\n }\n }\n\n /**\n * Waits for all pending and ongoing filesync operations to complete.\n */\n async idle(): Promise<void> {\n await this._syncOperations.onIdle();\n }\n\n /**\n * Attempts to send file changes to the Gadget. If a files version\n * mismatch error occurs, this function will merge the changes with\n * Gadget instead.\n *\n * @param ctx - The context to use.\n * @param options - The options to use.\n * @param options.changes - The changes to send.\n * @param options.printLocalChangesOptions - The options to use when printing the local changes.\n * @param options.printEnvironmentChangesOptions - The options to use when printing the changes from Gadget.\n * @returns A promise that resolves when the changes have been sent.\n */\n async mergeChangesWithEnvironment(\n ctx: Context<DevArgs>,\n {\n changes,\n printLocalChangesOptions,\n printEnvironmentChangesOptions,\n }: {\n changes: Changes;\n printLocalChangesOptions?: Partial<PrintChangesOptions>;\n printEnvironmentChangesOptions?: Partial<PrintChangesOptions>;\n },\n ): Promise<void> {\n await this._syncOperations.add(async () => {\n try {\n await this._sendChangesToEnvironment(ctx, { changes, printLocalChangesOptions });\n } catch (error) {\n swallowFilesVersionMismatch(ctx, error);\n // we either sent the wrong expectedFilesVersion or we received\n // a filesVersion that is greater than the expectedFilesVersion\n // + 1, so we need to stop what we're doing and get in sync\n await this.merge(ctx, { printEnvironmentChangesOptions });\n }\n });\n }\n\n /**\n * Subscribes to file changes on Gadget and executes the provided\n * callbacks before and after the changes occur.\n *\n * @param ctx - The context to use.\n * @param options - The options to use.\n * @param options.beforeChanges - A callback that is called before the changes occur.\n * @param options.afterChanges - A callback that is called after the changes occur.\n * @param options.onError - A callback that is called if an error occurs.\n * @param options.printEnvironmentChangesOptions - The options to use when printing the changes from Gadget.\n * @returns A function that unsubscribes from changes on Gadget.\n */\n subscribeToEnvironmentChanges(\n ctx: Context<DevArgs>,\n {\n beforeChanges = noop,\n printEnvironmentChangesOptions,\n afterChanges = noop,\n onError,\n }: {\n beforeChanges?: (data: { changed: string[]; deleted: string[] }) => Promisable<void>;\n printEnvironmentChangesOptions?: Partial<PrintChangesOptions>;\n afterChanges?: (data: { changes: Changes }) => Promisable<void>;\n onError: (error: unknown) => void;\n },\n ): EditSubscription<REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION> {\n return this.syncJson.edit.subscribe({\n subscription: REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n // the reason this is a function rather than a static value is\n // so that it will be re-evaluated if the connection is lost and\n // then re-established. this ensures that we send our current\n // filesVersion rather than the one that was sent when we first\n // subscribed\n variables: () => ({ localFilesVersion: String(this.syncJson.filesVersion) }),\n onError,\n onData: ({ remoteFileSyncEvents: { changed, deleted, remoteFilesVersion } }) => {\n this._syncOperations\n .add(async () => {\n if (BigInt(remoteFilesVersion) < this.syncJson.filesVersion) {\n ctx.log.warn(\"skipping received changes because files version is outdated\", { filesVersion: remoteFilesVersion });\n return;\n }\n\n ctx.log.debug(\"received files\", {\n remoteFilesVersion,\n changed: changed.map((change) => change.path),\n deleted: deleted.map((change) => change.path),\n });\n\n const filterIgnoredFiles = (file: { path: string }): boolean => {\n const ignored = this.syncJson.directory.ignores(file.path);\n if (ignored) {\n ctx.log.warn(\"skipping received change because file is ignored\", { path: file.path });\n }\n return !ignored;\n };\n\n changed = changed.filter(filterIgnoredFiles);\n deleted = deleted.filter(filterIgnoredFiles);\n\n if (changed.length === 0 && deleted.length === 0) {\n await this.syncJson.save(remoteFilesVersion);\n return;\n }\n\n await beforeChanges({\n changed: changed.map((file) => file.path),\n deleted: deleted.map((file) => file.path),\n });\n\n const changes = await this._writeToLocalFilesystem(ctx, {\n filesVersion: remoteFilesVersion,\n files: changed,\n delete: deleted.map((file) => file.path),\n printEnvironmentChangesOptions: {\n tense: \"past\",\n ensureEmptyLineAbove: true,\n title: sprintln`{green ${symbol.tick}} Pulled ${pluralize(\"file\", changed.length + deleted.length)}. ${symbol.arrowLeft} ${ts()}`,\n limit: 5,\n ...printEnvironmentChangesOptions,\n },\n });\n\n await afterChanges({ changes });\n })\n .catch(onError);\n },\n });\n }\n\n /**\n * Ensures the local filesystem is in sync with Gadget's filesystem.\n * - All non-conflicting changes are automatically merged.\n * - Conflicts are resolved by prompting the user to either keep their local changes or keep Gadget's changes.\n * - This function will not return until the filesystem is in sync.\n */\n async merge(\n ctx: Context<DevArgs>,\n {\n hashes,\n maxAttempts = 10,\n printLocalChangesOptions,\n printEnvironmentChangesOptions,\n }: {\n hashes?: FileSyncHashes;\n maxAttempts?: number;\n printLocalChangesOptions?: Partial<PrintChangesOptions>;\n printEnvironmentChangesOptions?: Partial<PrintChangesOptions>;\n } = {},\n ): Promise<void> {\n let attempt = 0;\n\n do {\n if (attempt === 0) {\n hashes ??= await this.hashes(ctx);\n } else {\n hashes = await this.hashes(ctx);\n }\n\n if (hashes.inSync) {\n this._syncOperations.clear();\n ctx.log.info(\"filesystem in sync\");\n await this.syncJson.save(hashes.environmentFilesVersion);\n return;\n }\n\n attempt += 1;\n ctx.log.info(\"merging\", { attempt, ...hashes });\n\n try {\n await this._merge(ctx, { hashes, printLocalChangesOptions, printEnvironmentChangesOptions });\n } catch (error) {\n swallowFilesVersionMismatch(ctx, error);\n // we either sent the wrong expectedFilesVersion or we received\n // a filesVersion that is greater than the expectedFilesVersion\n // + 1, so try again\n }\n } while (attempt < maxAttempts);\n\n throw new TooManyMergeAttemptsError(maxAttempts);\n }\n\n /**\n * Pushes any changes made to the local filesystem since the last sync\n * to Gadget.\n *\n * If Gadget has also made changes since the last sync, and --force\n * was not passed, the user will be prompted to discard them.\n */\n async push(\n ctx: Context<PullArgs>,\n {\n hashes,\n force,\n printLocalChangesOptions,\n }: {\n hashes?: FileSyncHashes;\n force?: boolean;\n printLocalChangesOptions?: PrintChangesOptions;\n } = {},\n ): Promise<void> {\n const { localChangesToPush, environmentChanges, environmentFilesVersion, onlyDotGadgetFilesChanged } =\n hashes ?? (await this.hashes(ctx));\n assert(localChangesToPush.size > 0, \"cannot push if there are no changes\");\n\n // TODO: lift this check up to the push command\n if (\n // they didn't pass --force\n !(force ?? ctx.args[\"--force\"]) &&\n // their environment's files have changed\n environmentChanges.size > 0 &&\n // some of the changes aren't .gadget/ files\n !onlyDotGadgetFilesChanged\n ) {\n await confirm({ ensureEmptyLineAbove: true })`\n Are you sure you want to {underline discard} your environment's changes?\n `;\n }\n\n try {\n await this._sendChangesToEnvironment(ctx, {\n // what changes need to be made to your local files to make\n // them match the environment's files\n changes: localChangesToPush,\n expectedFilesVersion: environmentFilesVersion,\n printLocalChangesOptions,\n });\n } catch (error) {\n swallowFilesVersionMismatch(ctx, error);\n // we were told to push their local changes, but their\n // environment's files have changed since we last checked, so\n // throw a nicer error message\n // TODO: we don't have to do this if only .gadget/ files changed\n throw new EdgeCaseError(sprint`\n Your environment's files have changed since we last checked.\n\n Please re-run \"ggt ${ctx.command}\" to see the changes and try again.\n `);\n }\n }\n\n async pull(\n ctx: Context<PullArgs>,\n {\n hashes,\n force,\n printEnvironmentChangesOptions,\n }: {\n hashes?: FileSyncHashes;\n force?: boolean;\n printEnvironmentChangesOptions?: Partial<PrintChangesOptions>;\n } = {},\n ): Promise<void> {\n const { localChanges, environmentChangesToPull, environmentFilesVersion } = hashes ?? (await this.hashes(ctx));\n assert(environmentChangesToPull.size > 0, \"cannot push if there are no changes\");\n\n // TODO: lift this check up to the pull command\n if (localChanges.size > 0 && !(force ?? ctx.args[\"--force\"])) {\n await confirm`\n Are you sure you want to {underline discard} your local changes?\n `;\n }\n\n await this._getChangesFromEnvironment(ctx, {\n changes: environmentChangesToPull,\n filesVersion: environmentFilesVersion,\n printEnvironmentChangesOptions,\n });\n }\n\n private async _merge(\n ctx: Context<DevArgs>,\n {\n hashes: { localChanges, environmentChanges, environmentFilesVersion },\n printLocalChangesOptions,\n printEnvironmentChangesOptions,\n }: {\n hashes: FileSyncHashes;\n printLocalChangesOptions?: Partial<PrintChangesOptions>;\n printEnvironmentChangesOptions?: Partial<PrintChangesOptions>;\n },\n ): Promise<void> {\n const conflicts = getConflicts({ localChanges, environmentChanges });\n if (conflicts.size > 0) {\n ctx.log.debug(\"conflicts detected\", { conflicts });\n\n let preference = ctx.args[\"--prefer\"];\n if (!preference) {\n printConflicts({ conflicts });\n preference = await select({ choices: Object.values(MergeConflictPreference) })`\n {bold How should we resolve these conflicts?}\n `;\n }\n\n switch (preference) {\n case MergeConflictPreference.CANCEL: {\n process.exit(0);\n break;\n }\n case MergeConflictPreference.LOCAL: {\n environmentChanges = withoutConflictingChanges({ conflicts, changes: environmentChanges });\n break;\n }\n case MergeConflictPreference.ENVIRONMENT: {\n localChanges = withoutConflictingChanges({ conflicts, changes: localChanges });\n break;\n }\n }\n }\n\n if (environmentChanges.size > 0) {\n await this._getChangesFromEnvironment(ctx, {\n changes: environmentChanges,\n filesVersion: environmentFilesVersion,\n printEnvironmentChangesOptions,\n });\n }\n\n if (localChanges.size > 0) {\n await this._sendChangesToEnvironment(ctx, {\n changes: localChanges,\n expectedFilesVersion: environmentFilesVersion,\n printLocalChangesOptions,\n });\n }\n }\n\n private async _getChangesFromEnvironment(\n ctx: Context<SyncJsonArgs>,\n {\n filesVersion,\n changes,\n printEnvironmentChangesOptions,\n }: {\n filesVersion: bigint;\n changes: Changes | ChangesWithHash;\n printEnvironmentChangesOptions?: Partial<PrintChangesOptions>;\n },\n ): Promise<void> {\n ctx.log.debug(\"getting changes from gadget\", { filesVersion, changes });\n const created = changes.created();\n const updated = changes.updated();\n\n const spinner = spin({ ensureEmptyLineAbove: true })(\n sprintChanges(ctx, {\n changes,\n tense: \"present\",\n title: sprint`Pulling ${pluralize(\"file\", changes.size)}. ${symbol.arrowLeft}`,\n ...printEnvironmentChangesOptions,\n }),\n );\n\n try {\n let files: File[] = [];\n if (created.length > 0 || updated.length > 0) {\n const { fileSyncFiles } = await this.syncJson.edit.query({\n query: FILE_SYNC_FILES_QUERY,\n variables: {\n paths: [...created, ...updated],\n filesVersion: String(filesVersion),\n encoding: FileSyncEncoding.Base64,\n },\n });\n\n files = fileSyncFiles.files;\n }\n\n await this._writeToLocalFilesystem(ctx, {\n filesVersion,\n files,\n delete: changes.deleted(),\n spinner,\n printEnvironmentChangesOptions,\n });\n } catch (error) {\n spinner.fail();\n throw error;\n }\n }\n\n private async _sendChangesToEnvironment(\n ctx: Context<SyncJsonArgs>,\n {\n changes,\n expectedFilesVersion = this.syncJson.filesVersion,\n printLocalChangesOptions,\n }: {\n changes: Changes | ChangesWithHash;\n expectedFilesVersion?: bigint;\n printLocalChangesOptions?: Partial<PrintChangesOptions>;\n },\n ): Promise<void> {\n ctx.log.debug(\"sending changes to gadget\", { expectedFilesVersion, changes });\n const changed: FileSyncChangedEventInput[] = [];\n const deleted: FileSyncDeletedEventInput[] = [];\n\n await pMap(changes, async ([normalizedPath, change]) => {\n if (change.type === \"delete\") {\n deleted.push({ path: normalizedPath });\n return;\n }\n\n const absolutePath = this.syncJson.directory.absolute(normalizedPath);\n\n let stats;\n try {\n stats = await fs.stat(absolutePath);\n } catch (error) {\n swallowEnoent(error);\n ctx.log.debug(\"skipping change because file doesn't exist\", { path: normalizedPath });\n return;\n }\n\n let content = \"\";\n if (stats.isFile()) {\n content = await fs.readFile(absolutePath, FileSyncEncoding.Base64);\n }\n\n let oldPath;\n if (change.type === \"create\" && change.oldPath) {\n oldPath = change.oldPath;\n }\n\n changed.push({\n content,\n oldPath,\n path: normalizedPath,\n mode: stats.mode,\n encoding: FileSyncEncoding.Base64,\n });\n });\n\n if (changed.length === 0 && deleted.length === 0) {\n ctx.log.debug(\"skipping send because there are no changes\");\n return;\n }\n\n const contentLength = changed.map((change) => change.content.length).reduce((a, b) => a + b, 0);\n if (contentLength > MAX_PUSH_CONTENT_LENGTH) {\n throw new EdgeCaseError(sprint`\n {underline Your file changes are too large to push.}\n\n Run \"ggt status\" to see your changes and consider\n ignoring some files or pushing in smaller batches.\n `);\n }\n\n const spinner = spin({ ensureEmptyLineAbove: true })(\n sprintChanges(ctx, {\n changes,\n tense: \"present\",\n title: sprintln`Pushing ${pluralize(\"file\", changed.length + deleted.length)}. ${symbol.arrowRight}`,\n ...printLocalChangesOptions,\n }),\n );\n\n try {\n const {\n publishFileSyncEvents: { remoteFilesVersion, problems: filesyncProblems },\n } = await this.syncJson.edit.mutate({\n mutation: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: {\n input: {\n expectedRemoteFilesVersion: String(expectedFilesVersion),\n changed,\n deleted,\n },\n },\n http: {\n retry: {\n // we can retry this request because\n // expectedRemoteFilesVersion makes it idempotent\n methods: [\"POST\"],\n calculateDelay: ({ error, computedValue }) => {\n if (isFilesVersionMismatchError(error.response?.body)) {\n // don't retry if we get a files version mismatch error\n return 0;\n }\n return computedValue;\n },\n },\n },\n });\n\n if (BigInt(remoteFilesVersion) > expectedFilesVersion + 1n) {\n // we can't save the remoteFilesVersion because we haven't\n // received the intermediate filesVersions yet\n throw new Error(\"Files version mismatch\");\n }\n\n await this.syncJson.save(remoteFilesVersion);\n\n spinner.succeed(\n sprintChanges(ctx, {\n changes,\n tense: \"past\",\n title: sprintln`Pushed ${pluralize(\"file\", changed.length + deleted.length)}. ${symbol.arrowRight} ${ts()}`,\n ...printLocalChangesOptions,\n }),\n );\n\n if (filesyncProblems.length > 0) {\n println({ ensureEmptyLineAbove: true })`\n {red Gadget has detected the following fatal errors with your files:}\n\n ${sprintProblems({\n problems: filesyncProblemsToProblems(filesyncProblems),\n showFileTypes: false,\n indent: 10,\n })}\n\n {red Your app will not be operational until all fatal errors are fixed.}\n `;\n }\n } catch (error) {\n if (isFilesVersionMismatchError(error)) {\n spinner.clear();\n } else {\n spinner.fail();\n }\n\n throw error;\n }\n }\n\n private async _writeToLocalFilesystem(\n ctx: Context<SyncJsonArgs>,\n options: {\n filesVersion: bigint | string;\n files: File[];\n delete: string[];\n printEnvironmentChangesOptions?: Partial<PrintChangesOptions>;\n spinner?: spinner;\n },\n ): Promise<Changes> {\n const filesVersion = BigInt(options.filesVersion);\n assert(filesVersion >= this.syncJson.filesVersion, \"filesVersion must be greater than or equal to current filesVersion\");\n\n ctx.log.debug(\"writing to local filesystem\", {\n filesVersion,\n files: options.files.map((file) => file.path),\n delete: options.delete,\n });\n\n const created: string[] = [];\n const updated: string[] = [];\n\n await pMap(options.delete, async (filepath) => {\n const currentPath = this.syncJson.directory.absolute(filepath);\n const backupPath = this.syncJson.directory.absolute(\".gadget/backup\", this.syncJson.directory.relative(filepath));\n\n // rather than `rm -rf`ing files, we move them to\n // `.gadget/backup/` so that users can recover them if something\n // goes wrong. We've seen a lot of EBUSY/EINVAL errors when moving\n // files so we retry a few times.\n await pRetry(\n async () => {\n try {\n // remove the current backup file in case it exists and is a\n // different type (file vs directory)\n await fs.remove(backupPath);\n await fs.move(currentPath, backupPath);\n } catch (error) {\n // replicate the behavior of `rm -rf` and ignore ENOENT\n swallowEnoent(error);\n }\n },\n {\n // windows tends to run into these issues way more often than\n // mac/linux, so we retry more times\n retries: config.windows ? 4 : 2,\n minTimeout: ms(\"100ms\"),\n onFailedAttempt: (error) => {\n ctx.log.warn(\"failed to move file to backup\", { error, currentPath, backupPath });\n },\n },\n );\n });\n\n await pMap(options.files, async (file) => {\n const absolutePath = this.syncJson.directory.absolute(file.path);\n if (await fs.pathExists(absolutePath)) {\n updated.push(file.path);\n } else {\n created.push(file.path);\n }\n\n if (file.path.endsWith(\"/\")) {\n await fs.ensureDir(absolutePath);\n } else {\n await fs.outputFile(absolutePath, Buffer.from(file.content, file.encoding));\n }\n\n if (supportsPermissions) {\n // the os's default umask makes setting the mode during creation\n // not work, so an additional fs.chmod call is necessary to\n // ensure the file has the correct mode\n await fs.chmod(absolutePath, file.mode & 0o777);\n }\n\n if (absolutePath === this.syncJson.directory.absolute(\".ignore\")) {\n await this.syncJson.directory.loadIgnoreFile();\n }\n });\n\n await this.syncJson.save(String(filesVersion));\n\n const changes = new Changes([\n ...created.map((path) => [path, { type: \"create\" }] as const),\n ...updated.map((path) => [path, { type: \"update\" }] as const),\n ...options.delete.map((path) => [path, { type: \"delete\" }] as const),\n ]);\n\n options.spinner?.clear();\n\n printChanges(ctx, {\n changes,\n tense: \"past\",\n title: sprint`{green ${symbol.tick}} Pulled ${pluralize(\"file\", changes.size)}. ${symbol.arrowLeft} ${ts()}`,\n ...options.printEnvironmentChangesOptions,\n });\n\n if (changes.has(\"yarn.lock\")) {\n const spinner = spin({ ensureEmptyLineAbove: true })('Running \"yarn install --check-files\"');\n\n try {\n await execa(\"yarn\", [\"install\", \"--check-files\"], { cwd: this.syncJson.directory.path });\n spinner.succeed`Ran \"yarn install --check-files\" ${ts()}`;\n } catch (error) {\n spinner.fail();\n ctx.log.error(\"yarn install failed\", { error });\n\n const message = serializeError(error).message;\n if (message) {\n println({ ensureEmptyLineAbove: true, indent: 2 })(message);\n }\n }\n }\n\n return changes;\n }\n}\n"],"names":["execa","fs","ms","assert","process","pMap","PQueue","pRetry","pluralize","FileSyncEncoding","FILE_SYNC_COMPARISON_HASHES_QUERY","FILE_SYNC_FILES_QUERY","FILE_SYNC_HASHES_QUERY","PUBLISH_FILE_SYNC_EVENTS_MUTATION","REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION","config","confirm","println","filesyncProblemsToProblems","sprintProblems","EdgeCaseError","select","spin","sprint","sprintln","symbol","ts","noop","serializeError","Changes","printChanges","sprintChanges","getConflicts","printConflicts","withoutConflictingChanges","supportsPermissions","swallowEnoent","TooManyMergeAttemptsError","isFilesVersionMismatchError","swallowFilesVersionMismatch","getNecessaryChanges","isEqualHashes","MergeConflictPreference","MAX_MERGE_ATTEMPTS","MAX_PUSH_CONTENT_LENGTH","FileSync","hashes","ctx","spinner","ensureEmptyLineAbove","localHashes","localFilesVersionHashes","environmentHashes","environmentFilesVersion","Promise","all","syncJson","directory","filesVersion","fileSyncHashes","edit","query","BigInt","fileSyncComparisonHashes","variables","String","filesVersionHashes","latestFilesVersionHashes","inSync","localChanges","from","to","existing","ignore","environmentChanges","size","Array","keys","every","path","startsWith","localChangesToPush","environmentChangesToPull","onlyDotGadgetFilesChanged","filepath","bothChanged","succeed","error","fail","print","changes","tense","title","idle","_syncOperations","onIdle","mergeChangesWithEnvironment","printLocalChangesOptions","printEnvironmentChangesOptions","add","_sendChangesToEnvironment","merge","subscribeToEnvironmentChanges","beforeChanges","afterChanges","onError","subscribe","subscription","localFilesVersion","onData","remoteFileSyncEvents","changed","deleted","remoteFilesVersion","log","warn","debug","map","change","filterIgnoredFiles","file","ignored","ignores","filter","length","save","_writeToLocalFilesystem","files","delete","tick","arrowLeft","limit","catch","maxAttempts","attempt","clear","info","_merge","push","force","args","expectedFilesVersion","command","pull","_getChangesFromEnvironment","conflicts","preference","choices","Object","values","CANCEL","exit","LOCAL","ENVIRONMENT","created","updated","fileSyncFiles","paths","encoding","Base64","normalizedPath","type","absolutePath","absolute","stats","stat","content","isFile","readFile","oldPath","mode","contentLength","reduce","a","b","arrowRight","publishFileSyncEvents","problems","filesyncProblems","mutate","mutation","input","expectedRemoteFilesVersion","http","retry","methods","calculateDelay","computedValue","response","body","Error","showFileTypes","indent","options","currentPath","backupPath","relative","remove","move","retries","windows","minTimeout","onFailedAttempt","pathExists","endsWith","ensureDir","outputFile","Buffer","chmod","loadIgnoreFile","has","cwd","message","constructor","concurrency"],"mappings":";AAAA,SAASA,KAAK,QAAQ,QAAQ;AAC9B,OAAOC,QAAQ,WAAW;AAC1B,OAAOC,QAAQ,KAAK;AACpB,OAA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AQ/F,8BAA8B;QAC3C;QAEA,IAAIR,QAAQwH,GAAG,CAAC,cAAc;YAC5B,MAAMlK,UAAU1B,KAAK;gBAAE2B,sBAAsB;YAAK,GAAG;YAErD,IAAI;gBACF,MAAMjD,MAAM,QAAQ;oBAAC;oBAAW;iBAAgB,EAAE;oBAAEmN,KAAK,IAAI,CAAC3J,QAAQ,CAACC,SAAS,CAACsB,IAAI;gBAAC;gBACtF/B,QAAQsC,OAAO,CAAC,iCAAiC,EAAE5D,KAAK,CAAC;YAC3D,EAAE,OAAO6D,OAAO;gBACdvC,QAAQwC,IAAI;gBACZzC,IAAImE,GAAG,CAAC3B,KAAK,CAAC,uBAAuB;oBAAEA;gBAAM;gBAE7C,MAAM6H,UAAUxL,eAAe2D,OAAO6H,OAAO;gBAC7C,IAAIA,SAAS;oBACXnM,QAAQ;wBAAEgC,sBAAsB;wBAAM+I,QAAQ;oBAAE,GAAGoB;gBACrD;YACF;QACF;QAEA,OAAO1H;IACT;IA3wBA2H,YAAY,AAAS7J,QAAkB,CAAE;;QANzC;;;GAGC,GACD,uBAAQsC,mBAAR,KAAA;aAEqBtC,WAAAA;aAFbsC,kBAAkB,IAAIxF,OAAO;YAAEgN,aAAa;QAAE;IAEZ;AA4wB5C"}
@@ -11,13 +11,16 @@ export class ChangesWithHash extends Map {
11
11
  }
12
12
  }
13
13
  /**
14
- * Calculates the changes that were made to `from` to make it end up as `to`.
14
+ * Depending on the callers perspective, this either calculates the
15
+ * changes that were made to `from` to make it end up as `to`, or it
16
+ * calculates the changes that need to be made to `from` to make it end
17
+ * up as `to`.
15
18
  *
16
- * If `existing` is provided, only the changes that are necessary to
17
- * apply to `existing` are returned.
19
+ * If `existing` is provided, any changes that `existing` already has
20
+ * are skipped.
18
21
  *
19
22
  * If `ignore` is provided, any changes that were made to a path that
20
- * starts with any of the `ignore` paths are skipped.
23
+ * starts with any of the `ignore`ed paths are skipped.
21
24
  *
22
25
  * @param ctx - The current context.
23
26
  * @param options - The options to use.
@@ -25,7 +28,7 @@ export class ChangesWithHash extends Map {
25
28
  * @param options.to - The target hashes.
26
29
  * @param options.existing - The existing hashes.
27
30
  * @param options.ignore - The paths to ignore.
28
- */ export const getChanges = (ctx, { from: source, to: target, existing, ignore })=>{
31
+ */ export const getNecessaryChanges = (ctx, { from: source, to: target, existing, ignore })=>{
29
32
  const changes = new ChangesWithHash();
30
33
  const targetPaths = Object.keys(target);
31
34
  for (const [sourcePath, sourceHash] of Object.entries(source)){
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/services/filesync/hashes.ts"],"sourcesContent":["import assert from \"node:assert\";\nimport type { Context } from \"../command/context.js\";\nimport { type Create, type Delete, type Update } from \"./changes.js\";\nimport type { Hash, Hashes } from \"./directory.js\";\n\nexport type CreateWithHash = Create & { targetHash: Hash };\nexport type UpdateWithHash = Update & { sourceHash: Hash; targetHash: Hash };\nexport type DeleteWithHash = Delete & { sourceHash: Hash };\nexport type ChangeWithHash = CreateWithHash | UpdateWithHash | DeleteWithHash;\n\nexport class ChangesWithHash extends Map<string, ChangeWithHash> {\n created(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"create\")\n .map(([path]) => path);\n }\n\n updated(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"update\")\n .map(([path]) => path);\n }\n\n deleted(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"delete\")\n .map(([path]) => path);\n }\n}\n\n/**\n * Calculates the changes that were made to `from` to make it end up as `to`.\n *\n * If `existing` is provided, only the changes that are necessary to\n * apply to `existing` are returned.\n *\n * If `ignore` is provided, any changes that were made to a path that\n * starts with any of the `ignore` paths are skipped.\n *\n * @param ctx - The current context.\n * @param options - The options to use.\n * @param options.from - The source hashes.\n * @param options.to - The target hashes.\n * @param options.existing - The existing hashes.\n * @param options.ignore - The paths to ignore.\n */\nexport const getChanges = (\n ctx: Context,\n {\n from: source,\n to: target,\n existing,\n ignore,\n }: {\n from: Hashes;\n to: Hashes;\n existing?: Hashes;\n ignore?: string[];\n },\n): ChangesWithHash => {\n const changes = new ChangesWithHash();\n const targetPaths = Object.keys(target);\n\n for (const [sourcePath, sourceHash] of Object.entries(source)) {\n if (ignore?.some((ignored) => sourcePath.startsWith(ignored))) {\n continue;\n }\n\n const targetHash = target[sourcePath];\n if (!targetHash) {\n if (!sourcePath.endsWith(\"/\") || !targetPaths.some((targetPath) => targetPath.startsWith(sourcePath))) {\n // sourcePath is a file and it doesn't exist in target OR\n // sourcePath is a directory and target doesn't have any\n // existing files inside it, therefor the sourcePath has been\n // deleted\n changes.set(sourcePath, { type: \"delete\", sourceHash });\n ctx.log.trace(\"file deleted\", { path: sourcePath, sourceHash });\n }\n } else if (!isEqualHash(sourcePath, sourceHash, targetHash)) {\n // the file or directory exists in target, but has a different\n // hash, so it's been updated\n changes.set(sourcePath, { type: \"update\", sourceHash, targetHash });\n ctx.log.trace(\"file updated\", { path: sourcePath, sourceHash, targetHash });\n }\n }\n\n for (const targetPath of targetPaths) {\n if (ignore?.some((ignored) => targetPath.startsWith(ignored))) {\n continue;\n }\n\n if (!source[targetPath]) {\n // the targetPath doesn't exist in source, so it's been created\n const targetHash = target[targetPath];\n assert(targetHash, \"targetHash should exist\");\n\n changes.set(targetPath, { type: \"create\", targetHash });\n ctx.log.trace(\"file created\", { path: targetPath, targetHash });\n }\n }\n\n if (!existing) {\n return changes;\n }\n\n return withoutUnnecessaryChanges(ctx, { changes, existing });\n};\n\n/**\n * Filters out changes that the existing filesystem already has.\n */\nexport const withoutUnnecessaryChanges = (\n ctx: Context,\n { changes, existing }: { changes: ChangesWithHash; existing: Hashes },\n): ChangesWithHash => {\n const necessaryChanges = new ChangesWithHash();\n\n for (const [path, change] of changes) {\n const existingHash = existing[path];\n if (change.type === \"delete\" && !existingHash) {\n // already deleted\n ctx.log.trace(\"already deleted\", { path });\n continue;\n }\n\n if (change.type !== \"delete\" && existingHash && isEqualHash(path, change.targetHash, existingHash)) {\n // already created or updated\n ctx.log.trace(\"already created or updated\", { path, existingHash, targetHash: change.targetHash });\n continue;\n }\n\n // we could do this:\n // if (change.type === \"update\" && !existingHash) {\n // change = { type: \"create\", targetHash: change.targetHash };\n // }\n // but, changing the type makes the output look confusing and it\n // doesn't change the outcome, so we just leave it as is\n\n necessaryChanges.set(path, change);\n }\n\n return necessaryChanges;\n};\n\nexport const isEqualHash = (_path: string, aHash: Hash, bHash: Hash): boolean => {\n // FIXME: we're running into issues syncing permissions with Gadget\n // so we're temporarily disabling this check until we can figure out\n return aHash.sha1 === bHash.sha1;\n\n // if (aHash.sha1 !== bHash.sha1) {\n // // the contents are different\n // return false;\n // }\n\n // if (path.endsWith(\"/\")) {\n // // it's a directory, so we don't care about permissions\n // return true;\n // }\n\n // if (isNil(aHash.permissions) || isNil(bHash.permissions)) {\n // // one of the filesystems doesn't support permissions, so ignore them\n // return true;\n // }\n\n // // the contents are the same, and both filesystems support permissions\n // // so ensure the permissions are also the same\n // return aHash.permissions === bHash.permissions;\n};\n\nexport const isEqualHashes = (ctx: Context, a: Hashes, b: Hashes): boolean => {\n for (const [aPath, aHash] of Object.entries(a)) {\n const bHash = b[aPath];\n if (!bHash || !isEqualHash(aPath, aHash, bHash)) {\n ctx.log.debug(\"hashes are not equal\", { path: aPath, aHash, bHash });\n return false;\n }\n }\n\n for (const bPath of Object.keys(b)) {\n if (!a[bPath]) {\n ctx.log.debug(\"hashes are not equal\", { path: bPath, aHash: undefined, bHash: b[bPath] });\n return false;\n }\n }\n\n return true;\n};\n"],"names":["assert","ChangesWithHash","Map","created","Array","from","entries","filter","change","type","map","path","updated","deleted","getChanges","ctx","source","to","target","existing","ignore","changes","targetPaths","Object","keys","sourcePath","sourceHash","some","ignored","startsWith","targetHash","endsWith","targetPath","set","log","trace","isEqualHash","withoutUnnecessaryChanges","necessaryChanges","existingHash","_path","aHash","bHash","sha1","isEqualHashes","a","b","aPath","debug","bPath","undefined"],"mappings":"AAAA,OAAOA,YAAY,cAAc;AAUjC,OAAO,MAAMC,w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AAO;AACT,EAAE"}
1
+ {"version":3,"sources":["../../../src/services/filesync/hashes.ts"],"sourcesContent":["import assert from \"node:assert\";\nimport type { Context } from \"../command/context.js\";\nimport { type Create, type Delete, type Update } from \"./changes.js\";\nimport type { Hash, Hashes } from \"./directory.js\";\n\nexport type CreateWithHash = Create & { targetHash: Hash };\nexport type UpdateWithHash = Update & { sourceHash: Hash; targetHash: Hash };\nexport type DeleteWithHash = Delete & { sourceHash: Hash };\nexport type ChangeWithHash = CreateWithHash | UpdateWithHash | DeleteWithHash;\n\nexport class ChangesWithHash extends Map<string, ChangeWithHash> {\n created(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"create\")\n .map(([path]) => path);\n }\n\n updated(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"update\")\n .map(([path]) => path);\n }\n\n deleted(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"delete\")\n .map(([path]) => path);\n }\n}\n\n/**\n * Depending on the callers perspective, this either calculates the\n * changes that were made to `from` to make it end up as `to`, or it\n * calculates the changes that need to be made to `from` to make it end\n * up as `to`.\n *\n * If `existing` is provided, any changes that `existing` already has\n * are skipped.\n *\n * If `ignore` is provided, any changes that were made to a path that\n * starts with any of the `ignore`ed paths are skipped.\n *\n * @param ctx - The current context.\n * @param options - The options to use.\n * @param options.from - The source hashes.\n * @param options.to - The target hashes.\n * @param options.existing - The existing hashes.\n * @param options.ignore - The paths to ignore.\n */\nexport const getNecessaryChanges = (\n ctx: Context,\n {\n from: source,\n to: target,\n existing,\n ignore,\n }: {\n from: Hashes;\n to: Hashes;\n existing?: Hashes;\n ignore?: string[];\n },\n): ChangesWithHash => {\n const changes = new ChangesWithHash();\n const targetPaths = Object.keys(target);\n\n for (const [sourcePath, sourceHash] of Object.entries(source)) {\n if (ignore?.some((ignored) => sourcePath.startsWith(ignored))) {\n continue;\n }\n\n const targetHash = target[sourcePath];\n if (!targetHash) {\n if (!sourcePath.endsWith(\"/\") || !targetPaths.some((targetPath) => targetPath.startsWith(sourcePath))) {\n // sourcePath is a file and it doesn't exist in target OR\n // sourcePath is a directory and target doesn't have any\n // existing files inside it, therefor the sourcePath has been\n // deleted\n changes.set(sourcePath, { type: \"delete\", sourceHash });\n ctx.log.trace(\"file deleted\", { path: sourcePath, sourceHash });\n }\n } else if (!isEqualHash(sourcePath, sourceHash, targetHash)) {\n // the file or directory exists in target, but has a different\n // hash, so it's been updated\n changes.set(sourcePath, { type: \"update\", sourceHash, targetHash });\n ctx.log.trace(\"file updated\", { path: sourcePath, sourceHash, targetHash });\n }\n }\n\n for (const targetPath of targetPaths) {\n if (ignore?.some((ignored) => targetPath.startsWith(ignored))) {\n continue;\n }\n\n if (!source[targetPath]) {\n // the targetPath doesn't exist in source, so it's been created\n const targetHash = target[targetPath];\n assert(targetHash, \"targetHash should exist\");\n\n changes.set(targetPath, { type: \"create\", targetHash });\n ctx.log.trace(\"file created\", { path: targetPath, targetHash });\n }\n }\n\n if (!existing) {\n return changes;\n }\n\n return withoutUnnecessaryChanges(ctx, { changes, existing });\n};\n\n/**\n * Filters out changes that the existing filesystem already has.\n */\nexport const withoutUnnecessaryChanges = (\n ctx: Context,\n { changes, existing }: { changes: ChangesWithHash; existing: Hashes },\n): ChangesWithHash => {\n const necessaryChanges = new ChangesWithHash();\n\n for (const [path, change] of changes) {\n const existingHash = existing[path];\n if (change.type === \"delete\" && !existingHash) {\n // already deleted\n ctx.log.trace(\"already deleted\", { path });\n continue;\n }\n\n if (change.type !== \"delete\" && existingHash && isEqualHash(path, change.targetHash, existingHash)) {\n // already created or updated\n ctx.log.trace(\"already created or updated\", { path, existingHash, targetHash: change.targetHash });\n continue;\n }\n\n // we could do this:\n // if (change.type === \"update\" && !existingHash) {\n // change = { type: \"create\", targetHash: change.targetHash };\n // }\n // but, changing the type makes the output look confusing and it\n // doesn't change the outcome, so we just leave it as is\n\n necessaryChanges.set(path, change);\n }\n\n return necessaryChanges;\n};\n\nexport const isEqualHash = (_path: string, aHash: Hash, bHash: Hash): boolean => {\n // FIXME: we're running into issues syncing permissions with Gadget\n // so we're temporarily disabling this check until we can figure out\n return aHash.sha1 === bHash.sha1;\n\n // if (aHash.sha1 !== bHash.sha1) {\n // // the contents are different\n // return false;\n // }\n\n // if (path.endsWith(\"/\")) {\n // // it's a directory, so we don't care about permissions\n // return true;\n // }\n\n // if (isNil(aHash.permissions) || isNil(bHash.permissions)) {\n // // one of the filesystems doesn't support permissions, so ignore them\n // return true;\n // }\n\n // // the contents are the same, and both filesystems support permissions\n // // so ensure the permissions are also the same\n // return aHash.permissions === bHash.permissions;\n};\n\nexport const isEqualHashes = (ctx: Context, a: Hashes, b: Hashes): boolean => {\n for (const [aPath, aHash] of Object.entries(a)) {\n const bHash = b[aPath];\n if (!bHash || !isEqualHash(aPath, aHash, bHash)) {\n ctx.log.debug(\"hashes are not equal\", { path: aPath, aHash, bHash });\n return false;\n }\n }\n\n for (const bPath of Object.keys(b)) {\n if (!a[bPath]) {\n ctx.log.debug(\"hashes are not equal\", { path: bPath, aHash: undefined, bHash: b[bPath] });\n return false;\n }\n }\n\n return true;\n};\n"],"names":["assert","ChangesWithHash","Map","created","Array","from","entries","filter","change","type","map","path","updated","deleted","getNecessaryChanges","ctx","source","to","target","existing","ignore","changes","targetPaths","Object","keys","sourcePath","sourceHash","some","ignored","startsWith","targetHash","endsWith","targetPath","set","log","trace","isEqualHash","withoutUnnecessaryChanges","necessaryChanges","existingHash","_path","aHash","bHash","sha1","isEqualHashes","a","b","aPath","debug","bPath","undefined"],"mappings":"AAAA,OAAOA,YAAY,cAAc;AAUjC,OAAO,MAAMC,wBAAwBC;IACnCC,UAAoB;QAClB,OAAOC,MAAMC,IAAI,CAAC,IAAI,CAACC,OAAO,IAC3BC,MAAM,CAAC,CAAC,GAAGC,OAAO,GAAKA,OAAOC,IAAI,KAAK,UACvCC,GAAG,CAAC,CAAC,CAACC,KAAK,GAAKA;IACrB;IAEAC,UAAoB;QAClB,OAAOR,MAAMC,IA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;QAChE,wDAAwD;QAExDQ,iBAAiBL,GAAG,CAACtB,MAAMH;IAC7B;IAEA,OAAO8B;AACT,EAAE;AAEF,OAAO,MAAMF,cAAc,CAACI,OAAeC,OAAaC;IACtD,mEAAmE;IACnE,oEAAoE;IACpE,OAAOD,MAAME,IAAI,KAAKD,MAAMC,IAAI;AAEhC,mCAAmC;AACnC,kCAAkC;AAClC,kBAAkB;AAClB,IAAI;AAEJ,4BAA4B;AAC5B,4DAA4D;AAC5D,iBAAiB;AACjB,IAAI;AAEJ,8DAA8D;AAC9D,0EAA0E;AAC1E,iBAAiB;AACjB,IAAI;AAEJ,yEAAyE;AACzE,iDAAiD;AACjD,kDAAkD;AACpD,EAAE;AAEF,OAAO,MAAMC,gBAAgB,CAAC7B,KAAc8B,GAAWC;IACrD,KAAK,MAAM,CAACC,OAAON,MAAM,IAAIlB,OAAOjB,OAAO,CAACuC,GAAI;QAC9C,MAAMH,QAAQI,CAAC,CAACC,MAAM;QACtB,IAAI,CAACL,SAAS,CAACN,YAAYW,OAAON,OAAOC,QAAQ;YAC/C3B,IAAImB,GAAG,CAACc,KAAK,CAAC,wBAAwB;gBAAErC,MAAMoC;gBAAON;gBAAOC;YAAM;YAClE,OAAO;QACT;IACF;IAEA,KAAK,MAAMO,SAAS1B,OAAOC,IAAI,CAACsB,GAAI;QAClC,IAAI,CAACD,CAAC,CAACI,MAAM,EAAE;YACblC,IAAImB,GAAG,CAACc,KAAK,CAAC,wBAAwB;gBAAErC,MAAMsC;gBAAOR,OAAOS;gBAAWR,OAAOI,CAAC,CAACG,MAAM;YAAC;YACvF,OAAO;QACT;IACF;IAEA,OAAO;AACT,EAAE"}
@@ -0,0 +1,59 @@
1
+ import { ArgError } from "../command/arg.js";
2
+ import { sprint } from "../output/sprint.js";
3
+ export const FileSyncStrategy = Object.freeze({
4
+ CANCEL: "cancel",
5
+ MERGE: "merge",
6
+ PUSH: "push",
7
+ PULL: "pull"
8
+ });
9
+ export const MergeConflictPreference = Object.freeze({
10
+ CANCEL: sprint`Cancel (Ctrl+C)`,
11
+ LOCAL: sprint`Keep {underline local} conflicting changes`,
12
+ ENVIRONMENT: sprint`Keep {underline environment}'s conflicting changes`
13
+ });
14
+ export const MergeConflictPreferenceArg = (value, name)=>{
15
+ if ([
16
+ "local",
17
+ "environment"
18
+ ].includes(value)) {
19
+ return MergeConflictPreference[value.toUpperCase()];
20
+ }
21
+ if (value === "gadget") {
22
+ // v0.4 (deprecated)
23
+ return MergeConflictPreference.ENVIRONMENT;
24
+ }
25
+ throw new ArgError(sprint`
26
+ ${name} must be {bold local} or {bold environment}
27
+
28
+ {bold EXAMPLES:}
29
+ ${name}=local
30
+ ${name}=environment
31
+ `);
32
+ }; // export type FileSyncArgs = DevArgs | PushArgs | PullArgs;
33
+ // export const getFileSyncStrategy = (ctx: Context<FileSyncArgs>): FileSyncStrategy | undefined => {
34
+ // switch (true) {
35
+ // case ctx.args["--push"]:
36
+ // return FileSyncStrategy.PUSH;
37
+ // case ctx.args["--pull"]:
38
+ // return FileSyncStrategy.PULL;
39
+ // case ctx.args["--merge"]:
40
+ // return FileSyncStrategy.MERGE;
41
+ // default:
42
+ // return undefined;
43
+ // }
44
+ // };
45
+ // export const validateFileSyncStrategy = (ctx: Context<FileSyncArgs>): void => {
46
+ // const strategies = ["--push", "--pull", "--merge"] as const;
47
+ // for (const strategy of strategies) {
48
+ // if (!ctx.args[strategy]) {
49
+ // continue;
50
+ // }
51
+ // for (const conflicting of strategies.filter((s) => s !== strategy)) {
52
+ // if (ctx.args[conflicting]) {
53
+ // throw new ArgError(sprint`{bold ${strategy}} and {bold ${conflicting}} cannot be used together`);
54
+ // }
55
+ // }
56
+ // }
57
+ // };
58
+
59
+ //# sourceMappingURL=strategy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/services/filesync/strategy.ts"],"sourcesContent":["import { ArgError } from \"../command/arg.js\";\nimport { sprint } from \"../output/sprint.js\";\n\nexport const FileSyncStrategy = Object.freeze({\n CANCEL: \"cancel\",\n MERGE: \"merge\",\n PUSH: \"push\",\n PULL: \"pull\",\n});\n\nexport type FileSyncStrategy = (typeof FileSyncStrategy)[keyof typeof FileSyncStrategy];\n\nexport const MergeConflictPreference = Object.freeze({\n CANCEL: sprint`Cancel (Ctrl+C)`,\n LOCAL: sprint`Keep {underline local} conflicting changes`,\n ENVIRONMENT: sprint`Keep {underline environment}'s conflicting changes`,\n});\n\nexport type MergeConflictPreference = (typeof MergeConflictPreference)[keyof typeof MergeConflictPreference];\n\nexport const MergeConflictPreferenceArg = (value: string, name: string): MergeConflictPreference => {\n if ([\"local\", \"environment\"].includes(value)) {\n return MergeConflictPreference[value.toUpperCase() as keyof typeof MergeConflictPreference];\n }\n\n if (value === \"gadget\") {\n // v0.4 (deprecated)\n return MergeConflictPreference.ENVIRONMENT;\n }\n\n throw new ArgError(sprint`\n ${name} must be {bold local} or {bold environment}\n\n {bold EXAMPLES:}\n ${name}=local\n ${name}=environment\n `);\n};\n\n// export type FileSyncArgs = DevArgs | PushArgs | PullArgs;\n\n// export const getFileSyncStrategy = (ctx: Context<FileSyncArgs>): FileSyncStrategy | undefined => {\n// switch (true) {\n// case ctx.args[\"--push\"]:\n// return FileSyncStrategy.PUSH;\n// case ctx.args[\"--pull\"]:\n// return FileSyncStrategy.PULL;\n// case ctx.args[\"--merge\"]:\n// return FileSyncStrategy.MERGE;\n// default:\n// return undefined;\n// }\n// };\n\n// export const validateFileSyncStrategy = (ctx: Context<FileSyncArgs>): void => {\n// const strategies = [\"--push\", \"--pull\", \"--merge\"] as const;\n// for (const strategy of strategies) {\n// if (!ctx.args[strategy]) {\n// continue;\n// }\n\n// for (const conflicting of strategies.filter((s) => s !== strategy)) {\n// if (ctx.args[conflicting]) {\n// throw new ArgError(sprint`{bold ${strategy}} and {bold ${conflicting}} cannot be used together`);\n// }\n// }\n// }\n// };\n"],"names":["ArgError","sprint","FileSyncStrategy","Object","freeze","CANCEL","MERGE","PUSH","PULL","MergeConflictPreference","LOCAL","ENVIRONMENT","MergeConflictPreferenceArg","value","name","includes","toUpperCase"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,oBAAoB;AAC7C,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,OAAO,MAAMC,mBAAmBC,OAAOC,MAAM,CAAC;IAC5CC,QAAQ;IACRC,OAAO;IACPC,MAAM;IACNC,MAAM;AACR,GAAG;AAIH,OAAO,MAAMC,0BAA0BN,OAAOC,MAAM,CAAC;IACnDC,QAAQJ,MAAM,CAAC,eAAe,CAAC;IAC/BS,OAAOT,MAAM,CAAC,0CAA0C,CAAC;IACzDU,aAAaV,MAAM,CAAC,kDAAkD,CAAC;AACzE,GAAG;AAIH,OAAO,MAAMW,6BAA6B,CAACC,OAAeC;IACxD,IAAI;QAAC;QAAS;KAAc,CAACC,QAAQ,CAACF,QAAQ;QAC5C,OAAOJ,uBAAuB,CAACI,MAAMG,WAAW,GAA2C;IAC7F;IAEA,IAAIH,UAAU,UAAU;QACtB,oBAAoB;QACpB,OAAOJ,wBAAwBE,WAAW;IAC5C;IAEA,MAAM,IAAIX,SAASC,MAAM,CAAC;MACtB,EAAEa,KAAK;;;QAGL,EAAEA,KAAK;QACP,EAAEA,KAAK;IACX,CAAC;AACL,EAAE,CAEF,4DAA4D;CAE5D,qGAAqG;CACrG,oBAAoB;CACpB,+BAA+B;CAC/B,sCAAsC;CACtC,+BAA+B;CAC/B,sCAAsC;CACtC,gCAAgC;CAChC,uCAAuC;CACvC,eAAe;CACf,0BAA0B;CAC1B,MAAM;CACN,KAAK;CAEL,kFAAkF;CAClF,iEAAiE;CACjE,yCAAyC;CACzC,iCAAiC;CACjC,kBAAkB;CAClB,QAAQ;CAER,4EAA4E;CAC5E,qCAAqC;CACrC,4GAA4G;CAC5G,UAAU;CACV,QAAQ;CACR,MAAM;CACN,KAAK"}