@nimbus-sh/worker 0.10.0 → 0.11.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 (260) hide show
  1. package/NOTICE.md +5 -0
  2. package/README.md +10 -0
  3. package/dist/_shared/session-router.d.ts +7 -0
  4. package/dist/_shared/session-router.d.ts.map +1 -1
  5. package/dist/_shared/session-router.js +7 -0
  6. package/dist/bindings/body.d.ts +6 -0
  7. package/dist/bindings/body.d.ts.map +1 -0
  8. package/dist/bindings/body.js +37 -0
  9. package/dist/bindings/kv.d.ts +0 -2
  10. package/dist/bindings/kv.d.ts.map +1 -1
  11. package/dist/bindings/kv.js +3 -42
  12. package/dist/bindings/r2.d.ts +0 -2
  13. package/dist/bindings/r2.d.ts.map +1 -1
  14. package/dist/bindings/r2.js +4 -44
  15. package/dist/esbuild-cli-artifact.generated.d.ts +18 -0
  16. package/dist/esbuild-cli-artifact.generated.d.ts.map +1 -0
  17. package/dist/esbuild-cli-artifact.generated.js +17 -0
  18. package/dist/facets/cirrus-real.d.ts.map +1 -1
  19. package/dist/facets/cirrus-real.js +9 -4
  20. package/dist/facets/compose.d.ts +11 -7
  21. package/dist/facets/compose.d.ts.map +1 -1
  22. package/dist/facets/compose.js +8 -38
  23. package/dist/facets/data-plan.d.ts +79 -0
  24. package/dist/facets/data-plan.d.ts.map +1 -0
  25. package/dist/facets/data-plan.js +477 -0
  26. package/dist/facets/esbuild-transform.d.ts +36 -10
  27. package/dist/facets/esbuild-transform.d.ts.map +1 -1
  28. package/dist/facets/esbuild-transform.js +216 -20
  29. package/dist/facets/exec-telemetry.d.ts +7 -3
  30. package/dist/facets/exec-telemetry.d.ts.map +1 -1
  31. package/dist/facets/manager.d.ts +179 -78
  32. package/dist/facets/manager.d.ts.map +1 -1
  33. package/dist/facets/manager.js +1221 -649
  34. package/dist/facets/opencode-staging.d.ts +0 -2
  35. package/dist/facets/opencode-staging.d.ts.map +1 -1
  36. package/dist/facets/opencode-staging.js +5 -11
  37. package/dist/facets/process.d.ts +4 -0
  38. package/dist/facets/process.d.ts.map +1 -1
  39. package/dist/facets/process.js +3 -0
  40. package/dist/facets/read-profile.d.ts +149 -0
  41. package/dist/facets/read-profile.d.ts.map +1 -0
  42. package/dist/facets/read-profile.js +483 -0
  43. package/dist/facets/resident-identity.d.ts +0 -1
  44. package/dist/facets/resident-identity.d.ts.map +1 -1
  45. package/dist/facets/resident-identity.js +0 -3
  46. package/dist/facets/wasm-swap-registry.d.ts +34 -25
  47. package/dist/facets/wasm-swap-registry.d.ts.map +1 -1
  48. package/dist/facets/wasm-swap-registry.js +62 -56
  49. package/dist/facets/ws-terminal.d.ts +4 -4
  50. package/dist/facets/ws-terminal.d.ts.map +1 -1
  51. package/dist/facets/ws-terminal.js +4 -5
  52. package/dist/git/commands.d.ts +16 -9
  53. package/dist/git/commands.d.ts.map +1 -1
  54. package/dist/git/commands.js +1818 -188
  55. package/dist/git/network-facet.d.ts +10 -2
  56. package/dist/git/network-facet.d.ts.map +1 -1
  57. package/dist/git/network-facet.js +62 -16
  58. package/dist/git/unified-diff.d.ts +74 -0
  59. package/dist/git/unified-diff.d.ts.map +1 -0
  60. package/dist/git/unified-diff.js +676 -0
  61. package/dist/git-bundle.generated.d.ts +7 -11
  62. package/dist/git-bundle.generated.d.ts.map +1 -1
  63. package/dist/git-bundle.generated.js +7 -11
  64. package/dist/hosted/commands.d.ts.map +1 -1
  65. package/dist/hosted/commands.js +62 -243
  66. package/dist/hosted/runtime.d.ts +19 -13
  67. package/dist/hosted/runtime.d.ts.map +1 -1
  68. package/dist/hosted/runtime.js +71 -14
  69. package/dist/hosted/services.d.ts +6 -7
  70. package/dist/hosted/services.d.ts.map +1 -1
  71. package/dist/hosted/services.js +10 -14
  72. package/dist/hosted/session.d.ts +165 -0
  73. package/dist/hosted/session.d.ts.map +1 -0
  74. package/dist/hosted/session.js +132 -0
  75. package/dist/loaders/generated-workers.d.ts +5 -2
  76. package/dist/loaders/generated-workers.d.ts.map +1 -1
  77. package/dist/loaders/generated-workers.js +6 -3
  78. package/dist/loaders/npm-resolve-preamble.d.ts.map +1 -1
  79. package/dist/loaders/npm-resolve-preamble.js +0 -27
  80. package/dist/node-shims-artifact.generated.d.ts +13 -4
  81. package/dist/node-shims-artifact.generated.d.ts.map +1 -1
  82. package/dist/node-shims-artifact.generated.js +16 -7
  83. package/dist/npm/bin-links.d.ts +3 -1
  84. package/dist/npm/bin-links.d.ts.map +1 -1
  85. package/dist/npm/bin-links.js +32 -8
  86. package/dist/npm/cache.d.ts +5 -0
  87. package/dist/npm/cache.d.ts.map +1 -1
  88. package/dist/npm/cache.js +13 -1
  89. package/dist/npm/install-batch-facet.d.ts +2 -2
  90. package/dist/npm/install-batch-facet.js +3 -3
  91. package/dist/npm/installer.d.ts +17 -1
  92. package/dist/npm/installer.d.ts.map +1 -1
  93. package/dist/npm/installer.js +159 -20
  94. package/dist/npm/package-lock.d.ts +32 -0
  95. package/dist/npm/package-lock.d.ts.map +1 -0
  96. package/dist/npm/package-lock.js +65 -0
  97. package/dist/npm/pre-bundle-facet.d.ts +1 -30
  98. package/dist/npm/pre-bundle-facet.d.ts.map +1 -1
  99. package/dist/npm/pre-bundle-facet.js +3 -5
  100. package/dist/npm/r2-cache.d.ts +2 -0
  101. package/dist/npm/r2-cache.d.ts.map +1 -1
  102. package/dist/npm/r2-cache.js +2 -0
  103. package/dist/npm/resolve-one-facet.d.ts.map +1 -1
  104. package/dist/npm/resolve-one-facet.js +14 -3
  105. package/dist/npm/resolver.d.ts +0 -7
  106. package/dist/npm/resolver.d.ts.map +1 -1
  107. package/dist/npm/resolver.js +0 -22
  108. package/dist/opencode-artifact.generated.js +2 -2
  109. package/dist/replica/routing.d.ts +2 -38
  110. package/dist/replica/routing.d.ts.map +1 -1
  111. package/dist/replica/routing.js +3 -55
  112. package/dist/router/index.d.ts.map +1 -1
  113. package/dist/router/index.js +15 -2
  114. package/dist/router/public-directory.d.ts +18 -0
  115. package/dist/router/public-directory.d.ts.map +1 -1
  116. package/dist/router/public-directory.js +1 -1
  117. package/dist/router/remote-api.d.ts +3 -1
  118. package/dist/router/remote-api.d.ts.map +1 -1
  119. package/dist/router/remote-api.js +42 -79
  120. package/dist/runtime/bash-repl.js +2 -2
  121. package/dist/runtime/bun-repl.d.ts.map +1 -1
  122. package/dist/runtime/bun-repl.js +2 -13
  123. package/dist/runtime/esbuild-wasm-bytes.d.ts +17 -5
  124. package/dist/runtime/esbuild-wasm-bytes.d.ts.map +1 -1
  125. package/dist/runtime/esbuild-wasm-bytes.js +43 -94
  126. package/dist/runtime/git-bundle-artifact.d.ts +17 -0
  127. package/dist/runtime/git-bundle-artifact.d.ts.map +1 -0
  128. package/dist/runtime/git-bundle-artifact.js +25 -0
  129. package/dist/runtime/node-repl.d.ts.map +1 -1
  130. package/dist/runtime/node-repl.js +2 -13
  131. package/dist/runtime/node-shims-artifact.d.ts +22 -23
  132. package/dist/runtime/node-shims-artifact.d.ts.map +1 -1
  133. package/dist/runtime/node-shims-artifact.js +48 -78
  134. package/dist/runtime/node-shims.d.ts.map +1 -1
  135. package/dist/runtime/node-shims.js +1567 -864
  136. package/dist/runtime/opencode-artifact.d.ts.map +1 -1
  137. package/dist/runtime/opencode-artifact.js +17 -53
  138. package/dist/runtime/opencode-facet-runner.d.ts +3 -6
  139. package/dist/runtime/opencode-facet-runner.d.ts.map +1 -1
  140. package/dist/runtime/opencode-facet-runner.js +45 -10
  141. package/dist/runtime/opentui-wasm-bytes.d.ts.map +1 -1
  142. package/dist/runtime/opentui-wasm-bytes.js +16 -49
  143. package/dist/runtime/package-manager.d.ts +0 -2
  144. package/dist/runtime/package-manager.d.ts.map +1 -1
  145. package/dist/runtime/package-manager.js +0 -3
  146. package/dist/runtime/python-repl.d.ts.map +1 -1
  147. package/dist/runtime/python-repl.js +2 -2
  148. package/dist/runtime/repl-session.d.ts +10 -0
  149. package/dist/runtime/repl-session.d.ts.map +1 -1
  150. package/dist/runtime/repl-session.js +7 -0
  151. package/dist/runtime/ruby-repl.d.ts.map +1 -1
  152. package/dist/runtime/ruby-repl.js +2 -2
  153. package/dist/runtime/ruby-resident.d.ts.map +1 -1
  154. package/dist/runtime/ruby-resident.js +36 -35
  155. package/dist/runtime/runtime-catalog.d.ts +10 -3
  156. package/dist/runtime/runtime-catalog.d.ts.map +1 -1
  157. package/dist/runtime/runtime-catalog.js +125 -15
  158. package/dist/runtime/sqlite-wasm-bytes.d.ts +4 -4
  159. package/dist/runtime/sqlite-wasm-bytes.d.ts.map +1 -1
  160. package/dist/runtime/sqlite-wasm-bytes.js +21 -57
  161. package/dist/runtime/staged-source.d.ts +67 -0
  162. package/dist/runtime/staged-source.d.ts.map +1 -0
  163. package/dist/runtime/staged-source.js +113 -0
  164. package/dist/runtime/wasi/preamble.d.ts.map +1 -1
  165. package/dist/runtime/wasi/preamble.js +0 -24
  166. package/dist/runtime-catalog.generated.js +1 -1
  167. package/dist/session/agent.d.ts +14 -2
  168. package/dist/session/agent.d.ts.map +1 -1
  169. package/dist/session/agent.js +57 -19
  170. package/dist/session/ai.d.ts +0 -11
  171. package/dist/session/ai.d.ts.map +1 -1
  172. package/dist/session/ai.js +0 -4
  173. package/dist/session/fs-watch.d.ts +0 -11
  174. package/dist/session/fs-watch.d.ts.map +1 -1
  175. package/dist/session/fs-watch.js +0 -21
  176. package/dist/session/hibernation.d.ts +34 -11
  177. package/dist/session/hibernation.d.ts.map +1 -1
  178. package/dist/session/hibernation.js +46 -29
  179. package/dist/session/init-phases.d.ts +1 -2
  180. package/dist/session/init-phases.d.ts.map +1 -1
  181. package/dist/session/init-phases.js +1 -2
  182. package/dist/session/init.d.ts.map +1 -1
  183. package/dist/session/init.js +7 -20
  184. package/dist/session/keys.d.ts +0 -3
  185. package/dist/session/keys.d.ts.map +1 -1
  186. package/dist/session/keys.js +0 -3
  187. package/dist/session/legacy-reset.d.ts +11 -0
  188. package/dist/session/legacy-reset.d.ts.map +1 -0
  189. package/dist/session/legacy-reset.js +16 -0
  190. package/dist/session/nimbus-session.d.ts +41 -15
  191. package/dist/session/nimbus-session.d.ts.map +1 -1
  192. package/dist/session/nimbus-session.js +64 -70
  193. package/dist/session/npm-install-port.d.ts.map +1 -1
  194. package/dist/session/npm-install-port.js +1 -0
  195. package/dist/session/programmatic.d.ts +13 -18
  196. package/dist/session/programmatic.d.ts.map +1 -1
  197. package/dist/session/programmatic.js +53 -39
  198. package/dist/session/replica-routes.d.ts +2 -3
  199. package/dist/session/replica-routes.d.ts.map +1 -1
  200. package/dist/session/replica-routes.js +3 -10
  201. package/dist/session/routes.d.ts.map +1 -1
  202. package/dist/session/routes.js +7 -10
  203. package/dist/session/rpc.d.ts +104 -20
  204. package/dist/session/rpc.d.ts.map +1 -1
  205. package/dist/session/rpc.js +184 -37
  206. package/dist/session/start-real-vite.js +2 -2
  207. package/dist/session/state-store.d.ts +1 -17
  208. package/dist/session/state-store.d.ts.map +1 -1
  209. package/dist/session/state-store.js +3 -53
  210. package/dist/session/supervisor-op.d.ts +7 -0
  211. package/dist/session/supervisor-op.d.ts.map +1 -1
  212. package/dist/session/supervisor-op.js +6 -1
  213. package/dist/session/supervisor-rpc.d.ts +104 -15
  214. package/dist/session/supervisor-rpc.d.ts.map +1 -1
  215. package/dist/session/supervisor-rpc.js +188 -71
  216. package/dist/session/vite-command.d.ts.map +1 -1
  217. package/dist/session/vite-command.js +17 -14
  218. package/dist/session/ws.d.ts.map +1 -1
  219. package/dist/session/ws.js +20 -8
  220. package/dist/shell/npm-bin-entrypoints.d.ts.map +1 -1
  221. package/dist/shell/npm-bin-entrypoints.js +30 -5
  222. package/dist/vfs/facet-resident-limits.d.ts +33 -0
  223. package/dist/vfs/facet-resident-limits.d.ts.map +1 -0
  224. package/dist/vfs/facet-resident-limits.js +33 -0
  225. package/dist/vfs/facet-resident-store.d.ts +2 -10
  226. package/dist/vfs/facet-resident-store.d.ts.map +1 -1
  227. package/dist/vfs/facet-resident-store.js +1594 -219
  228. package/dist/workspace-host.d.ts +2 -0
  229. package/dist/workspace-host.d.ts.map +1 -1
  230. package/dist/workspace-host.js +2 -0
  231. package/dist/wrangler/nimbus-wrangler.d.ts +0 -2
  232. package/dist/wrangler/nimbus-wrangler.d.ts.map +1 -1
  233. package/dist/wrangler/nimbus-wrangler.js +5 -22
  234. package/package.json +8 -7
  235. package/public/_assets/opencode/1.16.2/index-attach.js +2 -2
  236. package/public/_assets/runtime/esbuild-cli-c4fda380d52befc1.js +6892 -0
  237. package/public/_assets/runtime/git-de3e60c9f3ff006a.js +103 -0
  238. package/public/_assets/runtime/{node-shims-7b4dd7a76d95d21e.js → node-shims-06565b121555c194.js} +2089 -861
  239. package/public/_assets/runtime/resident-store-6ffb1939c53d982f.js +2264 -0
  240. package/public/_assets/runtime/vfs-write-ledger-e501e8fc793bc2c1.js +889 -0
  241. package/scripts/build-opencode-attach-entry.mjs +51 -1
  242. package/scripts/bundle-facet-workers.mjs +114 -3
  243. package/scripts/bundle-git.mjs +88 -27
  244. package/scripts/bundle-node-shims.mjs +72 -46
  245. package/scripts/bundle-runtime.mjs +18 -421
  246. package/scripts/cf-git-patch.mjs +137 -0
  247. package/scripts/patch-install-deps.mjs +49 -96
  248. package/scripts/runtime-specs.mjs +435 -0
  249. package/vendor/git-http.generated.d.ts +82 -0
  250. package/vendor/git-upstream.generated.d.ts +4378 -0
  251. package/vendor/git.LICENSE +7 -0
  252. package/vendor/git.generated.d.mts +21 -0
  253. package/vendor/git.generated.mjs +103 -0
  254. package/dist/replica/suspension.d.ts +0 -36
  255. package/dist/replica/suspension.d.ts.map +0 -1
  256. package/dist/replica/suspension.js +0 -49
  257. package/dist/runtime/static-server.d.ts +0 -3
  258. package/dist/runtime/static-server.d.ts.map +0 -1
  259. package/dist/runtime/static-server.js +0 -133
  260. package/scripts/clean-dist.mjs +0 -7
@@ -1,14 +1,10 @@
1
1
  /**
2
- * git-bundle.generated.ts — AUTO-GENERATED. DO NOT EDIT.
2
+ * git-bundle.generated.ts — AUTO-GENERATED by scripts/bundle-git.mjs. DO NOT EDIT.
3
3
  *
4
- * Produced by scripts/bundle-git.mjs from:
5
- * - isomorphic-git (github:AshishKumar4/cf-git)
6
- * - isomorphic-git/http/web
7
- *
8
- * Consumed by git-network-facet.ts: passed to LOADER.load()'s
9
- * `modules` record so the facet can `import` isomorphic-git.
10
- *
11
- * Size: 482.3 KiB
4
+ * Pins the staged copy of vendor/git.generated.mjs (isomorphic-git from
5
+ * github:AshishKumar4/cf-git + isomorphic-git/http/web) that the git network
6
+ * facet imports as `git-bundle.js`. GIT_BUNDLE_SHA256 is verified at fetch time.
12
7
  */
13
- export const GIT_BUNDLE_CODE = "var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\n\n// ../../node_modules/.bun/crc-32@1.2.2/node_modules/crc-32/crc32.js\nvar require_crc32 = __commonJS({\n \"../../node_modules/.bun/crc-32@1.2.2/node_modules/crc-32/crc32.js\"(exports) {\n var CRC32;\n (function(factory) {\n if (typeof DO_NOT_EXPORT_CRC === \"undefined\") {\n if (\"object\" === typeof exports) {\n factory(exports);\n } else if (\"function\" === typeof define && define.amd) {\n define(function() {\n var module2 = {};\n factory(module2);\n return module2;\n });\n } else {\n factory(CRC32 = {});\n }\n } else {\n factory(CRC32 = {});\n }\n })(function(CRC322) {\n CRC322.version = \"1.2.2\";\n function signed_crc_table() {\n var c = 0, table = new Array(256);\n for (var n = 0; n != 256; ++n) {\n c = n;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;\n table[n] = c;\n }\n return typeof Int32Array !== \"undefined\" ? new Int32Array(table) : table;\n }\n var T0 = signed_crc_table();\n function slice_by_16_tables(T) {\n var c = 0, v = 0, n = 0, table = typeof Int32Array !== \"undefined\" ? new Int32Array(4096) : new Array(4096);\n for (n = 0; n != 256; ++n) table[n] = T[n];\n for (n = 0; n != 256; ++n) {\n v = T[n];\n for (c = 256 + n; c < 4096; c += 256) v = table[c] = v >>> 8 ^ T[v & 255];\n }\n var out = [];\n for (n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== \"undefined\" ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);\n return out;\n }\n var TT = slice_by_16_tables(T0);\n var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];\n var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];\n var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];\n function crc32_bstr(bstr, seed) {\n var C = seed ^ -1;\n for (var i = 0, L = bstr.length; i < L; ) C = C >>> 8 ^ T0[(C ^ bstr.charCodeAt(i++)) & 255];\n return ~C;\n }\n function crc32_buf(B, seed) {\n var C = seed ^ -1, L = B.length - 15, i = 0;\n for (; i < L; ) C = Tf[B[i++] ^ C & 255] ^ Te[B[i++] ^ C >> 8 & 255] ^ Td[B[i++] ^ C >> 16 & 255] ^ Tc[B[i++] ^ C >>> 24] ^ Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];\n L += 15;\n while (i < L) C = C >>> 8 ^ T0[(C ^ B[i++]) & 255];\n return ~C;\n }\n function crc32_str(str, seed) {\n var C = seed ^ -1;\n for (var i = 0, L = str.length, c = 0, d = 0; i < L; ) {\n c = str.charCodeAt(i++);\n if (c < 128) {\n C = C >>> 8 ^ T0[(C ^ c) & 255];\n } else if (c < 2048) {\n C = C >>> 8 ^ T0[(C ^ (192 | c >> 6 & 31)) & 255];\n C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];\n } else if (c >= 55296 && c < 57344) {\n c = (c & 1023) + 64;\n d = str.charCodeAt(i++) & 1023;\n C = C >>> 8 ^ T0[(C ^ (240 | c >> 8 & 7)) & 255];\n C = C >>> 8 ^ T0[(C ^ (128 | c >> 2 & 63)) & 255];\n C = C >>> 8 ^ T0[(C ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255];\n C = C >>> 8 ^ T0[(C ^ (128 | d & 63)) & 255];\n } else {\n C = C >>> 8 ^ T0[(C ^ (224 | c >> 12 & 15)) & 255];\n C = C >>> 8 ^ T0[(C ^ (128 | c >> 6 & 63)) & 255];\n C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];\n }\n }\n return ~C;\n }\n CRC322.table = T0;\n CRC322.bstr = crc32_bstr;\n CRC322.buf = crc32_buf;\n CRC322.str = crc32_str;\n });\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/common.js\nvar require_common = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/common.js\"(exports) {\n \"use strict\";\n var TYPED_OK = typeof Uint8Array !== \"undefined\" && typeof Uint16Array !== \"undefined\" && typeof Int32Array !== \"undefined\";\n function _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n }\n exports.assign = function(obj) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) {\n continue;\n }\n if (typeof source !== \"object\") {\n throw new TypeError(source + \"must be non-object\");\n }\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n return obj;\n };\n exports.shrinkBuf = function(buf, size) {\n if (buf.length === size) {\n return buf;\n }\n if (buf.subarray) {\n return buf.subarray(0, size);\n }\n buf.length = size;\n return buf;\n };\n var fnTyped = {\n arraySet: function(dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function(chunks) {\n var i, l, len, pos, chunk, result;\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n return result;\n }\n };\n var fnUntyped = {\n arraySet: function(dest, src, src_offs, len, dest_offs) {\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function(chunks) {\n return [].concat.apply([], chunks);\n }\n };\n exports.setTyped = function(on) {\n if (on) {\n exports.Buf8 = Uint8Array;\n exports.Buf16 = Uint16Array;\n exports.Buf32 = Int32Array;\n exports.assign(exports, fnTyped);\n } else {\n exports.Buf8 = Array;\n exports.Buf16 = Array;\n exports.Buf32 = Array;\n exports.assign(exports, fnUntyped);\n }\n };\n exports.setTyped(TYPED_OK);\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/trees.js\nvar require_trees = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/trees.js\"(exports) {\n \"use strict\";\n var utils = require_common();\n var Z_FIXED = 4;\n var Z_BINARY = 0;\n var Z_TEXT = 1;\n var Z_UNKNOWN = 2;\n function zero(buf) {\n var len = buf.length;\n while (--len >= 0) {\n buf[len] = 0;\n }\n }\n var STORED_BLOCK = 0;\n var STATIC_TREES = 1;\n var DYN_TREES = 2;\n var MIN_MATCH = 3;\n var MAX_MATCH = 258;\n var LENGTH_CODES = 29;\n var LITERALS = 256;\n var L_CODES = LITERALS + 1 + LENGTH_CODES;\n var D_CODES = 30;\n var BL_CODES = 19;\n var HEAP_SIZE = 2 * L_CODES + 1;\n var MAX_BITS = 15;\n var Buf_size = 16;\n var MAX_BL_BITS = 7;\n var END_BLOCK = 256;\n var REP_3_6 = 16;\n var REPZ_3_10 = 17;\n var REPZ_11_138 = 18;\n var extra_lbits = (\n /* extra bits for each length code */\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]\n );\n var extra_dbits = (\n /* extra bits for each distance code */\n [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]\n );\n var extra_blbits = (\n /* extra bits for each bit length code */\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]\n );\n var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];\n var DIST_CODE_LEN = 512;\n var static_ltree = new Array((L_CODES + 2) * 2);\n zero(static_ltree);\n var static_dtree = new Array(D_CODES * 2);\n zero(static_dtree);\n var _dist_code = new Array(DIST_CODE_LEN);\n zero(_dist_code);\n var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\n zero(_length_code);\n var base_length = new Array(LENGTH_CODES);\n zero(base_length);\n var base_dist = new Array(D_CODES);\n zero(base_dist);\n function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n this.static_tree = static_tree;\n this.extra_bits = extra_bits;\n this.extra_base = extra_base;\n this.elems = elems;\n this.max_length = max_length;\n this.has_stree = static_tree && static_tree.length;\n }\n var static_l_desc;\n var static_d_desc;\n var static_bl_desc;\n function TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree;\n this.max_code = 0;\n this.stat_desc = stat_desc;\n }\n function d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n }\n function put_short(s, w) {\n s.pending_buf[s.pending++] = w & 255;\n s.pending_buf[s.pending++] = w >>> 8 & 255;\n }\n function send_bits(s, value, length) {\n if (s.bi_valid > Buf_size - length) {\n s.bi_buf |= value << s.bi_valid & 65535;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> Buf_size - s.bi_valid;\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= value << s.bi_valid & 65535;\n s.bi_valid += length;\n }\n }\n function send_code(s, c, tree) {\n send_bits(\n s,\n tree[c * 2],\n tree[c * 2 + 1]\n /*.Len*/\n );\n }\n function bi_reverse(code, len) {\n var res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n }\n function bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 255;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n }\n function gen_bitlen(s, desc) {\n var tree = desc.dyn_tree;\n var max_code = desc.max_code;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var extra = desc.stat_desc.extra_bits;\n var base = desc.stat_desc.extra_base;\n var max_length = desc.stat_desc.max_length;\n var h;\n var n, m;\n var bits;\n var xbits;\n var f;\n var overflow = 0;\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n tree[s.heap[s.heap_max] * 2 + 1] = 0;\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1] = bits;\n if (n > max_code) {\n continue;\n }\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2];\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1] + xbits);\n }\n }\n if (overflow === 0) {\n return;\n }\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) {\n bits--;\n }\n s.bl_count[bits]--;\n s.bl_count[bits + 1] += 2;\n s.bl_count[max_length]--;\n overflow -= 2;\n } while (overflow > 0);\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) {\n continue;\n }\n if (tree[m * 2 + 1] !== bits) {\n s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];\n tree[m * 2 + 1] = bits;\n }\n n--;\n }\n }\n }\n function gen_codes(tree, max_code, bl_count) {\n var next_code = new Array(MAX_BITS + 1);\n var code = 0;\n var bits;\n var n;\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n for (n = 0; n <= max_code; n++) {\n var len = tree[n * 2 + 1];\n if (len === 0) {\n continue;\n }\n tree[n * 2] = bi_reverse(next_code[len]++, len);\n }\n }\n function tr_static_init() {\n var n;\n var bits;\n var length;\n var code;\n var dist;\n var bl_count = new Array(MAX_BITS + 1);\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < 1 << extra_lbits[code]; n++) {\n _length_code[length++] = code;\n }\n }\n _length_code[length - 1] = code;\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < 1 << extra_dbits[code]; n++) {\n _dist_code[dist++] = code;\n }\n }\n dist >>= 7;\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1] = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1] = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1] = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1] = 8;\n n++;\n bl_count[8]++;\n }\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1] = 5;\n static_dtree[n * 2] = bi_reverse(n, 5);\n }\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n }\n function init_block(s) {\n var n;\n for (n = 0; n < L_CODES; n++) {\n s.dyn_ltree[n * 2] = 0;\n }\n for (n = 0; n < D_CODES; n++) {\n s.dyn_dtree[n * 2] = 0;\n }\n for (n = 0; n < BL_CODES; n++) {\n s.bl_tree[n * 2] = 0;\n }\n s.dyn_ltree[END_BLOCK * 2] = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n }\n function bi_windup(s) {\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n }\n function copy_block(s, buf, len, header) {\n bi_windup(s);\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n }\n function smaller(tree, n, m, depth) {\n var _n2 = n * 2;\n var _m2 = m * 2;\n return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m];\n }\n function pqdownheap(s, tree, k) {\n var v = s.heap[k];\n var j = k << 1;\n while (j <= s.heap_len) {\n if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n if (smaller(tree, v, s.heap[j], s.depth)) {\n break;\n }\n s.heap[k] = s.heap[j];\n k = j;\n j <<= 1;\n }\n s.heap[k] = v;\n }\n function compress_block(s, ltree, dtree) {\n var dist;\n var lc;\n var lx = 0;\n var code;\n var extra;\n if (s.last_lit !== 0) {\n do {\n dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n if (dist === 0) {\n send_code(s, lc, ltree);\n } else {\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree);\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra);\n }\n dist--;\n code = d_code(dist);\n send_code(s, code, dtree);\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra);\n }\n }\n } while (lx < s.last_lit);\n }\n send_code(s, END_BLOCK, ltree);\n }\n function build_tree(s, desc) {\n var tree = desc.dyn_tree;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var elems = desc.stat_desc.elems;\n var n, m;\n var max_code = -1;\n var node;\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n for (n = 0; n < elems; n++) {\n if (tree[n * 2] !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n } else {\n tree[n * 2 + 1] = 0;\n }\n }\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;\n tree[node * 2] = 1;\n s.depth[node] = 0;\n s.opt_len--;\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1];\n }\n }\n desc.max_code = max_code;\n for (n = s.heap_len >> 1; n >= 1; n--) {\n pqdownheap(s, tree, n);\n }\n node = elems;\n do {\n n = s.heap[\n 1\n /*SMALLEST*/\n ];\n s.heap[\n 1\n /*SMALLEST*/\n ] = s.heap[s.heap_len--];\n pqdownheap(\n s,\n tree,\n 1\n /*SMALLEST*/\n );\n m = s.heap[\n 1\n /*SMALLEST*/\n ];\n s.heap[--s.heap_max] = n;\n s.heap[--s.heap_max] = m;\n tree[node * 2] = tree[n * 2] + tree[m * 2];\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1] = tree[m * 2 + 1] = node;\n s.heap[\n 1\n /*SMALLEST*/\n ] = node++;\n pqdownheap(\n s,\n tree,\n 1\n /*SMALLEST*/\n );\n } while (s.heap_len >= 2);\n s.heap[--s.heap_max] = s.heap[\n 1\n /*SMALLEST*/\n ];\n gen_bitlen(s, desc);\n gen_codes(tree, max_code, s.bl_count);\n }\n function scan_tree(s, tree, max_code) {\n var n;\n var prevlen = -1;\n var curlen;\n var nextlen = tree[0 * 2 + 1];\n var count = 0;\n var max_count = 7;\n var min_count = 4;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1] = 65535;\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1];\n if (++count < max_count && curlen === nextlen) {\n continue;\n } else if (count < min_count) {\n s.bl_tree[curlen * 2] += count;\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n s.bl_tree[curlen * 2]++;\n }\n s.bl_tree[REP_3_6 * 2]++;\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]++;\n } else {\n s.bl_tree[REPZ_11_138 * 2]++;\n }\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n }\n function send_tree(s, tree, max_code) {\n var n;\n var prevlen = -1;\n var curlen;\n var nextlen = tree[0 * 2 + 1];\n var count = 0;\n var max_count = 7;\n var min_count = 4;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1];\n if (++count < max_count && curlen === nextlen) {\n continue;\n } else if (count < min_count) {\n do {\n send_code(s, curlen, s.bl_tree);\n } while (--count !== 0);\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n }\n function build_bl_tree(s) {\n var max_blindex;\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n build_tree(s, s.bl_desc);\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) {\n break;\n }\n }\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n return max_blindex;\n }\n function send_all_trees(s, lcodes, dcodes, blcodes) {\n var rank;\n send_bits(s, lcodes - 257, 5);\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4);\n for (rank = 0; rank < blcodes; rank++) {\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3);\n }\n send_tree(s, s.dyn_ltree, lcodes - 1);\n send_tree(s, s.dyn_dtree, dcodes - 1);\n }\n function detect_data_type(s) {\n var black_mask = 4093624447;\n var n;\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) {\n return Z_BINARY;\n }\n }\n if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2] !== 0) {\n return Z_TEXT;\n }\n }\n return Z_BINARY;\n }\n var static_init_done = false;\n function _tr_init(s) {\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n s.bi_buf = 0;\n s.bi_valid = 0;\n init_block(s);\n }\n function _tr_stored_block(s, buf, stored_len, last) {\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);\n copy_block(s, buf, stored_len, true);\n }\n function _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n }\n function _tr_flush_block(s, buf, stored_len, last) {\n var opt_lenb, static_lenb;\n var max_blindex = 0;\n if (s.level > 0) {\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n build_tree(s, s.l_desc);\n build_tree(s, s.d_desc);\n max_blindex = build_bl_tree(s);\n opt_lenb = s.opt_len + 3 + 7 >>> 3;\n static_lenb = s.static_len + 3 + 7 >>> 3;\n if (static_lenb <= opt_lenb) {\n opt_lenb = static_lenb;\n }\n } else {\n opt_lenb = static_lenb = stored_len + 5;\n }\n if (stored_len + 4 <= opt_lenb && buf !== -1) {\n _tr_stored_block(s, buf, stored_len, last);\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n init_block(s);\n if (last) {\n bi_windup(s);\n }\n }\n function _tr_tally(s, dist, lc) {\n s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255;\n s.pending_buf[s.l_buf + s.last_lit] = lc & 255;\n s.last_lit++;\n if (dist === 0) {\n s.dyn_ltree[lc * 2]++;\n } else {\n s.matches++;\n dist--;\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++;\n s.dyn_dtree[d_code(dist) * 2]++;\n }\n return s.last_lit === s.lit_bufsize - 1;\n }\n exports._tr_init = _tr_init;\n exports._tr_stored_block = _tr_stored_block;\n exports._tr_flush_block = _tr_flush_block;\n exports._tr_tally = _tr_tally;\n exports._tr_align = _tr_align;\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js\nvar require_adler32 = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js\"(exports, module) {\n \"use strict\";\n function adler32(adler, buf, len, pos) {\n var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0;\n while (len !== 0) {\n n = len > 2e3 ? 2e3 : len;\n len -= n;\n do {\n s1 = s1 + buf[pos++] | 0;\n s2 = s2 + s1 | 0;\n } while (--n);\n s1 %= 65521;\n s2 %= 65521;\n }\n return s1 | s2 << 16 | 0;\n }\n module.exports = adler32;\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js\nvar require_crc322 = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js\"(exports, module) {\n \"use strict\";\n function makeTable() {\n var c, table = [];\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;\n }\n table[n] = c;\n }\n return table;\n }\n var crcTable = makeTable();\n function crc322(crc, buf, len, pos) {\n var t = crcTable, end = pos + len;\n crc ^= -1;\n for (var i = pos; i < end; i++) {\n crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255];\n }\n return crc ^ -1;\n }\n module.exports = crc322;\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/messages.js\nvar require_messages = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/messages.js\"(exports, module) {\n \"use strict\";\n module.exports = {\n 2: \"need dictionary\",\n /* Z_NEED_DICT 2 */\n 1: \"stream end\",\n /* Z_STREAM_END 1 */\n 0: \"\",\n /* Z_OK 0 */\n \"-1\": \"file error\",\n /* Z_ERRNO (-1) */\n \"-2\": \"stream error\",\n /* Z_STREAM_ERROR (-2) */\n \"-3\": \"data error\",\n /* Z_DATA_ERROR (-3) */\n \"-4\": \"insufficient memory\",\n /* Z_MEM_ERROR (-4) */\n \"-5\": \"buffer error\",\n /* Z_BUF_ERROR (-5) */\n \"-6\": \"incompatible version\"\n /* Z_VERSION_ERROR (-6) */\n };\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js\nvar require_deflate = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js\"(exports) {\n \"use strict\";\n var utils = require_common();\n var trees = require_trees();\n var adler32 = require_adler32();\n var crc322 = require_crc322();\n var msg = require_messages();\n var Z_NO_FLUSH = 0;\n var Z_PARTIAL_FLUSH = 1;\n var Z_FULL_FLUSH = 3;\n var Z_FINISH = 4;\n var Z_BLOCK = 5;\n var Z_OK = 0;\n var Z_STREAM_END = 1;\n var Z_STREAM_ERROR = -2;\n var Z_DATA_ERROR = -3;\n var Z_BUF_ERROR = -5;\n var Z_DEFAULT_COMPRESSION = -1;\n var Z_FILTERED = 1;\n var Z_HUFFMAN_ONLY = 2;\n var Z_RLE = 3;\n var Z_FIXED = 4;\n var Z_DEFAULT_STRATEGY = 0;\n var Z_UNKNOWN = 2;\n var Z_DEFLATED = 8;\n var MAX_MEM_LEVEL = 9;\n var MAX_WBITS = 15;\n var DEF_MEM_LEVEL = 8;\n var LENGTH_CODES = 29;\n var LITERALS = 256;\n var L_CODES = LITERALS + 1 + LENGTH_CODES;\n var D_CODES = 30;\n var BL_CODES = 19;\n var HEAP_SIZE = 2 * L_CODES + 1;\n var MAX_BITS = 15;\n var MIN_MATCH = 3;\n var MAX_MATCH = 258;\n var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;\n var PRESET_DICT = 32;\n var INIT_STATE = 42;\n var EXTRA_STATE = 69;\n var NAME_STATE = 73;\n var COMMENT_STATE = 91;\n var HCRC_STATE = 103;\n var BUSY_STATE = 113;\n var FINISH_STATE = 666;\n var BS_NEED_MORE = 1;\n var BS_BLOCK_DONE = 2;\n var BS_FINISH_STARTED = 3;\n var BS_FINISH_DONE = 4;\n var OS_CODE = 3;\n function err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n }\n function rank(f) {\n return (f << 1) - (f > 4 ? 9 : 0);\n }\n function zero(buf) {\n var len = buf.length;\n while (--len >= 0) {\n buf[len] = 0;\n }\n }\n function flush_pending(strm) {\n var s = strm.state;\n var len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) {\n return;\n }\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n }\n function flush_block_only(s, last) {\n trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n }\n function put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n }\n function putShortMSB(s, b) {\n s.pending_buf[s.pending++] = b >>> 8 & 255;\n s.pending_buf[s.pending++] = b & 255;\n }\n function read_buf(strm, buf, start, size) {\n var len = strm.avail_in;\n if (len > size) {\n len = size;\n }\n if (len === 0) {\n return 0;\n }\n strm.avail_in -= len;\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n } else if (strm.state.wrap === 2) {\n strm.adler = crc322(strm.adler, buf, len, start);\n }\n strm.next_in += len;\n strm.total_in += len;\n return len;\n }\n function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length;\n var scan = s.strstart;\n var match;\n var len;\n var best_len = s.prev_length;\n var nice_match = s.nice_match;\n var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0;\n var _win = s.window;\n var wmask = s.w_mask;\n var prev = s.prev;\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n if (nice_match > s.lookahead) {\n nice_match = s.lookahead;\n }\n do {\n match = cur_match;\n if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) {\n continue;\n }\n scan += 2;\n match++;\n do {\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend);\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n }\n function fill_window(s) {\n var _w_size = s.w_size;\n var p, n, m, more, str;\n do {\n more = s.window_size - s.lookahead - s.strstart;\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n s.block_start -= _w_size;\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = m >= _w_size ? m - _w_size : 0;\n } while (--n);\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = m >= _w_size ? m - _w_size : 0;\n } while (--n);\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask;\n while (s.insert) {\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n }\n function deflate_stored(s, flush) {\n var max_block_size = 65535;\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n for (; ; ) {\n if (s.lookahead <= 1) {\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break;\n }\n }\n s.strstart += s.lookahead;\n s.lookahead = 0;\n var max_start = s.block_start + max_block_size;\n if (s.strstart === 0 || s.strstart >= max_start) {\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n return BS_FINISH_DONE;\n }\n if (s.strstart > s.block_start) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n return BS_NEED_MORE;\n }\n function deflate_fast(s, flush) {\n var hash_head;\n var bflush;\n for (; ; ) {\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break;\n }\n }\n hash_head = 0;\n if (s.lookahead >= MIN_MATCH) {\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n }\n if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) {\n s.match_length = longest_match(s, hash_head);\n }\n if (s.match_length >= MIN_MATCH) {\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n s.lookahead -= s.match_length;\n if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) {\n s.match_length--;\n do {\n s.strstart++;\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n } while (--s.match_length !== 0);\n s.strstart++;\n } else {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask;\n }\n } else {\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n return BS_BLOCK_DONE;\n }\n function deflate_slow(s, flush) {\n var hash_head;\n var bflush;\n var max_insert;\n for (; ; ) {\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break;\n }\n }\n hash_head = 0;\n if (s.lookahead >= MIN_MATCH) {\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n }\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) {\n s.match_length = longest_match(s, hash_head);\n if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) {\n s.match_length = MIN_MATCH - 1;\n }\n }\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n if (bflush) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n } else if (s.match_available) {\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n if (bflush) {\n flush_block_only(s, false);\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n if (s.match_available) {\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n return BS_BLOCK_DONE;\n }\n function deflate_rle(s, flush) {\n var bflush;\n var prev;\n var scan, strend;\n var _win = s.window;\n for (; ; ) {\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break;\n }\n }\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n }\n if (s.match_length >= MIN_MATCH) {\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n return BS_BLOCK_DONE;\n }\n function deflate_huff(s, flush) {\n var bflush;\n for (; ; ) {\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break;\n }\n }\n s.match_length = 0;\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n }\n return BS_BLOCK_DONE;\n }\n function Config(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n }\n var configuration_table;\n configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored),\n /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast),\n /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast),\n /* 2 */\n new Config(4, 6, 32, 32, deflate_fast),\n /* 3 */\n new Config(4, 4, 16, 16, deflate_slow),\n /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow),\n /* 5 */\n new Config(8, 16, 128, 128, deflate_slow),\n /* 6 */\n new Config(8, 32, 128, 256, deflate_slow),\n /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow),\n /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow)\n /* 9 max compression */\n ];\n function lm_init(s) {\n s.window_size = 2 * s.w_size;\n zero(s.head);\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n }\n function DeflateState() {\n this.strm = null;\n this.status = 0;\n this.pending_buf = null;\n this.pending_buf_size = 0;\n this.pending_out = 0;\n this.pending = 0;\n this.wrap = 0;\n this.gzhead = null;\n this.gzindex = 0;\n this.method = Z_DEFLATED;\n this.last_flush = -1;\n this.w_size = 0;\n this.w_bits = 0;\n this.w_mask = 0;\n this.window = null;\n this.window_size = 0;\n this.prev = null;\n this.head = null;\n this.ins_h = 0;\n this.hash_size = 0;\n this.hash_bits = 0;\n this.hash_mask = 0;\n this.hash_shift = 0;\n this.block_start = 0;\n this.match_length = 0;\n this.prev_match = 0;\n this.match_available = 0;\n this.strstart = 0;\n this.match_start = 0;\n this.lookahead = 0;\n this.prev_length = 0;\n this.max_chain_length = 0;\n this.max_lazy_match = 0;\n this.level = 0;\n this.strategy = 0;\n this.good_match = 0;\n this.nice_match = 0;\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n this.l_desc = null;\n this.d_desc = null;\n this.bl_desc = null;\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n this.heap = new utils.Buf16(2 * L_CODES + 1);\n zero(this.heap);\n this.heap_len = 0;\n this.heap_max = 0;\n this.depth = new utils.Buf16(2 * L_CODES + 1);\n zero(this.depth);\n this.l_buf = 0;\n this.lit_bufsize = 0;\n this.last_lit = 0;\n this.d_buf = 0;\n this.opt_len = 0;\n this.static_len = 0;\n this.matches = 0;\n this.insert = 0;\n this.bi_buf = 0;\n this.bi_valid = 0;\n }\n function deflateResetKeep(strm) {\n var s;\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n }\n s.status = s.wrap ? INIT_STATE : BUSY_STATE;\n strm.adler = s.wrap === 2 ? 0 : 1;\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n }\n function deflateReset(strm) {\n var ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n }\n function deflateSetHeader(strm, head) {\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n if (strm.state.wrap !== 2) {\n return Z_STREAM_ERROR;\n }\n strm.state.gzhead = head;\n return Z_OK;\n }\n function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) {\n return Z_STREAM_ERROR;\n }\n var wrap = 1;\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n } else if (windowBits > 15) {\n wrap = 2;\n windowBits -= 16;\n }\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n if (windowBits === 8) {\n windowBits = 9;\n }\n var s = new DeflateState();\n strm.state = s;\n s.strm = strm;\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n s.lit_bufsize = 1 << memLevel + 6;\n s.pending_buf_size = s.lit_bufsize * 4;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n s.d_buf = 1 * s.lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n return deflateReset(strm);\n }\n function deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n }\n function deflate2(strm, flush) {\n var old_flush, s;\n var beg, val;\n if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n s = strm.state;\n if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) {\n return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n s.strm = strm;\n old_flush = s.last_flush;\n s.last_flush = flush;\n if (s.status === INIT_STATE) {\n if (s.wrap === 2) {\n strm.adler = 0;\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) {\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n } else {\n put_byte(\n s,\n (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 255);\n put_byte(s, s.gzhead.time >> 8 & 255);\n put_byte(s, s.gzhead.time >> 16 & 255);\n put_byte(s, s.gzhead.time >> 24 & 255);\n put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);\n put_byte(s, s.gzhead.os & 255);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 255);\n put_byte(s, s.gzhead.extra.length >> 8 & 255);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc322(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n } else {\n var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8;\n var level_flags = -1;\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= level_flags << 6;\n if (s.strstart !== 0) {\n header |= PRESET_DICT;\n }\n header += 31 - header % 31;\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 65535);\n }\n strm.adler = 1;\n }\n }\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra) {\n beg = s.pending;\n while (s.gzindex < (s.gzhead.extra.length & 65535)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 255);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n } else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name) {\n beg = s.pending;\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 255;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n } else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment) {\n beg = s.pending;\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 255;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n } else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 255);\n put_byte(s, strm.adler >> 8 & 255);\n strm.adler = 0;\n s.status = BUSY_STATE;\n }\n } else {\n s.status = BUSY_STATE;\n }\n }\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n return Z_OK;\n }\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) {\n var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush);\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n }\n return Z_OK;\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n } else if (flush !== Z_BLOCK) {\n trees._tr_stored_block(s, 0, 0, false);\n if (flush === Z_FULL_FLUSH) {\n zero(s.head);\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n return Z_OK;\n }\n }\n }\n if (flush !== Z_FINISH) {\n return Z_OK;\n }\n if (s.wrap <= 0) {\n return Z_STREAM_END;\n }\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 255);\n put_byte(s, strm.adler >> 8 & 255);\n put_byte(s, strm.adler >> 16 & 255);\n put_byte(s, strm.adler >> 24 & 255);\n put_byte(s, strm.total_in & 255);\n put_byte(s, strm.total_in >> 8 & 255);\n put_byte(s, strm.total_in >> 16 & 255);\n put_byte(s, strm.total_in >> 24 & 255);\n } else {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 65535);\n }\n flush_pending(strm);\n if (s.wrap > 0) {\n s.wrap = -s.wrap;\n }\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n }\n function deflateEnd(strm) {\n var status2;\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n status2 = strm.state.status;\n if (status2 !== INIT_STATE && status2 !== EXTRA_STATE && status2 !== NAME_STATE && status2 !== COMMENT_STATE && status2 !== HCRC_STATE && status2 !== BUSY_STATE && status2 !== FINISH_STATE) {\n return err(strm, Z_STREAM_ERROR);\n }\n strm.state = null;\n return status2 === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n }\n function deflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n var s;\n var str, n;\n var wrap;\n var avail;\n var next;\n var input;\n var tmpDict;\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n s = strm.state;\n wrap = s.wrap;\n if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n if (wrap === 1) {\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n s.wrap = 0;\n if (dictLength >= s.w_size) {\n if (wrap === 0) {\n zero(s.head);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n }\n exports.deflateInit = deflateInit;\n exports.deflateInit2 = deflateInit2;\n exports.deflateReset = deflateReset;\n exports.deflateResetKeep = deflateResetKeep;\n exports.deflateSetHeader = deflateSetHeader;\n exports.deflate = deflate2;\n exports.deflateEnd = deflateEnd;\n exports.deflateSetDictionary = deflateSetDictionary;\n exports.deflateInfo = \"pako deflate (from Nodeca project)\";\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/strings.js\nvar require_strings = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/strings.js\"(exports) {\n \"use strict\";\n var utils = require_common();\n var STR_APPLY_OK = true;\n var STR_APPLY_UIA_OK = true;\n try {\n String.fromCharCode.apply(null, [0]);\n } catch (__) {\n STR_APPLY_OK = false;\n }\n try {\n String.fromCharCode.apply(null, new Uint8Array(1));\n } catch (__) {\n STR_APPLY_UIA_OK = false;\n }\n var _utf8len = new utils.Buf8(256);\n for (q = 0; q < 256; q++) {\n _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;\n }\n var q;\n _utf8len[254] = _utf8len[254] = 1;\n exports.string2buf = function(str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 64512) === 55296 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 64512) === 56320) {\n c = 65536 + (c - 55296 << 10) + (c2 - 56320);\n m_pos++;\n }\n }\n buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4;\n }\n buf = new utils.Buf8(buf_len);\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 64512) === 55296 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 64512) === 56320) {\n c = 65536 + (c - 55296 << 10) + (c2 - 56320);\n m_pos++;\n }\n }\n if (c < 128) {\n buf[i++] = c;\n } else if (c < 2048) {\n buf[i++] = 192 | c >>> 6;\n buf[i++] = 128 | c & 63;\n } else if (c < 65536) {\n buf[i++] = 224 | c >>> 12;\n buf[i++] = 128 | c >>> 6 & 63;\n buf[i++] = 128 | c & 63;\n } else {\n buf[i++] = 240 | c >>> 18;\n buf[i++] = 128 | c >>> 12 & 63;\n buf[i++] = 128 | c >>> 6 & 63;\n buf[i++] = 128 | c & 63;\n }\n }\n return buf;\n };\n function buf2binstring(buf, len) {\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n var result = \"\";\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n }\n exports.buf2binstring = function(buf) {\n return buf2binstring(buf, buf.length);\n };\n exports.binstring2buf = function(str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n };\n exports.buf2string = function(buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n var utf16buf = new Array(len * 2);\n for (out = 0, i = 0; i < len; ) {\n c = buf[i++];\n if (c < 128) {\n utf16buf[out++] = c;\n continue;\n }\n c_len = _utf8len[c];\n if (c_len > 4) {\n utf16buf[out++] = 65533;\n i += c_len - 1;\n continue;\n }\n c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;\n while (c_len > 1 && i < len) {\n c = c << 6 | buf[i++] & 63;\n c_len--;\n }\n if (c_len > 1) {\n utf16buf[out++] = 65533;\n continue;\n }\n if (c < 65536) {\n utf16buf[out++] = c;\n } else {\n c -= 65536;\n utf16buf[out++] = 55296 | c >> 10 & 1023;\n utf16buf[out++] = 56320 | c & 1023;\n }\n }\n return buf2binstring(utf16buf, out);\n };\n exports.utf8border = function(buf, max) {\n var pos;\n max = max || buf.length;\n if (max > buf.length) {\n max = buf.length;\n }\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 192) === 128) {\n pos--;\n }\n if (pos < 0) {\n return max;\n }\n if (pos === 0) {\n return max;\n }\n return pos + _utf8len[buf[pos]] > max ? pos : max;\n };\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js\nvar require_zstream = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js\"(exports, module) {\n \"use strict\";\n function ZStream() {\n this.input = null;\n this.next_in = 0;\n this.avail_in = 0;\n this.total_in = 0;\n this.output = null;\n this.next_out = 0;\n this.avail_out = 0;\n this.total_out = 0;\n this.msg = \"\";\n this.state = null;\n this.data_type = 2;\n this.adler = 0;\n }\n module.exports = ZStream;\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/deflate.js\nvar require_deflate2 = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/deflate.js\"(exports) {\n \"use strict\";\n var zlib_deflate = require_deflate();\n var utils = require_common();\n var strings = require_strings();\n var msg = require_messages();\n var ZStream = require_zstream();\n var toString = Object.prototype.toString;\n var Z_NO_FLUSH = 0;\n var Z_FINISH = 4;\n var Z_OK = 0;\n var Z_STREAM_END = 1;\n var Z_SYNC_FLUSH = 2;\n var Z_DEFAULT_COMPRESSION = -1;\n var Z_DEFAULT_STRATEGY = 0;\n var Z_DEFLATED = 8;\n function Deflate(options) {\n if (!(this instanceof Deflate)) return new Deflate(options);\n this.options = utils.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n to: \"\"\n }, options || {});\n var opt = this.options;\n if (opt.raw && opt.windowBits > 0) {\n opt.windowBits = -opt.windowBits;\n } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) {\n opt.windowBits += 16;\n }\n this.err = 0;\n this.msg = \"\";\n this.ended = false;\n this.chunks = [];\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n var status2 = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n if (status2 !== Z_OK) {\n throw new Error(msg[status2]);\n }\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n if (opt.dictionary) {\n var dict;\n if (typeof opt.dictionary === \"string\") {\n dict = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === \"[object ArrayBuffer]\") {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n status2 = zlib_deflate.deflateSetDictionary(this.strm, dict);\n if (status2 !== Z_OK) {\n throw new Error(msg[status2]);\n }\n this._dict_set = true;\n }\n }\n Deflate.prototype.push = function(data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var status2, _mode;\n if (this.ended) {\n return false;\n }\n _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH;\n if (typeof data === \"string\") {\n strm.input = strings.string2buf(data);\n } else if (toString.call(data) === \"[object ArrayBuffer]\") {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status2 = zlib_deflate.deflate(strm, _mode);\n if (status2 !== Z_STREAM_END && status2 !== Z_OK) {\n this.onEnd(status2);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) {\n if (this.options.to === \"string\") {\n this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status2 !== Z_STREAM_END);\n if (_mode === Z_FINISH) {\n status2 = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status2);\n this.ended = true;\n return status2 === Z_OK;\n }\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n return true;\n };\n Deflate.prototype.onData = function(chunk) {\n this.chunks.push(chunk);\n };\n Deflate.prototype.onEnd = function(status2) {\n if (status2 === Z_OK) {\n if (this.options.to === \"string\") {\n this.result = this.chunks.join(\"\");\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status2;\n this.msg = this.strm.msg;\n };\n function deflate2(input, options) {\n var deflator = new Deflate(options);\n deflator.push(input, true);\n if (deflator.err) {\n throw deflator.msg || msg[deflator.err];\n }\n return deflator.result;\n }\n function deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate2(input, options);\n }\n function gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate2(input, options);\n }\n exports.Deflate = Deflate;\n exports.deflate = deflate2;\n exports.deflateRaw = deflateRaw;\n exports.gzip = gzip;\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js\nvar require_inffast = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js\"(exports, module) {\n \"use strict\";\n var BAD = 30;\n var TYPE = 12;\n module.exports = function inflate_fast(strm, start) {\n var state;\n var _in;\n var last;\n var _out;\n var beg;\n var end;\n var dmax;\n var wsize;\n var whave;\n var wnext;\n var s_window;\n var hold;\n var bits;\n var lcode;\n var dcode;\n var lmask;\n var dmask;\n var here;\n var op;\n var len;\n var dist;\n var from;\n var from_source;\n var input, output;\n state = strm.state;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n dmax = state.dmax;\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = lcode[hold & lmask];\n dolen:\n for (; ; ) {\n op = here >>> 24;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 255;\n if (op === 0) {\n output[_out++] = here & 65535;\n } else if (op & 16) {\n len = here & 65535;\n op &= 15;\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & (1 << op) - 1;\n hold >>>= op;\n bits -= op;\n }\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n dodist:\n for (; ; ) {\n op = here >>> 24;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 255;\n if (op & 16) {\n dist = here & 65535;\n op &= 15;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & (1 << op) - 1;\n if (dist > dmax) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n hold >>>= op;\n bits -= op;\n op = _out - beg;\n if (dist > op) {\n op = dist - op;\n if (op > whave) {\n if (state.sane) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n }\n from = 0;\n from_source = s_window;\n if (wnext === 0) {\n from += wsize - op;\n if (op < len) {\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist;\n from_source = output;\n }\n } else if (wnext < op) {\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) {\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) {\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist;\n from_source = output;\n }\n }\n } else {\n from += wnext - op;\n if (op < len) {\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist;\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n } else {\n from = _out - dist;\n do {\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n } else if ((op & 64) === 0) {\n here = dcode[(here & 65535) + (hold & (1 << op) - 1)];\n continue dodist;\n } else {\n strm.msg = \"invalid distance code\";\n state.mode = BAD;\n break top;\n }\n break;\n }\n } else if ((op & 64) === 0) {\n here = lcode[(here & 65535) + (hold & (1 << op) - 1)];\n continue dolen;\n } else if (op & 32) {\n state.mode = TYPE;\n break top;\n } else {\n strm.msg = \"invalid literal/length code\";\n state.mode = BAD;\n break top;\n }\n break;\n }\n } while (_in < last && _out < end);\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);\n strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);\n state.hold = hold;\n state.bits = bits;\n return;\n };\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js\nvar require_inftrees = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js\"(exports, module) {\n \"use strict\";\n var utils = require_common();\n var MAXBITS = 15;\n var ENOUGH_LENS = 852;\n var ENOUGH_DISTS = 592;\n var CODES = 0;\n var LENS = 1;\n var DISTS = 2;\n var lbase = [\n /* Length codes 257..285 base */\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 13,\n 15,\n 17,\n 19,\n 23,\n 27,\n 31,\n 35,\n 43,\n 51,\n 59,\n 67,\n 83,\n 99,\n 115,\n 131,\n 163,\n 195,\n 227,\n 258,\n 0,\n 0\n ];\n var lext = [\n /* Length codes 257..285 extra */\n 16,\n 16,\n 16,\n 16,\n 16,\n 16,\n 16,\n 16,\n 17,\n 17,\n 17,\n 17,\n 18,\n 18,\n 18,\n 18,\n 19,\n 19,\n 19,\n 19,\n 20,\n 20,\n 20,\n 20,\n 21,\n 21,\n 21,\n 21,\n 16,\n 72,\n 78\n ];\n var dbase = [\n /* Distance codes 0..29 base */\n 1,\n 2,\n 3,\n 4,\n 5,\n 7,\n 9,\n 13,\n 17,\n 25,\n 33,\n 49,\n 65,\n 97,\n 129,\n 193,\n 257,\n 385,\n 513,\n 769,\n 1025,\n 1537,\n 2049,\n 3073,\n 4097,\n 6145,\n 8193,\n 12289,\n 16385,\n 24577,\n 0,\n 0\n ];\n var dext = [\n /* Distance codes 0..29 extra */\n 16,\n 16,\n 16,\n 16,\n 17,\n 17,\n 18,\n 18,\n 19,\n 19,\n 20,\n 20,\n 21,\n 21,\n 22,\n 22,\n 23,\n 23,\n 24,\n 24,\n 25,\n 25,\n 26,\n 26,\n 27,\n 27,\n 28,\n 28,\n 29,\n 29,\n 64,\n 64\n ];\n module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {\n var bits = opts.bits;\n var len = 0;\n var sym = 0;\n var min = 0, max = 0;\n var root = 0;\n var curr = 0;\n var drop = 0;\n var left = 0;\n var used = 0;\n var huff = 0;\n var incr;\n var fill;\n var low;\n var mask;\n var next;\n var base = null;\n var base_index = 0;\n var end;\n var count = new utils.Buf16(MAXBITS + 1);\n var offs = new utils.Buf16(MAXBITS + 1);\n var extra = null;\n var extra_index = 0;\n var here_bits, here_op, here_val;\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) {\n break;\n }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) {\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n opts.bits = 1;\n return 0;\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) {\n break;\n }\n }\n if (root < min) {\n root = min;\n }\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n }\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1;\n }\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n if (type === CODES) {\n base = extra = work;\n end = 19;\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n } else {\n base = dbase;\n extra = dext;\n end = -1;\n }\n huff = 0;\n sym = 0;\n len = min;\n next = table_index;\n curr = root;\n drop = 0;\n low = -1;\n used = 1 << root;\n mask = used - 1;\n if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n for (; ; ) {\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n } else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n } else {\n here_op = 32 + 64;\n here_val = 0;\n }\n incr = 1 << len - drop;\n fill = 1 << curr;\n min = fill;\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0;\n } while (fill !== 0);\n incr = 1 << len - 1;\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n sym++;\n if (--count[len] === 0) {\n if (len === max) {\n break;\n }\n len = lens[lens_index + work[sym]];\n }\n if (len > root && (huff & mask) !== low) {\n if (drop === 0) {\n drop = root;\n }\n next += min;\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) {\n break;\n }\n curr++;\n left <<= 1;\n }\n used += 1 << curr;\n if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n low = huff & mask;\n table[low] = root << 24 | curr << 16 | next - table_index | 0;\n }\n }\n if (huff !== 0) {\n table[next + huff] = len - drop << 24 | 64 << 16 | 0;\n }\n opts.bits = root;\n return 0;\n };\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js\nvar require_inflate = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js\"(exports) {\n \"use strict\";\n var utils = require_common();\n var adler32 = require_adler32();\n var crc322 = require_crc322();\n var inflate_fast = require_inffast();\n var inflate_table = require_inftrees();\n var CODES = 0;\n var LENS = 1;\n var DISTS = 2;\n var Z_FINISH = 4;\n var Z_BLOCK = 5;\n var Z_TREES = 6;\n var Z_OK = 0;\n var Z_STREAM_END = 1;\n var Z_NEED_DICT = 2;\n var Z_STREAM_ERROR = -2;\n var Z_DATA_ERROR = -3;\n var Z_MEM_ERROR = -4;\n var Z_BUF_ERROR = -5;\n var Z_DEFLATED = 8;\n var HEAD = 1;\n var FLAGS = 2;\n var TIME = 3;\n var OS = 4;\n var EXLEN = 5;\n var EXTRA = 6;\n var NAME = 7;\n var COMMENT = 8;\n var HCRC = 9;\n var DICTID = 10;\n var DICT = 11;\n var TYPE = 12;\n var TYPEDO = 13;\n var STORED = 14;\n var COPY_ = 15;\n var COPY = 16;\n var TABLE = 17;\n var LENLENS = 18;\n var CODELENS = 19;\n var LEN_ = 20;\n var LEN = 21;\n var LENEXT = 22;\n var DIST = 23;\n var DISTEXT = 24;\n var MATCH = 25;\n var LIT = 26;\n var CHECK = 27;\n var LENGTH = 28;\n var DONE = 29;\n var BAD = 30;\n var MEM = 31;\n var SYNC = 32;\n var ENOUGH_LENS = 852;\n var ENOUGH_DISTS = 592;\n var MAX_WBITS = 15;\n var DEF_WBITS = MAX_WBITS;\n function zswap32(q) {\n return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24);\n }\n function InflateState() {\n this.mode = 0;\n this.last = false;\n this.wrap = 0;\n this.havedict = false;\n this.flags = 0;\n this.dmax = 0;\n this.check = 0;\n this.total = 0;\n this.head = null;\n this.wbits = 0;\n this.wsize = 0;\n this.whave = 0;\n this.wnext = 0;\n this.window = null;\n this.hold = 0;\n this.bits = 0;\n this.length = 0;\n this.offset = 0;\n this.extra = 0;\n this.lencode = null;\n this.distcode = null;\n this.lenbits = 0;\n this.distbits = 0;\n this.ncode = 0;\n this.nlen = 0;\n this.ndist = 0;\n this.have = 0;\n this.next = null;\n this.lens = new utils.Buf16(320);\n this.work = new utils.Buf16(288);\n this.lendyn = null;\n this.distdyn = null;\n this.sane = 0;\n this.back = 0;\n this.was = 0;\n }\n function inflateResetKeep(strm) {\n var state;\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = \"\";\n if (state.wrap) {\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null;\n state.hold = 0;\n state.bits = 0;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n state.sane = 1;\n state.back = -1;\n return Z_OK;\n }\n function inflateReset(strm) {\n var state;\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n }\n function inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n state = strm.state;\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n } else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n }\n function inflateInit2(strm, windowBits) {\n var ret;\n var state;\n if (!strm) {\n return Z_STREAM_ERROR;\n }\n state = new InflateState();\n strm.state = state;\n state.window = null;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null;\n }\n return ret;\n }\n function inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n }\n var virgin = true;\n var lenfix;\n var distfix;\n function fixedtables(state) {\n if (virgin) {\n var sym;\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n sym = 0;\n while (sym < 144) {\n state.lens[sym++] = 8;\n }\n while (sym < 256) {\n state.lens[sym++] = 9;\n }\n while (sym < 280) {\n state.lens[sym++] = 7;\n }\n while (sym < 288) {\n state.lens[sym++] = 8;\n }\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n sym = 0;\n while (sym < 32) {\n state.lens[sym++] = 5;\n }\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n virgin = false;\n }\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n }\n function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n state.window = new utils.Buf8(state.wsize);\n }\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n } else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n } else {\n state.wnext += dist;\n if (state.wnext === state.wsize) {\n state.wnext = 0;\n }\n if (state.whave < state.wsize) {\n state.whave += dist;\n }\n }\n }\n return 0;\n }\n function inflate2(strm, flush) {\n var state;\n var input, output;\n var next;\n var put;\n var have, left;\n var hold;\n var bits;\n var _in, _out;\n var copy;\n var from;\n var from_source;\n var here = 0;\n var here_bits, here_op, here_val;\n var last_bits, last_op, last_val;\n var len;\n var ret;\n var hbuf = new utils.Buf8(4);\n var opts;\n var n;\n var order = (\n /* permutation of code lengths */\n [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]\n );\n if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) {\n return Z_STREAM_ERROR;\n }\n state = strm.state;\n if (state.mode === TYPE) {\n state.mode = TYPEDO;\n }\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n _in = have;\n _out = left;\n ret = Z_OK;\n inf_leave:\n for (; ; ) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n while (bits < 16) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if (state.wrap & 2 && hold === 35615) {\n state.check = 0;\n hbuf[0] = hold & 255;\n hbuf[1] = hold >>> 8 & 255;\n state.check = crc322(state.check, hbuf, 2, 0);\n hold = 0;\n bits = 0;\n state.mode = FLAGS;\n break;\n }\n state.flags = 0;\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 255) << 8) + (hold >> 8)) % 31) {\n strm.msg = \"incorrect header check\";\n state.mode = BAD;\n break;\n }\n if ((hold & 15) !== Z_DEFLATED) {\n strm.msg = \"unknown compression method\";\n state.mode = BAD;\n break;\n }\n hold >>>= 4;\n bits -= 4;\n len = (hold & 15) + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n } else if (len > state.wbits) {\n strm.msg = \"invalid window size\";\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n strm.adler = state.check = 1;\n state.mode = hold & 512 ? DICTID : TYPE;\n hold = 0;\n bits = 0;\n break;\n case FLAGS:\n while (bits < 16) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n state.flags = hold;\n if ((state.flags & 255) !== Z_DEFLATED) {\n strm.msg = \"unknown compression method\";\n state.mode = BAD;\n break;\n }\n if (state.flags & 57344) {\n strm.msg = \"unknown header flags set\";\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = hold >> 8 & 1;\n }\n if (state.flags & 512) {\n hbuf[0] = hold & 255;\n hbuf[1] = hold >>> 8 & 255;\n state.check = crc322(state.check, hbuf, 2, 0);\n }\n hold = 0;\n bits = 0;\n state.mode = TIME;\n /* falls through */\n case TIME:\n while (bits < 32) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 512) {\n hbuf[0] = hold & 255;\n hbuf[1] = hold >>> 8 & 255;\n hbuf[2] = hold >>> 16 & 255;\n hbuf[3] = hold >>> 24 & 255;\n state.check = crc322(state.check, hbuf, 4, 0);\n }\n hold = 0;\n bits = 0;\n state.mode = OS;\n /* falls through */\n case OS:\n while (bits < 16) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if (state.head) {\n state.head.xflags = hold & 255;\n state.head.os = hold >> 8;\n }\n if (state.flags & 512) {\n hbuf[0] = hold & 255;\n hbuf[1] = hold >>> 8 & 255;\n state.check = crc322(state.check, hbuf, 2, 0);\n }\n hold = 0;\n bits = 0;\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 1024) {\n while (bits < 16) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 512) {\n hbuf[0] = hold & 255;\n hbuf[1] = hold >>> 8 & 255;\n state.check = crc322(state.check, hbuf, 2, 0);\n }\n hold = 0;\n bits = 0;\n } else if (state.head) {\n state.head.extra = null;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 1024) {\n copy = state.length;\n if (copy > have) {\n copy = have;\n }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n }\n if (state.flags & 512) {\n state.check = crc322(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) {\n break inf_leave;\n }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 2048) {\n if (have === 0) {\n break inf_leave;\n }\n copy = 0;\n do {\n len = input[next + copy++];\n if (state.head && len && state.length < 65536) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 512) {\n state.check = crc322(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) {\n break inf_leave;\n }\n } else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 4096) {\n if (have === 0) {\n break inf_leave;\n }\n copy = 0;\n do {\n len = input[next + copy++];\n if (state.head && len && state.length < 65536) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 512) {\n state.check = crc322(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) {\n break inf_leave;\n }\n } else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 512) {\n while (bits < 16) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if (hold !== (state.check & 65535)) {\n strm.msg = \"header crc mismatch\";\n state.mode = BAD;\n break;\n }\n hold = 0;\n bits = 0;\n }\n if (state.head) {\n state.head.hcrc = state.flags >> 9 & 1;\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n while (bits < 32) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n strm.adler = state.check = zswap32(hold);\n hold = 0;\n bits = 0;\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) {\n break inf_leave;\n }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n hold >>>= bits & 7;\n bits -= bits & 7;\n state.mode = CHECK;\n break;\n }\n while (bits < 3) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n state.last = hold & 1;\n hold >>>= 1;\n bits -= 1;\n switch (hold & 3) {\n case 0:\n state.mode = STORED;\n break;\n case 1:\n fixedtables(state);\n state.mode = LEN_;\n if (flush === Z_TREES) {\n hold >>>= 2;\n bits -= 2;\n break inf_leave;\n }\n break;\n case 2:\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = \"invalid block type\";\n state.mode = BAD;\n }\n hold >>>= 2;\n bits -= 2;\n break;\n case STORED:\n hold >>>= bits & 7;\n bits -= bits & 7;\n while (bits < 32) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if ((hold & 65535) !== (hold >>> 16 ^ 65535)) {\n strm.msg = \"invalid stored block lengths\";\n state.mode = BAD;\n break;\n }\n state.length = hold & 65535;\n hold = 0;\n bits = 0;\n state.mode = COPY_;\n if (flush === Z_TREES) {\n break inf_leave;\n }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) {\n copy = have;\n }\n if (copy > left) {\n copy = left;\n }\n if (copy === 0) {\n break inf_leave;\n }\n utils.arraySet(output, input, next, copy, put);\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n state.mode = TYPE;\n break;\n case TABLE:\n while (bits < 14) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n state.nlen = (hold & 31) + 257;\n hold >>>= 5;\n bits -= 5;\n state.ndist = (hold & 31) + 1;\n hold >>>= 5;\n bits -= 5;\n state.ncode = (hold & 15) + 4;\n hold >>>= 4;\n bits -= 4;\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = \"too many length or distance symbols\";\n state.mode = BAD;\n break;\n }\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n while (bits < 3) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n state.lens[order[state.have++]] = hold & 7;\n hold >>>= 3;\n bits -= 3;\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n state.lencode = state.lendyn;\n state.lenbits = 7;\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n if (ret) {\n strm.msg = \"invalid code lengths set\";\n state.mode = BAD;\n break;\n }\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (; ; ) {\n here = state.lencode[hold & (1 << state.lenbits) - 1];\n here_bits = here >>> 24;\n here_op = here >>> 16 & 255;\n here_val = here & 65535;\n if (here_bits <= bits) {\n break;\n }\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if (here_val < 16) {\n hold >>>= here_bits;\n bits -= here_bits;\n state.lens[state.have++] = here_val;\n } else {\n if (here_val === 16) {\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n hold >>>= here_bits;\n bits -= here_bits;\n if (state.have === 0) {\n strm.msg = \"invalid bit length repeat\";\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 3);\n hold >>>= 2;\n bits -= 2;\n } else if (here_val === 17) {\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n hold >>>= here_bits;\n bits -= here_bits;\n len = 0;\n copy = 3 + (hold & 7);\n hold >>>= 3;\n bits -= 3;\n } else {\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n hold >>>= here_bits;\n bits -= here_bits;\n len = 0;\n copy = 11 + (hold & 127);\n hold >>>= 7;\n bits -= 7;\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = \"invalid bit length repeat\";\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n if (state.mode === BAD) {\n break;\n }\n if (state.lens[256] === 0) {\n strm.msg = \"invalid code -- missing end-of-block\";\n state.mode = BAD;\n break;\n }\n state.lenbits = 9;\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n if (ret) {\n strm.msg = \"invalid literal/lengths set\";\n state.mode = BAD;\n break;\n }\n state.distbits = 6;\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n state.distbits = opts.bits;\n if (ret) {\n strm.msg = \"invalid distances set\";\n state.mode = BAD;\n break;\n }\n state.mode = LEN_;\n if (flush === Z_TREES) {\n break inf_leave;\n }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n inflate_fast(strm, _out);\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (; ; ) {\n here = state.lencode[hold & (1 << state.lenbits) - 1];\n here_bits = here >>> 24;\n here_op = here >>> 16 & 255;\n here_val = here & 65535;\n if (here_bits <= bits) {\n break;\n }\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if (here_op && (here_op & 240) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (; ; ) {\n here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];\n here_bits = here >>> 24;\n here_op = here >>> 16 & 255;\n here_val = here & 65535;\n if (last_bits + here_bits <= bits) {\n break;\n }\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n hold >>>= last_bits;\n bits -= last_bits;\n state.back += last_bits;\n }\n hold >>>= here_bits;\n bits -= here_bits;\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = \"invalid literal/length code\";\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n n = state.extra;\n while (bits < n) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n state.length += hold & (1 << state.extra) - 1;\n hold >>>= state.extra;\n bits -= state.extra;\n state.back += state.extra;\n }\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (; ; ) {\n here = state.distcode[hold & (1 << state.distbits) - 1];\n here_bits = here >>> 24;\n here_op = here >>> 16 & 255;\n here_val = here & 65535;\n if (here_bits <= bits) {\n break;\n }\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if ((here_op & 240) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (; ; ) {\n here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];\n here_bits = here >>> 24;\n here_op = here >>> 16 & 255;\n here_val = here & 65535;\n if (last_bits + here_bits <= bits) {\n break;\n }\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n hold >>>= last_bits;\n bits -= last_bits;\n state.back += last_bits;\n }\n hold >>>= here_bits;\n bits -= here_bits;\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = \"invalid distance code\";\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = here_op & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n n = state.extra;\n while (bits < n) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n state.offset += hold & (1 << state.extra) - 1;\n hold >>>= state.extra;\n bits -= state.extra;\n state.back += state.extra;\n }\n if (state.offset > state.dmax) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break;\n }\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) {\n break inf_leave;\n }\n copy = _out - left;\n if (state.offset > copy) {\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break;\n }\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n } else {\n from = state.wnext - copy;\n }\n if (copy > state.length) {\n copy = state.length;\n }\n from_source = state.window;\n } else {\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) {\n copy = left;\n }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) {\n state.mode = LEN;\n }\n break;\n case LIT:\n if (left === 0) {\n break inf_leave;\n }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n while (bits < 32) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold |= input[next++] << bits;\n bits += 8;\n }\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/\n state.flags ? crc322(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out);\n }\n _out = left;\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = \"incorrect data check\";\n state.mode = BAD;\n break;\n }\n hold = 0;\n bits = 0;\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n while (bits < 32) {\n if (have === 0) {\n break inf_leave;\n }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n if (hold !== (state.total & 4294967295)) {\n strm.msg = \"incorrect length check\";\n state.mode = BAD;\n break;\n }\n hold = 0;\n bits = 0;\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n state.flags ? crc322(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out);\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n }\n function inflateEnd(strm) {\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n }\n function inflateGetHeader(strm, head) {\n var state;\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n state = strm.state;\n if ((state.wrap & 2) === 0) {\n return Z_STREAM_ERROR;\n }\n state.head = head;\n head.done = false;\n return Z_OK;\n }\n function inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n var state;\n var dictid;\n var ret;\n if (!strm || !strm.state) {\n return Z_STREAM_ERROR;\n }\n state = strm.state;\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n if (state.mode === DICT) {\n dictid = 1;\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n return Z_OK;\n }\n exports.inflateReset = inflateReset;\n exports.inflateReset2 = inflateReset2;\n exports.inflateResetKeep = inflateResetKeep;\n exports.inflateInit = inflateInit;\n exports.inflateInit2 = inflateInit2;\n exports.inflate = inflate2;\n exports.inflateEnd = inflateEnd;\n exports.inflateGetHeader = inflateGetHeader;\n exports.inflateSetDictionary = inflateSetDictionary;\n exports.inflateInfo = \"pako inflate (from Nodeca project)\";\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/constants.js\nvar require_constants = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/constants.js\"(exports, module) {\n \"use strict\";\n module.exports = {\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n };\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js\nvar require_gzheader = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js\"(exports, module) {\n \"use strict\";\n function GZheader() {\n this.text = 0;\n this.time = 0;\n this.xflags = 0;\n this.os = 0;\n this.extra = null;\n this.extra_len = 0;\n this.name = \"\";\n this.comment = \"\";\n this.hcrc = 0;\n this.done = false;\n }\n module.exports = GZheader;\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/inflate.js\nvar require_inflate2 = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/inflate.js\"(exports) {\n \"use strict\";\n var zlib_inflate = require_inflate();\n var utils = require_common();\n var strings = require_strings();\n var c = require_constants();\n var msg = require_messages();\n var ZStream = require_zstream();\n var GZheader = require_gzheader();\n var toString = Object.prototype.toString;\n function Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: \"\"\n }, options || {});\n var opt = this.options;\n if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) {\n opt.windowBits = -15;\n }\n }\n if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n if (opt.windowBits > 15 && opt.windowBits < 48) {\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n this.err = 0;\n this.msg = \"\";\n this.ended = false;\n this.chunks = [];\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n var status2 = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n if (status2 !== c.Z_OK) {\n throw new Error(msg[status2]);\n }\n this.header = new GZheader();\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n if (opt.dictionary) {\n if (typeof opt.dictionary === \"string\") {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === \"[object ArrayBuffer]\") {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) {\n status2 = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status2 !== c.Z_OK) {\n throw new Error(msg[status2]);\n }\n }\n }\n }\n Inflate.prototype.push = function(data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status2, _mode;\n var next_out_utf8, tail, utf8str;\n var allowBufError = false;\n if (this.ended) {\n return false;\n }\n _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH;\n if (typeof data === \"string\") {\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === \"[object ArrayBuffer]\") {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status2 = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);\n if (status2 === c.Z_NEED_DICT && dictionary) {\n status2 = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n if (status2 === c.Z_BUF_ERROR && allowBufError === true) {\n status2 = c.Z_OK;\n allowBufError = false;\n }\n if (status2 !== c.Z_STREAM_END && status2 !== c.Z_OK) {\n this.onEnd(status2);\n this.ended = true;\n return false;\n }\n if (strm.next_out) {\n if (strm.avail_out === 0 || status2 === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) {\n if (this.options.to === \"string\") {\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) {\n utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0);\n }\n this.onData(utf8str);\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status2 !== c.Z_STREAM_END);\n if (status2 === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n if (_mode === c.Z_FINISH) {\n status2 = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status2);\n this.ended = true;\n return status2 === c.Z_OK;\n }\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n return true;\n };\n Inflate.prototype.onData = function(chunk) {\n this.chunks.push(chunk);\n };\n Inflate.prototype.onEnd = function(status2) {\n if (status2 === c.Z_OK) {\n if (this.options.to === \"string\") {\n this.result = this.chunks.join(\"\");\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status2;\n this.msg = this.strm.msg;\n };\n function inflate2(input, options) {\n var inflator = new Inflate(options);\n inflator.push(input, true);\n if (inflator.err) {\n throw inflator.msg || msg[inflator.err];\n }\n return inflator.result;\n }\n function inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate2(input, options);\n }\n exports.Inflate = Inflate;\n exports.inflate = inflate2;\n exports.inflateRaw = inflateRaw;\n exports.ungzip = inflate2;\n }\n});\n\n// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/index.js\nvar require_pako = __commonJS({\n \"../../node_modules/.bun/pako@1.0.11/node_modules/pako/index.js\"(exports, module) {\n \"use strict\";\n var assign = require_common().assign;\n var deflate2 = require_deflate2();\n var inflate2 = require_inflate2();\n var constants = require_constants();\n var pako2 = {};\n assign(pako2, deflate2, inflate2, constants);\n module.exports = pako2;\n }\n});\n\n// ../../node_modules/.bun/pify@4.0.1/node_modules/pify/index.js\nvar require_pify = __commonJS({\n \"../../node_modules/.bun/pify@4.0.1/node_modules/pify/index.js\"(exports, module) {\n \"use strict\";\n var processFn = (fn, options) => function(...args) {\n const P = options.promiseModule;\n return new P((resolve, reject) => {\n if (options.multiArgs) {\n args.push((...result) => {\n if (options.errorFirst) {\n if (result[0]) {\n reject(result);\n } else {\n result.shift();\n resolve(result);\n }\n } else {\n resolve(result);\n }\n });\n } else if (options.errorFirst) {\n args.push((error, result) => {\n if (error) {\n reject(error);\n } else {\n resolve(result);\n }\n });\n } else {\n args.push(resolve);\n }\n fn.apply(this, args);\n });\n };\n module.exports = (input, options) => {\n options = Object.assign({\n exclude: [/.+(Sync|Stream)$/],\n errorFirst: true,\n promiseModule: Promise\n }, options);\n const objType = typeof input;\n if (!(input !== null && (objType === \"object\" || objType === \"function\"))) {\n throw new TypeError(`Expected \\`input\\` to be a \\`Function\\` or \\`Object\\`, got \\`${input === null ? \"null\" : objType}\\``);\n }\n const filter = (key) => {\n const match = (pattern) => typeof pattern === \"string\" ? key === pattern : pattern.test(key);\n return options.include ? options.include.some(match) : !options.exclude.some(match);\n };\n let ret;\n if (objType === \"function\") {\n ret = function(...args) {\n return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args);\n };\n } else {\n ret = Object.create(Object.getPrototypeOf(input));\n }\n for (const key in input) {\n const property = input[key];\n ret[key] = typeof property === \"function\" && filter(key) ? processFn(property, options) : property;\n }\n return ret;\n };\n }\n});\n\n// ../../node_modules/.bun/ignore@5.3.2/node_modules/ignore/index.js\nvar require_ignore = __commonJS({\n \"../../node_modules/.bun/ignore@5.3.2/node_modules/ignore/index.js\"(exports, module) {\n function makeArray(subject) {\n return Array.isArray(subject) ? subject : [subject];\n }\n var EMPTY = \"\";\n var SPACE = \" \";\n var ESCAPE = \"\\\\\";\n var REGEX_TEST_BLANK_LINE = /^\\s+$/;\n var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/;\n var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/;\n var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/;\n var REGEX_SPLITALL_CRLF = /\\r?\\n/g;\n var REGEX_TEST_INVALID_PATH = /^\\.*\\/|^\\.+$/;\n var SLASH = \"/\";\n var TMP_KEY_IGNORE = \"node-ignore\";\n if (typeof Symbol !== \"undefined\") {\n TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for(\"node-ignore\");\n }\n var KEY_IGNORE = TMP_KEY_IGNORE;\n var define2 = (object, key, value) => Object.defineProperty(object, key, { value });\n var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;\n var RETURN_FALSE = () => false;\n var sanitizeRange = (range) => range.replace(\n REGEX_REGEXP_RANGE,\n (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY\n );\n var cleanRangeBackSlash = (slashes) => {\n const { length } = slashes;\n return slashes.slice(0, length - length % 2);\n };\n var REPLACERS = [\n [\n // remove BOM\n // TODO:\n // Other similar zero-width characters?\n /^\\uFEFF/,\n () => EMPTY\n ],\n // > Trailing spaces are ignored unless they are quoted with backslash (\"\\\")\n [\n // (a\\ ) -> (a )\n // (a ) -> (a)\n // (a ) -> (a)\n // (a \\ ) -> (a )\n /((?:\\\\\\\\)*?)(\\\\?\\s+)$/,\n (_, m1, m2) => m1 + (m2.indexOf(\"\\\\\") === 0 ? SPACE : EMPTY)\n ],\n // replace (\\ ) with ' '\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n /(\\\\+?)\\s/g,\n (_, m1) => {\n const { length } = m1;\n return m1.slice(0, length - length % 2) + SPACE;\n }\n ],\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n (match) => `\\\\${match}`\n ],\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => \"[^/]\"\n ],\n // leading slash\n [\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => \"^\"\n ],\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => \"\\\\/\"\n ],\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*\\\\\\*\\\\\\*\\\\\\//,\n // '**/foo' <-> 'foo'\n () => \"^(?:.*\\\\/)?\"\n ],\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n /^(?=[^^])/,\n function startingReplacer() {\n return !/\\/(?!$)/.test(this) ? \"(?:^|\\\\/)\" : \"^\";\n }\n ],\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n // Check if it is not the last `'/**'`\n (_, index3, str) => index3 + 6 < str.length ? \"(?:\\\\/[^\\\\/]+)*\" : \"\\\\/.+\"\n ],\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n const unescaped = p2.replace(/\\\\\\*/g, \"[^\\\\/]*\");\n return p1 + unescaped;\n }\n ],\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE\n ],\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE\n ],\n [\n // > The range notation, e.g. [a-zA-Z],\n // > can be used to match one of the characters in a range.\n // `\\` is escaped by step 3\n /(\\\\)?\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === \"]\" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : \"[]\" : \"[]\"\n ],\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n /(?:[^*])$/,\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n (match) => /\\/$/.test(match) ? `${match}$` : `${match}(?=$|\\\\/$)`\n ],\n // trailing wildcard\n [\n /(\\^|\\\\\\/)?\\\\\\*$/,\n (_, p1) => {\n const prefix = p1 ? `${p1}[^/]+` : \"[^/]*\";\n return `${prefix}(?=$|\\\\/$)`;\n }\n ]\n ];\n var regexCache = /* @__PURE__ */ Object.create(null);\n var makeRegex = (pattern, ignoreCase) => {\n let source = regexCache[pattern];\n if (!source) {\n source = REPLACERS.reduce(\n (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),\n pattern\n );\n regexCache[pattern] = source;\n }\n return ignoreCase ? new RegExp(source, \"i\") : new RegExp(source);\n };\n var isString = (subject) => typeof subject === \"string\";\n var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf(\"#\") !== 0;\n var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF);\n var IgnoreRule = class {\n constructor(origin, pattern, negative, regex) {\n this.origin = origin;\n this.pattern = pattern;\n this.negative = negative;\n this.regex = regex;\n }\n };\n var createRule = (pattern, ignoreCase) => {\n const origin = pattern;\n let negative = false;\n if (pattern.indexOf(\"!\") === 0) {\n negative = true;\n pattern = pattern.substr(1);\n }\n pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, \"!\").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, \"#\");\n const regex = makeRegex(pattern, ignoreCase);\n return new IgnoreRule(\n origin,\n pattern,\n negative,\n regex\n );\n };\n var throwError = (message, Ctor) => {\n throw new Ctor(message);\n };\n var checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n );\n }\n if (!path) {\n return doThrow(`path must not be empty`, TypeError);\n }\n if (checkPath.isNotRelative(path)) {\n const r = \"`path.relative()`d\";\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n );\n }\n return true;\n };\n var isNotRelative = (path) => REGEX_TEST_INVALID_PATH.test(path);\n checkPath.isNotRelative = isNotRelative;\n checkPath.convert = (p) => p;\n var Ignore = class {\n constructor({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define2(this, KEY_IGNORE, true);\n this._rules = [];\n this._ignoreCase = ignoreCase;\n this._allowRelativePaths = allowRelativePaths;\n this._initCache();\n }\n _initCache() {\n this._ignoreCache = /* @__PURE__ */ Object.create(null);\n this._testCache = /* @__PURE__ */ Object.create(null);\n }\n _addPattern(pattern) {\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules);\n this._added = true;\n return;\n }\n if (checkPattern(pattern)) {\n const rule = createRule(pattern, this._ignoreCase);\n this._added = true;\n this._rules.push(rule);\n }\n }\n // @param {Array<string> | string | Ignore} pattern\n add(pattern) {\n this._added = false;\n makeArray(\n isString(pattern) ? splitPattern(pattern) : pattern\n ).forEach(this._addPattern, this);\n if (this._added) {\n this._initCache();\n }\n return this;\n }\n // legacy\n addPattern(pattern) {\n return this.add(pattern);\n }\n // | ignored : unignored\n // negative | 0:0 | 0:1 | 1:0 | 1:1\n // -------- | ------- | ------- | ------- | --------\n // 0 | TEST | TEST | SKIP | X\n // 1 | TESTIF | SKIP | TEST | X\n // - SKIP: always skip\n // - TEST: always test\n // - TESTIF: only test if checkUnignored\n // - X: that never happen\n // @param {boolean} whether should check if the path is unignored,\n // setting `checkUnignored` to `false` could reduce additional\n // path matching.\n // @returns {TestResult} true if a file is ignored\n _testOne(path, checkUnignored) {\n let ignored = false;\n let unignored = false;\n this._rules.forEach((rule) => {\n const { negative } = rule;\n if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {\n return;\n }\n const matched = rule.regex.test(path);\n if (matched) {\n ignored = !negative;\n unignored = negative;\n }\n });\n return {\n ignored,\n unignored\n };\n }\n // @returns {TestResult}\n _test(originalPath, cache, checkUnignored, slices) {\n const path = originalPath && checkPath.convert(originalPath);\n checkPath(\n path,\n originalPath,\n this._allowRelativePaths ? RETURN_FALSE : throwError\n );\n return this._t(path, cache, checkUnignored, slices);\n }\n _t(path, cache, checkUnignored, slices) {\n if (path in cache) {\n return cache[path];\n }\n if (!slices) {\n slices = path.split(SLASH);\n }\n slices.pop();\n if (!slices.length) {\n return cache[path] = this._testOne(path, checkUnignored);\n }\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n cache,\n checkUnignored,\n slices\n );\n return cache[path] = parent.ignored ? parent : this._testOne(path, checkUnignored);\n }\n ignores(path) {\n return this._test(path, this._ignoreCache, false).ignored;\n }\n createFilter() {\n return (path) => !this.ignores(path);\n }\n filter(paths) {\n return makeArray(paths).filter(this.createFilter());\n }\n // @returns {TestResult}\n test(path) {\n return this._test(path, this._testCache, true);\n }\n };\n var factory = (options) => new Ignore(options);\n var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);\n factory.isPathValid = isPathValid;\n factory.default = factory;\n module.exports = factory;\n if (\n // Detect `process` so that it can run in browsers.\n typeof process !== \"undefined\" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === \"win32\")\n ) {\n const makePosix = (str) => /^\\\\\\\\\\?\\\\/.test(str) || /[\"<>|\\u0000-\\u001F]+/u.test(str) ? str : str.replace(/\\\\/g, \"/\");\n checkPath.convert = makePosix;\n const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i;\n checkPath.isNotRelative = (path) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);\n }\n }\n});\n\n// ../../node_modules/.bun/clean-git-ref@2.0.1/node_modules/clean-git-ref/lib/index.js\nvar require_lib = __commonJS({\n \"../../node_modules/.bun/clean-git-ref@2.0.1/node_modules/clean-git-ref/lib/index.js\"(exports, module) {\n \"use strict\";\n function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n }\n function replaceAll(str, search, replacement) {\n search = search instanceof RegExp ? search : new RegExp(escapeRegExp(search), \"g\");\n return str.replace(search, replacement);\n }\n var CleanGitRef = {\n clean: function clean(value) {\n if (typeof value !== \"string\") {\n throw new Error(\"Expected a string, received: \" + value);\n }\n value = replaceAll(value, \"./\", \"/\");\n value = replaceAll(value, \"..\", \".\");\n value = replaceAll(value, \" \", \"-\");\n value = replaceAll(value, /^[~^:?*\\\\\\-]/g, \"\");\n value = replaceAll(value, /[~^:?*\\\\]/g, \"-\");\n value = replaceAll(value, /[~^:?*\\\\\\-]$/g, \"\");\n value = replaceAll(value, \"@{\", \"-\");\n value = replaceAll(value, /\\.$/g, \"\");\n value = replaceAll(value, /\\/$/g, \"\");\n value = replaceAll(value, /\\.lock$/g, \"\");\n return value;\n }\n };\n module.exports = CleanGitRef;\n }\n});\n\n// ../../node_modules/.bun/is-git-ref-name-valid@1.0.0/node_modules/is-git-ref-name-valid/index.js\nvar require_is_git_ref_name_valid = __commonJS({\n \"../../node_modules/.bun/is-git-ref-name-valid@1.0.0/node_modules/is-git-ref-name-valid/index.js\"(exports, module) {\n \"use strict\";\n var bad = /(^|[/.])([/.]|$)|^@$|@{|[\\x00-\\x20\\x7f~^:?*[\\\\]|\\.lock(\\/|$)/;\n module.exports = function validRef2(name, onelevel) {\n if (typeof name !== \"string\") {\n throw new TypeError(\"Reference name must be a string\");\n }\n return !bad.test(name) && (!!onelevel || name.includes(\"/\"));\n };\n }\n});\n\n// ../../node_modules/.bun/diff3@0.0.3/node_modules/diff3/onp.js\nvar require_onp = __commonJS({\n \"../../node_modules/.bun/diff3@0.0.3/node_modules/diff3/onp.js\"(exports, module) {\n module.exports = function(a_, b_) {\n var a = a_, b = b_, m = a.length, n = b.length, reverse = false, ed = null, offset = m + 1, path = [], pathposi = [], ses = [], lcs = \"\", SES_DELETE = -1, SES_COMMON = 0, SES_ADD = 1;\n var tmp1, tmp2;\n var init2 = function() {\n if (m >= n) {\n tmp1 = a;\n tmp2 = m;\n a = b;\n b = tmp1;\n m = n;\n n = tmp2;\n reverse = true;\n offset = m + 1;\n }\n };\n var P = function(x, y, k) {\n return {\n \"x\": x,\n \"y\": y,\n \"k\": k\n };\n };\n var seselem = function(elem, t) {\n return {\n \"elem\": elem,\n \"t\": t\n };\n };\n var snake = function(k, p, pp) {\n var r, x, y;\n if (p > pp) {\n r = path[k - 1 + offset];\n } else {\n r = path[k + 1 + offset];\n }\n y = Math.max(p, pp);\n x = y - k;\n while (x < m && y < n && a[x] === b[y]) {\n ++x;\n ++y;\n }\n path[k + offset] = pathposi.length;\n pathposi[pathposi.length] = new P(x, y, r);\n return y;\n };\n var recordseq = function(epc) {\n var x_idx, y_idx, px_idx, py_idx, i;\n x_idx = y_idx = 1;\n px_idx = py_idx = 0;\n for (i = epc.length - 1; i >= 0; --i) {\n while (px_idx < epc[i].x || py_idx < epc[i].y) {\n if (epc[i].y - epc[i].x > py_idx - px_idx) {\n if (reverse) {\n ses[ses.length] = new seselem(b[py_idx], SES_DELETE);\n } else {\n ses[ses.length] = new seselem(b[py_idx], SES_ADD);\n }\n ++y_idx;\n ++py_idx;\n } else if (epc[i].y - epc[i].x < py_idx - px_idx) {\n if (reverse) {\n ses[ses.length] = new seselem(a[px_idx], SES_ADD);\n } else {\n ses[ses.length] = new seselem(a[px_idx], SES_DELETE);\n }\n ++x_idx;\n ++px_idx;\n } else {\n ses[ses.length] = new seselem(a[px_idx], SES_COMMON);\n lcs += a[px_idx];\n ++x_idx;\n ++y_idx;\n ++px_idx;\n ++py_idx;\n }\n }\n }\n };\n init2();\n return {\n SES_DELETE: -1,\n SES_COMMON: 0,\n SES_ADD: 1,\n editdistance: function() {\n return ed;\n },\n getlcs: function() {\n return lcs;\n },\n getses: function() {\n return ses;\n },\n compose: function() {\n var delta, size, fp, p, r, epc, i, k;\n delta = n - m;\n size = m + n + 3;\n fp = {};\n for (i = 0; i < size; ++i) {\n fp[i] = -1;\n path[i] = -1;\n }\n p = -1;\n do {\n ++p;\n for (k = -p; k <= delta - 1; ++k) {\n fp[k + offset] = snake(k, fp[k - 1 + offset] + 1, fp[k + 1 + offset]);\n }\n for (k = delta + p; k >= delta + 1; --k) {\n fp[k + offset] = snake(k, fp[k - 1 + offset] + 1, fp[k + 1 + offset]);\n }\n fp[delta + offset] = snake(delta, fp[delta - 1 + offset] + 1, fp[delta + 1 + offset]);\n } while (fp[delta + offset] !== n);\n ed = delta + 2 * p;\n r = path[delta + offset];\n epc = [];\n while (r !== -1) {\n epc[epc.length] = new P(pathposi[r].x, pathposi[r].y, null);\n r = pathposi[r].k;\n }\n recordseq(epc);\n }\n };\n };\n }\n});\n\n// ../../node_modules/.bun/diff3@0.0.3/node_modules/diff3/diff3.js\nvar require_diff3 = __commonJS({\n \"../../node_modules/.bun/diff3@0.0.3/node_modules/diff3/diff3.js\"(exports, module) {\n var onp = require_onp();\n function longestCommonSubsequence(file1, file2) {\n var diff2 = new onp(file1, file2);\n diff2.compose();\n var ses = diff2.getses();\n var root;\n var prev;\n var file1RevIdx = file1.length - 1, file2RevIdx = file2.length - 1;\n for (var i = ses.length - 1; i >= 0; --i) {\n if (ses[i].t === diff2.SES_COMMON) {\n if (prev) {\n prev.chain = {\n file1index: file1RevIdx,\n file2index: file2RevIdx,\n chain: null\n };\n prev = prev.chain;\n } else {\n root = {\n file1index: file1RevIdx,\n file2index: file2RevIdx,\n chain: null\n };\n prev = root;\n }\n file1RevIdx--;\n file2RevIdx--;\n } else if (ses[i].t === diff2.SES_DELETE) {\n file1RevIdx--;\n } else if (ses[i].t === diff2.SES_ADD) {\n file2RevIdx--;\n }\n }\n var tail = {\n file1index: -1,\n file2index: -1,\n chain: null\n };\n if (!prev) {\n return tail;\n }\n prev.chain = tail;\n return root;\n }\n function diffIndices(file1, file2) {\n var result = [];\n var tail1 = file1.length;\n var tail2 = file2.length;\n for (var candidate = longestCommonSubsequence(file1, file2); candidate !== null; candidate = candidate.chain) {\n var mismatchLength1 = tail1 - candidate.file1index - 1;\n var mismatchLength2 = tail2 - candidate.file2index - 1;\n tail1 = candidate.file1index;\n tail2 = candidate.file2index;\n if (mismatchLength1 || mismatchLength2) {\n result.push({\n file1: [tail1 + 1, mismatchLength1],\n file2: [tail2 + 1, mismatchLength2]\n });\n }\n }\n result.reverse();\n return result;\n }\n function diff3MergeIndices(a, o, b) {\n var i;\n var m1 = diffIndices(o, a);\n var m2 = diffIndices(o, b);\n var hunks = [];\n function addHunk(h, side2) {\n hunks.push([h.file1[0], side2, h.file1[1], h.file2[0], h.file2[1]]);\n }\n for (i = 0; i < m1.length; i++) {\n addHunk(m1[i], 0);\n }\n for (i = 0; i < m2.length; i++) {\n addHunk(m2[i], 2);\n }\n hunks.sort(function(x, y) {\n return x[0] - y[0];\n });\n var result = [];\n var commonOffset = 0;\n function copyCommon(targetOffset) {\n if (targetOffset > commonOffset) {\n result.push([1, commonOffset, targetOffset - commonOffset]);\n commonOffset = targetOffset;\n }\n }\n for (var hunkIndex = 0; hunkIndex < hunks.length; hunkIndex++) {\n var firstHunkIndex = hunkIndex;\n var hunk = hunks[hunkIndex];\n var regionLhs = hunk[0];\n var regionRhs = regionLhs + hunk[2];\n while (hunkIndex < hunks.length - 1) {\n var maybeOverlapping = hunks[hunkIndex + 1];\n var maybeLhs = maybeOverlapping[0];\n if (maybeLhs > regionRhs) break;\n regionRhs = Math.max(regionRhs, maybeLhs + maybeOverlapping[2]);\n hunkIndex++;\n }\n copyCommon(regionLhs);\n if (firstHunkIndex == hunkIndex) {\n if (hunk[4] > 0) {\n result.push([hunk[1], hunk[3], hunk[4]]);\n }\n } else {\n var regions = {\n 0: [a.length, -1, o.length, -1],\n 2: [b.length, -1, o.length, -1]\n };\n for (i = firstHunkIndex; i <= hunkIndex; i++) {\n hunk = hunks[i];\n var side = hunk[1];\n var r = regions[side];\n var oLhs = hunk[0];\n var oRhs = oLhs + hunk[2];\n var abLhs = hunk[3];\n var abRhs = abLhs + hunk[4];\n r[0] = Math.min(abLhs, r[0]);\n r[1] = Math.max(abRhs, r[1]);\n r[2] = Math.min(oLhs, r[2]);\n r[3] = Math.max(oRhs, r[3]);\n }\n var aLhs = regions[0][0] + (regionLhs - regions[0][2]);\n var aRhs = regions[0][1] + (regionRhs - regions[0][3]);\n var bLhs = regions[2][0] + (regionLhs - regions[2][2]);\n var bRhs = regions[2][1] + (regionRhs - regions[2][3]);\n result.push([\n -1,\n aLhs,\n aRhs - aLhs,\n regionLhs,\n regionRhs - regionLhs,\n bLhs,\n bRhs - bLhs\n ]);\n }\n commonOffset = regionRhs;\n }\n copyCommon(o.length);\n return result;\n }\n function diff3Merge2(a, o, b) {\n var result = [];\n var files = [a, o, b];\n var indices = diff3MergeIndices(a, o, b);\n var okLines = [];\n function flushOk() {\n if (okLines.length) {\n result.push({\n ok: okLines\n });\n }\n okLines = [];\n }\n function pushOk(xs) {\n for (var j = 0; j < xs.length; j++) {\n okLines.push(xs[j]);\n }\n }\n function isTrueConflict(rec) {\n if (rec[2] != rec[6]) return true;\n var aoff = rec[1];\n var boff = rec[5];\n for (var j = 0; j < rec[2]; j++) {\n if (a[j + aoff] != b[j + boff]) return true;\n }\n return false;\n }\n for (var i = 0; i < indices.length; i++) {\n var x = indices[i];\n var side = x[0];\n if (side == -1) {\n if (!isTrueConflict(x)) {\n pushOk(files[0].slice(x[1], x[1] + x[2]));\n } else {\n flushOk();\n result.push({\n conflict: {\n a: a.slice(x[1], x[1] + x[2]),\n aIndex: x[1],\n o: o.slice(x[3], x[3] + x[4]),\n oIndex: x[3],\n b: b.slice(x[5], x[5] + x[6]),\n bIndex: x[5]\n }\n });\n }\n } else {\n pushOk(files[side].slice(x[1], x[1] + x[2]));\n }\n }\n flushOk();\n return result;\n }\n module.exports = diff3Merge2;\n }\n});\n\n// ../../node_modules/.bun/@ashishkumar472+cf-git@1.0.5/node_modules/@ashishkumar472/cf-git/index.js\nvar cf_git_exports = {};\n__export(cf_git_exports, {\n Errors: () => Errors,\n STAGE: () => STAGE,\n TREE: () => TREE,\n WORKDIR: () => WORKDIR,\n abortMerge: () => abortMerge,\n add: () => add,\n addNote: () => addNote,\n addRemote: () => addRemote,\n annotatedTag: () => annotatedTag,\n branch: () => branch,\n checkout: () => checkout,\n checkoutFreshChunk: () => checkoutFreshChunk,\n clone: () => clone,\n commit: () => commit,\n currentBranch: () => currentBranch,\n default: () => cf_git_default,\n deleteBranch: () => deleteBranch,\n deleteRef: () => deleteRef,\n deleteRemote: () => deleteRemote,\n deleteTag: () => deleteTag,\n expandOid: () => expandOid,\n expandRef: () => expandRef,\n fastForward: () => fastForward,\n fetch: () => fetch2,\n findMergeBase: () => findMergeBase,\n findRoot: () => findRoot,\n getConfig: () => getConfig,\n getConfigAll: () => getConfigAll,\n getRemoteInfo: () => getRemoteInfo,\n getRemoteInfo2: () => getRemoteInfo2,\n hashBlob: () => hashBlob,\n indexPack: () => indexPack,\n init: () => init,\n isDescendent: () => isDescendent,\n isIgnored: () => isIgnored,\n listBranches: () => listBranches,\n listFiles: () => listFiles,\n listNotes: () => listNotes,\n listRefs: () => listRefs,\n listRemotes: () => listRemotes,\n listServerRefs: () => listServerRefs,\n listTags: () => listTags,\n log: () => log,\n merge: () => merge,\n packObjects: () => packObjects,\n pull: () => pull,\n push: () => push,\n readBlob: () => readBlob,\n readCommit: () => readCommit,\n readNote: () => readNote,\n readObject: () => readObject,\n readTag: () => readTag,\n readTree: () => readTree,\n remove: () => remove,\n removeNote: () => removeNote,\n renameBranch: () => renameBranch,\n resetIndex: () => resetIndex,\n resolveRef: () => resolveRef,\n setConfig: () => setConfig,\n stash: () => stash,\n status: () => status,\n statusMatrix: () => statusMatrix,\n tag: () => tag,\n updateIndex: () => updateIndex$1,\n version: () => version,\n walk: () => walk,\n writeBlob: () => writeBlob,\n writeCommit: () => writeCommit,\n writeObject: () => writeObject,\n writeRef: () => writeRef,\n writeTag: () => writeTag,\n writeTree: () => writeTree\n});\nvar import_crc_32 = __toESM(require_crc32(), 1);\nvar import_pako = __toESM(require_pako(), 1);\nvar import_pify = __toESM(require_pify(), 1);\nvar import_ignore = __toESM(require_ignore(), 1);\nvar import_clean_git_ref = __toESM(require_lib(), 1);\nvar import_is_git_ref_name_valid = __toESM(require_is_git_ref_name_valid(), 1);\nvar import_diff3 = __toESM(require_diff3(), 1);\nimport { createHash } from \"node:crypto\";\n\n// ../../node_modules/.bun/diff@5.2.2/node_modules/diff/lib/index.mjs\nfunction Diff() {\n}\nDiff.prototype = {\n diff: function diff(oldString, newString) {\n var _options$timeout;\n var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};\n var callback = options.callback;\n if (typeof options === \"function\") {\n callback = options;\n options = {};\n }\n this.options = options;\n var self = this;\n function done(value) {\n if (callback) {\n setTimeout(function() {\n callback(void 0, value);\n }, 0);\n return true;\n } else {\n return value;\n }\n }\n oldString = this.castInput(oldString);\n newString = this.castInput(newString);\n oldString = this.removeEmpty(this.tokenize(oldString));\n newString = this.removeEmpty(this.tokenize(newString));\n var newLen = newString.length, oldLen = oldString.length;\n var editLength = 1;\n var maxEditLength = newLen + oldLen;\n if (options.maxEditLength) {\n maxEditLength = Math.min(maxEditLength, options.maxEditLength);\n }\n var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity;\n var abortAfterTimestamp = Date.now() + maxExecutionTime;\n var bestPath = [{\n oldPos: -1,\n lastComponent: void 0\n }];\n var newPos = this.extractCommon(bestPath[0], newString, oldString, 0);\n if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n return done([{\n value: this.join(newString),\n count: newString.length\n }]);\n }\n var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;\n function execEditLength() {\n for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {\n var basePath = void 0;\n var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];\n if (removePath) {\n bestPath[diagonalPath - 1] = void 0;\n }\n var canAdd = false;\n if (addPath) {\n var addPathNewPos = addPath.oldPos - diagonalPath;\n canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;\n }\n var canRemove = removePath && removePath.oldPos + 1 < oldLen;\n if (!canAdd && !canRemove) {\n bestPath[diagonalPath] = void 0;\n continue;\n }\n if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) {\n basePath = self.addToPath(addPath, true, void 0, 0);\n } else {\n basePath = self.addToPath(removePath, void 0, true, 1);\n }\n newPos = self.extractCommon(basePath, newString, oldString, diagonalPath);\n if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken));\n } else {\n bestPath[diagonalPath] = basePath;\n if (basePath.oldPos + 1 >= oldLen) {\n maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);\n }\n if (newPos + 1 >= newLen) {\n minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);\n }\n }\n }\n editLength++;\n }\n if (callback) {\n (function exec() {\n setTimeout(function() {\n if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {\n return callback();\n }\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n })();\n } else {\n while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {\n var ret = execEditLength();\n if (ret) {\n return ret;\n }\n }\n }\n },\n addToPath: function addToPath(path, added, removed, oldPosInc) {\n var last = path.lastComponent;\n if (last && last.added === added && last.removed === removed) {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: {\n count: last.count + 1,\n added,\n removed,\n previousComponent: last.previousComponent\n }\n };\n } else {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: {\n count: 1,\n added,\n removed,\n previousComponent: last\n }\n };\n }\n },\n extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {\n var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {\n newPos++;\n oldPos++;\n commonCount++;\n }\n if (commonCount) {\n basePath.lastComponent = {\n count: commonCount,\n previousComponent: basePath.lastComponent\n };\n }\n basePath.oldPos = oldPos;\n return newPos;\n },\n equals: function equals(left, right) {\n if (this.options.comparator) {\n return this.options.comparator(left, right);\n } else {\n return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();\n }\n },\n removeEmpty: function removeEmpty(array) {\n var ret = [];\n for (var i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n return ret;\n },\n castInput: function castInput(value) {\n return value;\n },\n tokenize: function tokenize(value) {\n return value.split(\"\");\n },\n join: function join(chars) {\n return chars.join(\"\");\n }\n};\nfunction buildValues(diff2, lastComponent, newString, oldString, useLongestToken) {\n var components = [];\n var nextComponent;\n while (lastComponent) {\n components.push(lastComponent);\n nextComponent = lastComponent.previousComponent;\n delete lastComponent.previousComponent;\n lastComponent = nextComponent;\n }\n components.reverse();\n var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;\n for (; componentPos < componentLen; componentPos++) {\n var component = components[componentPos];\n if (!component.removed) {\n if (!component.added && useLongestToken) {\n var value = newString.slice(newPos, newPos + component.count);\n value = value.map(function(value2, i) {\n var oldValue = oldString[oldPos + i];\n return oldValue.length > value2.length ? oldValue : value2;\n });\n component.value = diff2.join(value);\n } else {\n component.value = diff2.join(newString.slice(newPos, newPos + component.count));\n }\n newPos += component.count;\n if (!component.added) {\n oldPos += component.count;\n }\n } else {\n component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));\n oldPos += component.count;\n if (componentPos && components[componentPos - 1].added) {\n var tmp = components[componentPos - 1];\n components[componentPos - 1] = components[componentPos];\n components[componentPos] = tmp;\n }\n }\n }\n var finalComponent = components[componentLen - 1];\n if (componentLen > 1 && typeof finalComponent.value === \"string\" && (finalComponent.added || finalComponent.removed) && diff2.equals(\"\", finalComponent.value)) {\n components[componentLen - 2].value += finalComponent.value;\n components.pop();\n }\n return components;\n}\nvar characterDiff = new Diff();\nvar extendedWordChars = /^[A-Za-z\\xC0-\\u02C6\\u02C8-\\u02D7\\u02DE-\\u02FF\\u1E00-\\u1EFF]+$/;\nvar reWhitespace = /\\S/;\nvar wordDiff = new Diff();\nwordDiff.equals = function(left, right) {\n if (this.options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);\n};\nwordDiff.tokenize = function(value) {\n var tokens = value.split(/([^\\S\\r\\n]+|[()[\\]{}'\"\\r\\n]|\\b)/);\n for (var i = 0; i < tokens.length - 1; i++) {\n if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {\n tokens[i] += tokens[i + 2];\n tokens.splice(i + 1, 2);\n i--;\n }\n }\n return tokens;\n};\nvar lineDiff = new Diff();\nlineDiff.tokenize = function(value) {\n if (this.options.stripTrailingCr) {\n value = value.replace(/\\r\\n/g, \"\\n\");\n }\n var retLines = [], linesAndNewlines = value.split(/(\\n|\\r\\n)/);\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n }\n for (var i = 0; i < linesAndNewlines.length; i++) {\n var line = linesAndNewlines[i];\n if (i % 2 && !this.options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n } else {\n if (this.options.ignoreWhitespace) {\n line = line.trim();\n }\n retLines.push(line);\n }\n }\n return retLines;\n};\nvar sentenceDiff = new Diff();\nsentenceDiff.tokenize = function(value) {\n return value.split(/(\\S.+?[.!?])(?=\\s+|$)/);\n};\nvar cssDiff = new Diff();\ncssDiff.tokenize = function(value) {\n return value.split(/([{}:;,]|\\s+)/);\n};\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function(obj2) {\n return typeof obj2;\n };\n } else {\n _typeof = function(obj2) {\n return obj2 && typeof Symbol === \"function\" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? \"symbol\" : typeof obj2;\n };\n }\n return _typeof(obj);\n}\nvar objectPrototypeToString = Object.prototype.toString;\nvar jsonDiff = new Diff();\njsonDiff.useLongestToken = true;\njsonDiff.tokenize = lineDiff.tokenize;\njsonDiff.castInput = function(value) {\n var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {\n return typeof v === \"undefined\" ? undefinedReplacement : v;\n } : _this$options$stringi;\n return typeof value === \"string\" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, \" \");\n};\njsonDiff.equals = function(left, right) {\n return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\\r\\n])/g, \"$1\"), right.replace(/,([\\r\\n])/g, \"$1\"));\n};\nfunction canonicalize(obj, stack, replacementStack, replacer, key) {\n stack = stack || [];\n replacementStack = replacementStack || [];\n if (replacer) {\n obj = replacer(key, obj);\n }\n var i;\n for (i = 0; i < stack.length; i += 1) {\n if (stack[i] === obj) {\n return replacementStack[i];\n }\n }\n var canonicalizedObj;\n if (\"[object Array]\" === objectPrototypeToString.call(obj)) {\n stack.push(obj);\n canonicalizedObj = new Array(obj.length);\n replacementStack.push(canonicalizedObj);\n for (i = 0; i < obj.length; i += 1) {\n canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);\n }\n stack.pop();\n replacementStack.pop();\n return canonicalizedObj;\n }\n if (obj && obj.toJSON) {\n obj = obj.toJSON();\n }\n if (_typeof(obj) === \"object\" && obj !== null) {\n stack.push(obj);\n canonicalizedObj = {};\n replacementStack.push(canonicalizedObj);\n var sortedKeys = [], _key;\n for (_key in obj) {\n if (obj.hasOwnProperty(_key)) {\n sortedKeys.push(_key);\n }\n }\n sortedKeys.sort();\n for (i = 0; i < sortedKeys.length; i += 1) {\n _key = sortedKeys[i];\n canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);\n }\n stack.pop();\n replacementStack.pop();\n } else {\n canonicalizedObj = obj;\n }\n return canonicalizedObj;\n}\nvar arrayDiff = new Diff();\narrayDiff.tokenize = function(value) {\n return value.slice();\n};\narrayDiff.join = arrayDiff.removeEmpty = function(value) {\n return value;\n};\n\n// ../../node_modules/.bun/@ashishkumar472+cf-git@1.0.5/node_modules/@ashishkumar472/cf-git/index.js\nvar AsyncLock = class {\n constructor(options = {}) {\n this.queues = /* @__PURE__ */ new Map();\n }\n async acquire(key, fn) {\n const lockKey = Array.isArray(key) ? key.join(\":\") : key;\n if (!this.queues.has(lockKey)) {\n this.queues.set(lockKey, []);\n }\n const queue = this.queues.get(lockKey);\n let resolveAcquire;\n const acquirePromise = new Promise((resolve) => {\n resolveAcquire = resolve;\n });\n queue.push(resolveAcquire);\n if (queue.length > 1) {\n await acquirePromise;\n }\n const release = () => {\n queue.shift();\n if (queue.length > 0) {\n queue[0]();\n } else {\n this.queues.delete(lockKey);\n }\n };\n if (typeof fn === \"function\") {\n try {\n return await fn();\n } finally {\n release();\n }\n }\n return release;\n }\n async run(key, fn) {\n return this.acquire(key, fn);\n }\n};\nvar BaseError = class _BaseError extends Error {\n constructor(message) {\n super(message);\n this.caller = \"\";\n }\n toJSON() {\n return {\n code: this.code,\n data: this.data,\n caller: this.caller,\n message: this.message,\n stack: this.stack\n };\n }\n fromJSON(json) {\n const e = new _BaseError(json.message);\n e.code = json.code;\n e.data = json.data;\n e.caller = json.caller;\n e.stack = json.stack;\n return e;\n }\n get isIsomorphicGitError() {\n return true;\n }\n};\nvar UnmergedPathsError = class _UnmergedPathsError extends BaseError {\n /**\n * @param {Array<string>} filepaths\n */\n constructor(filepaths) {\n super(\n `Modifying the index is not possible because you have unmerged files: ${filepaths.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`\n );\n this.code = this.name = _UnmergedPathsError.code;\n this.data = { filepaths };\n }\n};\nUnmergedPathsError.code = \"UnmergedPathsError\";\nvar InternalError = class _InternalError extends BaseError {\n /**\n * @param {string} message\n */\n constructor(message) {\n super(\n `An internal error caused this command to fail. Please file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${message}`\n );\n this.code = this.name = _InternalError.code;\n this.data = { message };\n }\n};\nInternalError.code = \"InternalError\";\nvar UnsafeFilepathError = class _UnsafeFilepathError extends BaseError {\n /**\n * @param {string} filepath\n */\n constructor(filepath) {\n super(`The filepath \"${filepath}\" contains unsafe character sequences`);\n this.code = this.name = _UnsafeFilepathError.code;\n this.data = { filepath };\n }\n};\nUnsafeFilepathError.code = \"UnsafeFilepathError\";\nvar BufferCursor = class {\n constructor(buffer) {\n this.buffer = buffer;\n this._start = 0;\n }\n eof() {\n return this._start >= this.buffer.length;\n }\n tell() {\n return this._start;\n }\n seek(n) {\n this._start = n;\n }\n slice(n) {\n const r = this.buffer.slice(this._start, this._start + n);\n this._start += n;\n return r;\n }\n toString(enc, length) {\n const r = this.buffer.toString(enc, this._start, this._start + length);\n this._start += length;\n return r;\n }\n write(value, length, enc) {\n const r = this.buffer.write(value, this._start, length, enc);\n this._start += length;\n return r;\n }\n copy(source, start, end) {\n const r = source.copy(this.buffer, this._start, start, end);\n this._start += r;\n return r;\n }\n readUInt8() {\n const r = this.buffer.readUInt8(this._start);\n this._start += 1;\n return r;\n }\n writeUInt8(value) {\n const r = this.buffer.writeUInt8(value, this._start);\n this._start += 1;\n return r;\n }\n readUInt16BE() {\n const r = this.buffer.readUInt16BE(this._start);\n this._start += 2;\n return r;\n }\n writeUInt16BE(value) {\n const r = this.buffer.writeUInt16BE(value, this._start);\n this._start += 2;\n return r;\n }\n readUInt32BE() {\n const r = this.buffer.readUInt32BE(this._start);\n this._start += 4;\n return r;\n }\n writeUInt32BE(value) {\n const r = this.buffer.writeUInt32BE(value, this._start);\n this._start += 4;\n return r;\n }\n};\nfunction compareStrings(a, b) {\n return -(a < b) || +(a > b);\n}\nfunction comparePath(a, b) {\n return compareStrings(a.path, b.path);\n}\nfunction normalizeMode(mode) {\n let type = mode > 0 ? mode >> 12 : 0;\n if (type !== 4 && type !== 8 && type !== 10 && type !== 14) {\n type = 8;\n }\n let permissions = mode & 511;\n if (permissions & 73) {\n permissions = 493;\n } else {\n permissions = 420;\n }\n if (type !== 8) permissions = 0;\n return (type << 12) + permissions;\n}\nvar MAX_UINT32 = 2 ** 32;\nfunction SecondsNanoseconds(givenSeconds, givenNanoseconds, milliseconds, date) {\n if (givenSeconds !== void 0 && givenNanoseconds !== void 0) {\n return [givenSeconds, givenNanoseconds];\n }\n if (milliseconds === void 0) {\n milliseconds = date.valueOf();\n }\n const seconds = Math.floor(milliseconds / 1e3);\n const nanoseconds = (milliseconds - seconds * 1e3) * 1e6;\n return [seconds, nanoseconds];\n}\nfunction normalizeStats(e) {\n const [ctimeSeconds, ctimeNanoseconds] = SecondsNanoseconds(\n e.ctimeSeconds,\n e.ctimeNanoseconds,\n e.ctimeMs,\n e.ctime\n );\n const [mtimeSeconds, mtimeNanoseconds] = SecondsNanoseconds(\n e.mtimeSeconds,\n e.mtimeNanoseconds,\n e.mtimeMs,\n e.mtime\n );\n return {\n ctimeSeconds: ctimeSeconds % MAX_UINT32,\n ctimeNanoseconds: ctimeNanoseconds % MAX_UINT32,\n mtimeSeconds: mtimeSeconds % MAX_UINT32,\n mtimeNanoseconds: mtimeNanoseconds % MAX_UINT32,\n dev: e.dev % MAX_UINT32,\n ino: e.ino % MAX_UINT32,\n mode: normalizeMode(e.mode % MAX_UINT32),\n uid: e.uid % MAX_UINT32,\n gid: e.gid % MAX_UINT32,\n // size of -1 happens over a BrowserFS HTTP Backend that doesn't serve Content-Length headers\n // (like the Karma webserver) because BrowserFS HTTP Backend uses HTTP HEAD requests to do fs.stat\n size: e.size > -1 ? e.size % MAX_UINT32 : 0\n };\n}\nfunction toHex(buffer) {\n let hex = \"\";\n for (const byte of new Uint8Array(buffer)) {\n if (byte < 16) hex += \"0\";\n hex += byte.toString(16);\n }\n return hex;\n}\nasync function shasum(buffer) {\n if (crypto.subtle.digestSync) {\n const hash2 = crypto.subtle.digestSync(\"SHA-1\", buffer);\n return toHex(hash2);\n }\n const hash = await crypto.subtle.digest(\"SHA-1\", buffer);\n return toHex(hash);\n}\nfunction parseCacheEntryFlags(bits) {\n return {\n assumeValid: Boolean(bits & 32768),\n extended: Boolean(bits & 16384),\n stage: (bits & 12288) >> 12,\n nameLength: bits & 4095\n };\n}\nfunction renderCacheEntryFlags(entry) {\n const flags = entry.flags;\n flags.extended = false;\n flags.nameLength = Math.min(Buffer.from(entry.path).length, 4095);\n return (flags.assumeValid ? 32768 : 0) + (flags.extended ? 16384 : 0) + ((flags.stage & 3) << 12) + (flags.nameLength & 4095);\n}\nvar GitIndex = class _GitIndex {\n /*::\n _entries: Map<string, CacheEntry>\n _dirty: boolean // Used to determine if index needs to be saved to filesystem\n */\n constructor(entries, unmergedPaths) {\n this._dirty = false;\n this._unmergedPaths = unmergedPaths || /* @__PURE__ */ new Set();\n this._entries = entries || /* @__PURE__ */ new Map();\n }\n _addEntry(entry) {\n if (entry.flags.stage === 0) {\n entry.stages = [entry];\n this._entries.set(entry.path, entry);\n this._unmergedPaths.delete(entry.path);\n } else {\n let existingEntry = this._entries.get(entry.path);\n if (!existingEntry) {\n this._entries.set(entry.path, entry);\n existingEntry = entry;\n }\n existingEntry.stages[entry.flags.stage] = entry;\n this._unmergedPaths.add(entry.path);\n }\n }\n static async from(buffer) {\n if (Buffer.isBuffer(buffer)) {\n return _GitIndex.fromBuffer(buffer);\n } else if (buffer === null) {\n return new _GitIndex(null);\n } else {\n throw new InternalError(\"invalid type passed to GitIndex.from\");\n }\n }\n static async fromBuffer(buffer) {\n if (buffer.length === 0) {\n throw new InternalError(\"Index file is empty (.git/index)\");\n }\n const index3 = new _GitIndex();\n const reader = new BufferCursor(buffer);\n const magic = reader.toString(\"utf8\", 4);\n if (magic !== \"DIRC\") {\n throw new InternalError(`Invalid dircache magic file number: ${magic}`);\n }\n const shaComputed = await shasum(buffer.slice(0, -20));\n const shaClaimed = buffer.slice(-20).toString(\"hex\");\n if (shaClaimed !== shaComputed) {\n throw new InternalError(\n `Invalid checksum in GitIndex buffer: expected ${shaClaimed} but saw ${shaComputed}`\n );\n }\n const version2 = reader.readUInt32BE();\n if (version2 !== 2) {\n throw new InternalError(`Unsupported dircache version: ${version2}`);\n }\n const numEntries = reader.readUInt32BE();\n let i = 0;\n while (!reader.eof() && i < numEntries) {\n const entry = {};\n entry.ctimeSeconds = reader.readUInt32BE();\n entry.ctimeNanoseconds = reader.readUInt32BE();\n entry.mtimeSeconds = reader.readUInt32BE();\n entry.mtimeNanoseconds = reader.readUInt32BE();\n entry.dev = reader.readUInt32BE();\n entry.ino = reader.readUInt32BE();\n entry.mode = reader.readUInt32BE();\n entry.uid = reader.readUInt32BE();\n entry.gid = reader.readUInt32BE();\n entry.size = reader.readUInt32BE();\n entry.oid = reader.slice(20).toString(\"hex\");\n const flags = reader.readUInt16BE();\n entry.flags = parseCacheEntryFlags(flags);\n const pathlength = buffer.indexOf(0, reader.tell() + 1) - reader.tell();\n if (pathlength < 1) {\n throw new InternalError(`Got a path length of: ${pathlength}`);\n }\n entry.path = reader.toString(\"utf8\", pathlength);\n if (entry.path.includes(\"..\\\\\") || entry.path.includes(\"../\")) {\n throw new UnsafeFilepathError(entry.path);\n }\n let padding = 8 - (reader.tell() - 12) % 8;\n if (padding === 0) padding = 8;\n while (padding--) {\n const tmp = reader.readUInt8();\n if (tmp !== 0) {\n throw new InternalError(\n `Expected 1-8 null characters but got '${tmp}' after ${entry.path}`\n );\n } else if (reader.eof()) {\n throw new InternalError(\"Unexpected end of file\");\n }\n }\n entry.stages = [];\n index3._addEntry(entry);\n i++;\n }\n return index3;\n }\n get unmergedPaths() {\n return [...this._unmergedPaths];\n }\n get entries() {\n return [...this._entries.values()].sort(comparePath);\n }\n get entriesMap() {\n return this._entries;\n }\n get entriesFlat() {\n return [...this.entries].flatMap((entry) => {\n return entry.stages.length > 1 ? entry.stages.filter((x) => x) : entry;\n });\n }\n *[Symbol.iterator]() {\n for (const entry of this.entries) {\n yield entry;\n }\n }\n insert({ filepath, stats, oid, stage = 0 }) {\n if (!stats) {\n stats = {\n ctimeSeconds: 0,\n ctimeNanoseconds: 0,\n mtimeSeconds: 0,\n mtimeNanoseconds: 0,\n dev: 0,\n ino: 0,\n mode: 0,\n uid: 0,\n gid: 0,\n size: 0\n };\n }\n stats = normalizeStats(stats);\n const bfilepath = Buffer.from(filepath);\n const entry = {\n ctimeSeconds: stats.ctimeSeconds,\n ctimeNanoseconds: stats.ctimeNanoseconds,\n mtimeSeconds: stats.mtimeSeconds,\n mtimeNanoseconds: stats.mtimeNanoseconds,\n dev: stats.dev,\n ino: stats.ino,\n // We provide a fallback value for `mode` here because not all fs\n // implementations assign it, but we use it in GitTree.\n // '100644' is for a \"regular non-executable file\"\n mode: stats.mode || 33188,\n uid: stats.uid,\n gid: stats.gid,\n size: stats.size,\n path: filepath,\n oid,\n flags: {\n assumeValid: false,\n extended: false,\n stage,\n nameLength: bfilepath.length < 4095 ? bfilepath.length : 4095\n },\n stages: []\n };\n this._addEntry(entry);\n this._dirty = true;\n }\n delete({ filepath }) {\n if (this._entries.has(filepath)) {\n this._entries.delete(filepath);\n } else {\n for (const key of this._entries.keys()) {\n if (key.startsWith(filepath + \"/\")) {\n this._entries.delete(key);\n }\n }\n }\n if (this._unmergedPaths.has(filepath)) {\n this._unmergedPaths.delete(filepath);\n }\n this._dirty = true;\n }\n clear() {\n this._entries.clear();\n this._dirty = true;\n }\n has({ filepath }) {\n return this._entries.has(filepath);\n }\n render() {\n return this.entries.map((entry) => `${entry.mode.toString(8)} ${entry.oid} ${entry.path}`).join(\"\\n\");\n }\n static async _entryToBuffer(entry) {\n const bpath = Buffer.from(entry.path);\n const length = Math.ceil((62 + bpath.length + 1) / 8) * 8;\n const written = Buffer.alloc(length);\n const writer = new BufferCursor(written);\n const stat = normalizeStats(entry);\n writer.writeUInt32BE(stat.ctimeSeconds);\n writer.writeUInt32BE(stat.ctimeNanoseconds);\n writer.writeUInt32BE(stat.mtimeSeconds);\n writer.writeUInt32BE(stat.mtimeNanoseconds);\n writer.writeUInt32BE(stat.dev);\n writer.writeUInt32BE(stat.ino);\n writer.writeUInt32BE(stat.mode);\n writer.writeUInt32BE(stat.uid);\n writer.writeUInt32BE(stat.gid);\n writer.writeUInt32BE(stat.size);\n writer.write(entry.oid, 20, \"hex\");\n writer.writeUInt16BE(renderCacheEntryFlags(entry));\n writer.write(entry.path, bpath.length, \"utf8\");\n return written;\n }\n async toObject({ entries = this.entries } = {}) {\n const header = Buffer.alloc(12);\n const writer = new BufferCursor(header);\n writer.write(\"DIRC\", 4, \"utf8\");\n writer.writeUInt32BE(2);\n writer.writeUInt32BE(entries.reduce(\n (count, entry) => count + (entry.stages.length > 1 ? entry.stages.filter(Boolean).length : 1),\n 0\n ));\n let entryBuffers = [];\n for (const entry of entries) {\n entryBuffers.push(_GitIndex._entryToBuffer(entry));\n if (entry.stages.length > 1) {\n for (const stage of entry.stages) {\n if (stage && stage !== entry) {\n entryBuffers.push(_GitIndex._entryToBuffer(stage));\n }\n }\n }\n }\n entryBuffers = await Promise.all(entryBuffers);\n const body = Buffer.concat(entryBuffers);\n const main = Buffer.concat([header, body]);\n const sum = await shasum(main);\n return Buffer.concat([main, Buffer.from(sum, \"hex\")]);\n }\n};\nfunction compareStats(entry, stats, filemode = true, trustino = true) {\n const e = normalizeStats(entry);\n const s = normalizeStats(stats);\n const staleness = filemode && e.mode !== s.mode || e.mtimeSeconds !== s.mtimeSeconds || e.ctimeSeconds !== s.ctimeSeconds || e.uid !== s.uid || e.gid !== s.gid || trustino && e.ino !== s.ino || e.size !== s.size;\n return staleness;\n}\nvar lock = null;\nvar IndexCache = /* @__PURE__ */ Symbol(\"IndexCache\");\nfunction createCache() {\n return {\n map: /* @__PURE__ */ new Map(),\n stats: /* @__PURE__ */ new Map()\n };\n}\nasync function updateCachedIndexFile(fs, filepath, cache) {\n const [stat, rawIndexFile] = await Promise.all([\n fs.lstat(filepath),\n fs.read(filepath)\n ]);\n const index3 = await GitIndex.from(rawIndexFile);\n cache.map.set(filepath, index3);\n cache.stats.set(filepath, stat);\n}\nasync function isIndexStale(fs, filepath, cache) {\n const savedStats = cache.stats.get(filepath);\n if (savedStats === void 0) return true;\n if (savedStats === null) return false;\n const currStats = await fs.lstat(filepath);\n if (currStats === null) return false;\n return compareStats(savedStats, currStats);\n}\nvar GitIndexManager = class {\n /**\n * Manages access to the Git index file, ensuring thread-safe operations and caching.\n *\n * @param {object} opts - Options for acquiring the Git index.\n * @param {FSClient} opts.fs - A file system implementation.\n * @param {string} opts.gitdir - The path to the `.git` directory.\n * @param {object} opts.cache - A shared cache object for storing index data.\n * @param {boolean} [opts.allowUnmerged=true] - Whether to allow unmerged paths in the index.\n * @param {boolean} [opts.trustIndexCache=false] - Skip the stat check when the caller exclusively owns index mutation.\n * @param {function(GitIndex): any} closure - A function to execute with the Git index.\n * @returns {Promise<any>} The result of the closure function.\n * @throws {UnmergedPathsError} If unmerged paths exist and `allowUnmerged` is `false`.\n */\n static async acquire({ fs, gitdir, cache, allowUnmerged = true, trustIndexCache = false }, closure) {\n if (!cache[IndexCache]) {\n cache[IndexCache] = createCache();\n }\n const filepath = `${gitdir}/index`;\n if (lock === null) lock = new AsyncLock({ maxPending: Infinity });\n let result;\n let unmergedPaths = [];\n await lock.acquire(filepath, async () => {\n const theIndexCache = cache[IndexCache];\n if (!theIndexCache.map.has(filepath) || !trustIndexCache && await isIndexStale(fs, filepath, theIndexCache)) {\n await updateCachedIndexFile(fs, filepath, theIndexCache);\n }\n const index3 = theIndexCache.map.get(filepath);\n unmergedPaths = index3.unmergedPaths;\n if (unmergedPaths.length && !allowUnmerged)\n throw new UnmergedPathsError(unmergedPaths);\n result = await closure(index3);\n if (index3._dirty) {\n const buffer = await index3.toObject();\n await fs.write(filepath, buffer);\n theIndexCache.stats.set(filepath, await fs.lstat(filepath));\n index3._dirty = false;\n }\n });\n return result;\n }\n static async acquireFreshCheckout({ fs, gitdir, priorChunks, priorEntries, deferFragmentCleanup }, closure) {\n const chunkIndex = new GitIndex();\n const result = await closure(chunkIndex);\n const chunkEntries = chunkIndex.entries;\n const indexEntries = priorEntries + chunkEntries.length;\n const fragmentDir = `${gitdir}/nimbus-checkout-index`;\n if (!result.complete) {\n await fs.mkdir(fragmentDir);\n await fs.write(\n `${fragmentDir}/${String(priorChunks).padStart(8, \"0\")}`,\n await chunkIndex.toObject({ entries: chunkEntries })\n );\n return { result, indexEntries };\n }\n const index3 = new GitIndex();\n let durableEntries = 0;\n const collected = [];\n for (let chunk = 0; chunk < priorChunks; chunk++) {\n const fragmentPath = `${fragmentDir}/${String(chunk).padStart(8, \"0\")}`;\n const fragmentBuffer = await fs.read(fragmentPath);\n if (fragmentBuffer === null) {\n throw new InternalError(`Fresh checkout: missing index fragment ${chunk}`);\n }\n const fragment = await GitIndex.from(fragmentBuffer);\n const fragmentEntries = fragment.entries;\n durableEntries += fragmentEntries.length;\n collected.push(...fragmentEntries);\n }\n if (durableEntries !== priorEntries) {\n throw new InternalError(\n `Fresh checkout: index fragments contain ${durableEntries} entries, expected ${priorEntries}`\n );\n }\n collected.push(...chunkEntries);\n collected.sort(comparePath);\n let previousEntry = null;\n for (const entry of collected) {\n if (previousEntry !== null && comparePath(previousEntry, entry) >= 0) {\n throw new InternalError(`Fresh checkout: duplicate index entry ${entry.path}`);\n }\n index3._addEntry(entry);\n previousEntry = entry;\n }\n await fs.write(\n `${gitdir}/index`,\n await index3.toObject({ entries: [...index3._entries.values()] })\n );\n if (priorChunks > 0 && !deferFragmentCleanup) {\n await fs.rmdir(fragmentDir, { recursive: true });\n }\n return { result, indexEntries };\n }\n};\nfunction basename(path) {\n const last = Math.max(path.lastIndexOf(\"/\"), path.lastIndexOf(\"\\\\\"));\n if (last > -1) {\n path = path.slice(last + 1);\n }\n return path;\n}\nfunction dirname(path) {\n const last = Math.max(path.lastIndexOf(\"/\"), path.lastIndexOf(\"\\\\\"));\n if (last === -1) return \".\";\n if (last === 0) return \"/\";\n return path.slice(0, last);\n}\nfunction flatFileListToDirectoryStructure(files) {\n const inodes = /* @__PURE__ */ new Map();\n const mkdir = function(name) {\n if (!inodes.has(name)) {\n const dir = {\n type: \"tree\",\n fullpath: name,\n basename: basename(name),\n metadata: {},\n children: []\n };\n inodes.set(name, dir);\n dir.parent = mkdir(dirname(name));\n if (dir.parent && dir.parent !== dir) dir.parent.children.push(dir);\n }\n return inodes.get(name);\n };\n const mkfile = function(name, metadata) {\n if (!inodes.has(name)) {\n const file = {\n type: \"blob\",\n fullpath: name,\n basename: basename(name),\n metadata,\n // This recursively generates any missing parent folders.\n parent: mkdir(dirname(name)),\n children: []\n };\n if (file.parent) file.parent.children.push(file);\n inodes.set(name, file);\n }\n return inodes.get(name);\n };\n mkdir(\".\");\n for (const file of files) {\n mkfile(file.path, file);\n }\n return inodes;\n}\nfunction mode2type(mode) {\n switch (mode) {\n case 16384:\n return \"tree\";\n case 33188:\n return \"blob\";\n case 33261:\n return \"blob\";\n case 40960:\n return \"blob\";\n case 57344:\n return \"commit\";\n }\n throw new InternalError(`Unexpected GitTree entry mode: ${mode.toString(8)}`);\n}\nvar GitWalkerIndex = class {\n constructor({ fs, gitdir, cache }) {\n this.treePromise = GitIndexManager.acquire(\n { fs, gitdir, cache },\n async function(index3) {\n return flatFileListToDirectoryStructure(index3.entries);\n }\n );\n const walker = this;\n this.ConstructEntry = class StageEntry {\n constructor(fullpath) {\n this._fullpath = fullpath;\n this._type = false;\n this._mode = false;\n this._stat = false;\n this._oid = false;\n }\n async type() {\n return walker.type(this);\n }\n async mode() {\n return walker.mode(this);\n }\n async stat() {\n return walker.stat(this);\n }\n async content() {\n return walker.content(this);\n }\n async oid() {\n return walker.oid(this);\n }\n };\n }\n async readdir(entry) {\n const filepath = entry._fullpath;\n const tree = await this.treePromise;\n const inode = tree.get(filepath);\n if (!inode) return null;\n if (inode.type === \"blob\") return null;\n if (inode.type !== \"tree\") {\n throw new Error(`ENOTDIR: not a directory, scandir '${filepath}'`);\n }\n const names = inode.children.map((inode2) => inode2.fullpath);\n names.sort(compareStrings);\n return names;\n }\n async type(entry) {\n if (entry._type === false) {\n await entry.stat();\n }\n return entry._type;\n }\n async mode(entry) {\n if (entry._mode === false) {\n await entry.stat();\n }\n return entry._mode;\n }\n async stat(entry) {\n if (entry._stat === false) {\n const tree = await this.treePromise;\n const inode = tree.get(entry._fullpath);\n if (!inode) {\n throw new Error(\n `ENOENT: no such file or directory, lstat '${entry._fullpath}'`\n );\n }\n const stats = inode.type === \"tree\" ? {} : normalizeStats(inode.metadata);\n entry._type = inode.type === \"tree\" ? \"tree\" : mode2type(stats.mode);\n entry._mode = stats.mode;\n if (inode.type === \"tree\") {\n entry._stat = void 0;\n } else {\n entry._stat = stats;\n }\n }\n return entry._stat;\n }\n async content(_entry) {\n }\n async oid(entry) {\n if (entry._oid === false) {\n const tree = await this.treePromise;\n const inode = tree.get(entry._fullpath);\n entry._oid = inode.metadata.oid;\n }\n return entry._oid;\n }\n};\nvar GitWalkSymbol = /* @__PURE__ */ Symbol(\"GitWalkSymbol\");\nfunction STAGE() {\n const o = /* @__PURE__ */ Object.create(null);\n Object.defineProperty(o, GitWalkSymbol, {\n value: function({ fs, gitdir, cache }) {\n return new GitWalkerIndex({ fs, gitdir, cache });\n }\n });\n Object.freeze(o);\n return o;\n}\nvar NotFoundError = class _NotFoundError extends BaseError {\n /**\n * @param {string} what\n */\n constructor(what) {\n super(`Could not find ${what}.`);\n this.code = this.name = _NotFoundError.code;\n this.data = { what };\n }\n};\nNotFoundError.code = \"NotFoundError\";\nvar ObjectTypeError = class _ObjectTypeError extends BaseError {\n /**\n * @param {string} oid\n * @param {'blob'|'commit'|'tag'|'tree'} actual\n * @param {'blob'|'commit'|'tag'|'tree'} expected\n * @param {string} [filepath]\n */\n constructor(oid, actual, expected, filepath) {\n super(\n `Object ${oid} ${filepath ? `at ${filepath}` : \"\"}was anticipated to be a ${expected} but it is a ${actual}.`\n );\n this.code = this.name = _ObjectTypeError.code;\n this.data = { oid, actual, expected, filepath };\n }\n};\nObjectTypeError.code = \"ObjectTypeError\";\nvar InvalidOidError = class _InvalidOidError extends BaseError {\n /**\n * @param {string} value\n */\n constructor(value) {\n super(`Expected a 40-char hex object id but saw \"${value}\".`);\n this.code = this.name = _InvalidOidError.code;\n this.data = { value };\n }\n};\nInvalidOidError.code = \"InvalidOidError\";\nvar NoRefspecError = class _NoRefspecError extends BaseError {\n /**\n * @param {string} remote\n */\n constructor(remote) {\n super(`Could not find a fetch refspec for remote \"${remote}\". Make sure the config file has an entry like the following:\n[remote \"${remote}\"]\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n`);\n this.code = this.name = _NoRefspecError.code;\n this.data = { remote };\n }\n};\nNoRefspecError.code = \"NoRefspecError\";\nvar GitPackedRefs = class _GitPackedRefs {\n constructor(text) {\n this.refs = /* @__PURE__ */ new Map();\n this.parsedConfig = [];\n if (text) {\n let key = null;\n this.parsedConfig = text.trim().split(\"\\n\").map((line) => {\n if (/^\\s*#/.test(line)) {\n return { line, comment: true };\n }\n const i = line.indexOf(\" \");\n if (line.startsWith(\"^\")) {\n const value = line.slice(1);\n this.refs.set(key + \"^{}\", value);\n return { line, ref: key, peeled: value };\n } else {\n const value = line.slice(0, i);\n key = line.slice(i + 1);\n this.refs.set(key, value);\n return { line, ref: key, oid: value };\n }\n });\n }\n return this;\n }\n static from(text) {\n return new _GitPackedRefs(text);\n }\n delete(ref) {\n this.parsedConfig = this.parsedConfig.filter((entry) => entry.ref !== ref);\n this.refs.delete(ref);\n }\n toString() {\n return this.parsedConfig.map(({ line }) => line).join(\"\\n\") + \"\\n\";\n }\n};\nvar GitRefSpec = class _GitRefSpec {\n constructor({ remotePath, localPath, force, matchPrefix }) {\n Object.assign(this, {\n remotePath,\n localPath,\n force,\n matchPrefix\n });\n }\n static from(refspec) {\n const [\n forceMatch,\n remotePath,\n remoteGlobMatch,\n localPath,\n localGlobMatch\n ] = refspec.match(/^(\\+?)(.*?)(\\*?):(.*?)(\\*?)$/).slice(1);\n const force = forceMatch === \"+\";\n const remoteIsGlob = remoteGlobMatch === \"*\";\n const localIsGlob = localGlobMatch === \"*\";\n if (remoteIsGlob !== localIsGlob) {\n throw new InternalError(\"Invalid refspec\");\n }\n return new _GitRefSpec({\n remotePath,\n localPath,\n force,\n matchPrefix: remoteIsGlob\n });\n }\n translate(remoteBranch) {\n if (this.matchPrefix) {\n if (remoteBranch.startsWith(this.remotePath)) {\n return this.localPath + remoteBranch.replace(this.remotePath, \"\");\n }\n } else {\n if (remoteBranch === this.remotePath) return this.localPath;\n }\n return null;\n }\n reverseTranslate(localBranch) {\n if (this.matchPrefix) {\n if (localBranch.startsWith(this.localPath)) {\n return this.remotePath + localBranch.replace(this.localPath, \"\");\n }\n } else {\n if (localBranch === this.localPath) return this.remotePath;\n }\n return null;\n }\n};\nvar GitRefSpecSet = class _GitRefSpecSet {\n constructor(rules = []) {\n this.rules = rules;\n }\n static from(refspecs) {\n const rules = [];\n for (const refspec of refspecs) {\n rules.push(GitRefSpec.from(refspec));\n }\n return new _GitRefSpecSet(rules);\n }\n add(refspec) {\n const rule = GitRefSpec.from(refspec);\n this.rules.push(rule);\n }\n translate(remoteRefs) {\n const result = [];\n for (const rule of this.rules) {\n for (const remoteRef of remoteRefs) {\n const localRef = rule.translate(remoteRef);\n if (localRef) {\n result.push([remoteRef, localRef]);\n }\n }\n }\n return result;\n }\n translateOne(remoteRef) {\n let result = null;\n for (const rule of this.rules) {\n const localRef = rule.translate(remoteRef);\n if (localRef) {\n result = localRef;\n }\n }\n return result;\n }\n localNamespaces() {\n return this.rules.filter((rule) => rule.matchPrefix).map((rule) => rule.localPath.replace(/\\/$/, \"\"));\n }\n};\nfunction compareRefNames(a, b) {\n const _a = a.replace(/\\^\\{\\}$/, \"\");\n const _b = b.replace(/\\^\\{\\}$/, \"\");\n const tmp = -(_a < _b) || +(_a > _b);\n if (tmp === 0) {\n return a.endsWith(\"^{}\") ? 1 : -1;\n }\n return tmp;\n}\nfunction join2(...paths) {\n if (paths.length === 0) return \".\";\n let joined;\n for (let i = 0; i < paths.length; i++) {\n const arg = paths[i];\n if (arg && typeof arg === \"string\" && arg.length > 0) {\n if (joined === void 0) {\n joined = arg;\n } else {\n const cleanArg = arg.charCodeAt(0) === 47 ? arg.slice(1) : arg;\n if (cleanArg.length > 0) {\n joined += \"/\" + cleanArg;\n }\n }\n }\n }\n if (joined === void 0) return \".\";\n return normalize(joined);\n}\nfunction normalize(path) {\n if (path.length === 0) return \".\";\n const isAbsolute = path.charCodeAt(0) === 47;\n const trailingSlash = path.charCodeAt(path.length - 1) === 47;\n const segments = [];\n let current = \"\";\n for (let i = 0; i <= path.length; i++) {\n const code = i < path.length ? path.charCodeAt(i) : 47;\n if (code === 47) {\n if (current.length === 0) {\n continue;\n } else if (current === \".\") {\n current = \"\";\n continue;\n } else if (current === \"..\") {\n if (segments.length > 0 && segments[segments.length - 1] !== \"..\") {\n segments.pop();\n } else if (!isAbsolute) {\n segments.push(\"..\");\n }\n current = \"\";\n continue;\n }\n segments.push(current);\n current = \"\";\n } else {\n current += path[i];\n }\n }\n let result = segments.join(\"/\");\n if (isAbsolute) {\n result = \"/\" + result;\n }\n if (trailingSlash && result.length > 1) {\n result += \"/\";\n }\n if (result.length === 0) {\n return \".\";\n }\n return result;\n}\nvar num = (val) => {\n if (typeof val === \"number\") {\n return val;\n }\n val = val.toLowerCase();\n let n = parseInt(val);\n if (val.endsWith(\"k\")) n *= 1024;\n if (val.endsWith(\"m\")) n *= 1024 * 1024;\n if (val.endsWith(\"g\")) n *= 1024 * 1024 * 1024;\n return n;\n};\nvar bool = (val) => {\n if (typeof val === \"boolean\") {\n return val;\n }\n val = val.trim().toLowerCase();\n if (val === \"true\" || val === \"yes\" || val === \"on\") return true;\n if (val === \"false\" || val === \"no\" || val === \"off\") return false;\n throw Error(\n `Expected 'true', 'false', 'yes', 'no', 'on', or 'off', but got ${val}`\n );\n};\nvar schema = {\n core: {\n filemode: bool,\n bare: bool,\n logallrefupdates: bool,\n symlinks: bool,\n ignorecase: bool,\n bigFileThreshold: num\n }\n};\nvar SECTION_LINE_REGEX = /^\\[([A-Za-z0-9-.]+)(?: \"(.*)\")?\\]$/;\nvar SECTION_REGEX = /^[A-Za-z0-9-.]+$/;\nvar VARIABLE_LINE_REGEX = /^([A-Za-z][A-Za-z-]*)(?: *= *(.*))?$/;\nvar VARIABLE_NAME_REGEX = /^[A-Za-z][A-Za-z-]*$/;\nvar VARIABLE_VALUE_COMMENT_REGEX = /^(.*?)( *[#;].*)$/;\nvar extractSectionLine = (line) => {\n const matches = SECTION_LINE_REGEX.exec(line);\n if (matches != null) {\n const [section, subsection] = matches.slice(1);\n return [section, subsection];\n }\n return null;\n};\nvar extractVariableLine = (line) => {\n const matches = VARIABLE_LINE_REGEX.exec(line);\n if (matches != null) {\n const [name, rawValue = \"true\"] = matches.slice(1);\n const valueWithoutComments = removeComments(rawValue);\n const valueWithoutQuotes = removeQuotes(valueWithoutComments);\n return [name, valueWithoutQuotes];\n }\n return null;\n};\nvar removeComments = (rawValue) => {\n const commentMatches = VARIABLE_VALUE_COMMENT_REGEX.exec(rawValue);\n if (commentMatches == null) {\n return rawValue;\n }\n const [valueWithoutComment, comment] = commentMatches.slice(1);\n if (hasOddNumberOfQuotes(valueWithoutComment) && hasOddNumberOfQuotes(comment)) {\n return `${valueWithoutComment}${comment}`;\n }\n return valueWithoutComment;\n};\nvar hasOddNumberOfQuotes = (text) => {\n const numberOfQuotes = (text.match(/(?:^|[^\\\\])\"/g) || []).length;\n return numberOfQuotes % 2 !== 0;\n};\nvar removeQuotes = (text) => {\n return text.split(\"\").reduce((newText, c, idx, text2) => {\n const isQuote = c === '\"' && text2[idx - 1] !== \"\\\\\";\n const isEscapeForQuote = c === \"\\\\\" && text2[idx + 1] === '\"';\n if (isQuote || isEscapeForQuote) {\n return newText;\n }\n return newText + c;\n }, \"\");\n};\nvar lower = (text) => {\n return text != null ? text.toLowerCase() : null;\n};\nvar getPath = (section, subsection, name) => {\n return [lower(section), subsection, lower(name)].filter((a) => a != null).join(\".\");\n};\nvar normalizePath = (path) => {\n const pathSegments = path.split(\".\");\n const section = pathSegments.shift();\n const name = pathSegments.pop();\n const subsection = pathSegments.length ? pathSegments.join(\".\") : void 0;\n return {\n section,\n subsection,\n name,\n path: getPath(section, subsection, name),\n sectionPath: getPath(section, subsection, null),\n isSection: !!section\n };\n};\nvar findLastIndex = (array, callback) => {\n return array.reduce((lastIndex, item, index3) => {\n return callback(item) ? index3 : lastIndex;\n }, -1);\n};\nvar GitConfig = class _GitConfig {\n constructor(text) {\n let section = null;\n let subsection = null;\n this.parsedConfig = text ? text.split(\"\\n\").map((line) => {\n let name = null;\n let value = null;\n const trimmedLine = line.trim();\n const extractedSection = extractSectionLine(trimmedLine);\n const isSection = extractedSection != null;\n if (isSection) {\n ;\n [section, subsection] = extractedSection;\n } else {\n const extractedVariable = extractVariableLine(trimmedLine);\n const isVariable = extractedVariable != null;\n if (isVariable) {\n ;\n [name, value] = extractedVariable;\n }\n }\n const path = getPath(section, subsection, name);\n return { line, isSection, section, subsection, name, value, path };\n }) : [];\n }\n static from(text) {\n return new _GitConfig(text);\n }\n async get(path, getall = false) {\n const normalizedPath = normalizePath(path).path;\n const allValues = this.parsedConfig.filter((config) => config.path === normalizedPath).map(({ section, name, value }) => {\n const fn = schema[section] && schema[section][name];\n return fn ? fn(value) : value;\n });\n return getall ? allValues : allValues.pop();\n }\n async getall(path) {\n return this.get(path, true);\n }\n async getSubsections(section) {\n return this.parsedConfig.filter((config) => config.isSection && config.section === section).map((config) => config.subsection);\n }\n async deleteSection(section, subsection) {\n this.parsedConfig = this.parsedConfig.filter(\n (config) => !(config.section === section && config.subsection === subsection)\n );\n }\n async append(path, value) {\n return this.set(path, value, true);\n }\n async set(path, value, append = false) {\n const {\n section,\n subsection,\n name,\n path: normalizedPath,\n sectionPath,\n isSection\n } = normalizePath(path);\n const configIndex = findLastIndex(\n this.parsedConfig,\n (config) => config.path === normalizedPath\n );\n if (value == null) {\n if (configIndex !== -1) {\n this.parsedConfig.splice(configIndex, 1);\n }\n } else {\n if (configIndex !== -1) {\n const config = this.parsedConfig[configIndex];\n const modifiedConfig = Object.assign({}, config, {\n name,\n value,\n modified: true\n });\n if (append) {\n this.parsedConfig.splice(configIndex + 1, 0, modifiedConfig);\n } else {\n this.parsedConfig[configIndex] = modifiedConfig;\n }\n } else {\n const sectionIndex = this.parsedConfig.findIndex(\n (config) => config.path === sectionPath\n );\n const newConfig = {\n section,\n subsection,\n name,\n value,\n modified: true,\n path: normalizedPath\n };\n if (SECTION_REGEX.test(section) && VARIABLE_NAME_REGEX.test(name)) {\n if (sectionIndex >= 0) {\n this.parsedConfig.splice(sectionIndex + 1, 0, newConfig);\n } else {\n const newSection = {\n isSection,\n section,\n subsection,\n modified: true,\n path: sectionPath\n };\n this.parsedConfig.push(newSection, newConfig);\n }\n }\n }\n }\n }\n toString() {\n return this.parsedConfig.map(({ line, section, subsection, name, value, modified: modified2 = false }) => {\n if (!modified2) {\n return line;\n }\n if (name != null && value != null) {\n if (typeof value === \"string\" && /[#;]/.test(value)) {\n return `\t${name} = \"${value}\"`;\n }\n return `\t${name} = ${value}`;\n }\n if (subsection != null) {\n return `[${section} \"${subsection}\"]`;\n }\n return `[${section}]`;\n }).join(\"\\n\");\n }\n};\nvar GitConfigManager = class {\n /**\n * Reads the Git configuration file from the specified `.git` directory.\n *\n * @param {object} opts - Options for reading the Git configuration.\n * @param {FSClient} opts.fs - A file system implementation.\n * @param {string} opts.gitdir - The path to the `.git` directory.\n * @returns {Promise<GitConfig>} A `GitConfig` object representing the parsed configuration.\n */\n static async get({ fs, gitdir }) {\n const text = await fs.read(`${gitdir}/config`, { encoding: \"utf8\" });\n return GitConfig.from(text);\n }\n /**\n * Saves the provided Git configuration to the specified `.git` directory.\n *\n * @param {object} opts - Options for saving the Git configuration.\n * @param {FSClient} opts.fs - A file system implementation.\n * @param {string} opts.gitdir - The path to the `.git` directory.\n * @param {GitConfig} opts.config - The `GitConfig` object to save.\n * @returns {Promise<void>} Resolves when the configuration has been successfully saved.\n */\n static async save({ fs, gitdir, config }) {\n await fs.write(`${gitdir}/config`, config.toString(), {\n encoding: \"utf8\"\n });\n }\n};\nvar refpaths = (ref) => [\n `${ref}`,\n `refs/${ref}`,\n `refs/tags/${ref}`,\n `refs/heads/${ref}`,\n `refs/remotes/${ref}`,\n `refs/remotes/${ref}/HEAD`\n];\nvar GIT_FILES = [\"config\", \"description\", \"index\", \"shallow\", \"commondir\"];\nvar lock$1;\nasync function acquireLock(ref, callback) {\n if (lock$1 === void 0) lock$1 = new AsyncLock();\n return lock$1.run(ref, callback);\n}\nvar GitRefManager = class _GitRefManager {\n /**\n * Updates remote refs based on the provided refspecs and options.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.remote - The name of the remote.\n * @param {Map<string, string>} args.refs - A map of refs to their object IDs.\n * @param {Map<string, string>} args.symrefs - A map of symbolic refs.\n * @param {boolean} args.tags - Whether to fetch tags.\n * @param {string[]} [args.refspecs = undefined] - The refspecs to use.\n * @param {boolean} [args.prune = false] - Whether to prune stale refs.\n * @param {boolean} [args.pruneTags = false] - Whether to prune tags.\n * @returns {Promise<Object>} - An object containing pruned refs.\n */\n static async updateRemoteRefs({\n fs,\n gitdir,\n remote,\n refs,\n symrefs,\n tags,\n refspecs = void 0,\n prune = false,\n pruneTags = false\n }) {\n for (const value of refs.values()) {\n if (!value.match(/[0-9a-f]{40}/)) {\n throw new InvalidOidError(value);\n }\n }\n const config = await GitConfigManager.get({ fs, gitdir });\n if (!refspecs) {\n refspecs = await config.getall(`remote.${remote}.fetch`);\n if (refspecs.length === 0) {\n throw new NoRefspecError(remote);\n }\n refspecs.unshift(`+HEAD:refs/remotes/${remote}/HEAD`);\n }\n const refspec = GitRefSpecSet.from(refspecs);\n const actualRefsToWrite = /* @__PURE__ */ new Map();\n if (pruneTags) {\n const tags2 = await _GitRefManager.listRefs({\n fs,\n gitdir,\n filepath: \"refs/tags\"\n });\n await _GitRefManager.deleteRefs({\n fs,\n gitdir,\n refs: tags2.map((tag2) => `refs/tags/${tag2}`)\n });\n }\n if (tags) {\n for (const serverRef of refs.keys()) {\n if (serverRef.startsWith(\"refs/tags\") && !serverRef.endsWith(\"^{}\")) {\n if (!await _GitRefManager.exists({ fs, gitdir, ref: serverRef })) {\n const oid = refs.get(serverRef);\n actualRefsToWrite.set(serverRef, oid);\n }\n }\n }\n }\n const refTranslations = refspec.translate([...refs.keys()]);\n for (const [serverRef, translatedRef] of refTranslations) {\n const value = refs.get(serverRef);\n actualRefsToWrite.set(translatedRef, value);\n }\n const symrefTranslations = refspec.translate([...symrefs.keys()]);\n for (const [serverRef, translatedRef] of symrefTranslations) {\n const value = symrefs.get(serverRef);\n const symtarget = refspec.translateOne(value);\n if (symtarget) {\n actualRefsToWrite.set(translatedRef, `ref: ${symtarget}`);\n }\n }\n const pruned = [];\n if (prune) {\n for (const filepath of refspec.localNamespaces()) {\n const refs2 = (await _GitRefManager.listRefs({\n fs,\n gitdir,\n filepath\n })).map((file) => `${filepath}/${file}`);\n for (const ref of refs2) {\n if (!actualRefsToWrite.has(ref)) {\n pruned.push(ref);\n }\n }\n }\n if (pruned.length > 0) {\n await _GitRefManager.deleteRefs({ fs, gitdir, refs: pruned });\n }\n }\n for (const [key, value] of actualRefsToWrite) {\n await acquireLock(\n key,\n async () => fs.write(join2(gitdir, key), `${value.trim()}\n`, \"utf8\")\n );\n }\n return { pruned };\n }\n /**\n * Writes a ref to the file system.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.ref - The ref to write.\n * @param {string} args.value - The object ID to write.\n * @returns {Promise<void>}\n */\n // TODO: make this less crude?\n static async writeRef({ fs, gitdir, ref, value }) {\n if (!value.match(/[0-9a-f]{40}/)) {\n throw new InvalidOidError(value);\n }\n await acquireLock(\n ref,\n async () => fs.write(join2(gitdir, ref), `${value.trim()}\n`, \"utf8\")\n );\n }\n /**\n * Writes a symbolic ref to the file system.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.ref - The ref to write.\n * @param {string} args.value - The target ref.\n * @returns {Promise<void>}\n */\n static async writeSymbolicRef({ fs, gitdir, ref, value }) {\n await acquireLock(\n ref,\n async () => fs.write(join2(gitdir, ref), `ref: ${value.trim()}\n`, \"utf8\")\n );\n }\n /**\n * Deletes a single ref.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.ref - The ref to delete.\n * @returns {Promise<void>}\n */\n static async deleteRef({ fs, gitdir, ref }) {\n return _GitRefManager.deleteRefs({ fs, gitdir, refs: [ref] });\n }\n /**\n * Deletes multiple refs.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string[]} args.refs - The refs to delete.\n * @returns {Promise<void>}\n */\n static async deleteRefs({ fs, gitdir, refs }) {\n await Promise.all(refs.map((ref) => fs.rm(join2(gitdir, ref))));\n let text = await acquireLock(\n \"packed-refs\",\n async () => fs.read(`${gitdir}/packed-refs`, { encoding: \"utf8\" })\n );\n const packed = GitPackedRefs.from(text);\n const beforeSize = packed.refs.size;\n for (const ref of refs) {\n if (packed.refs.has(ref)) {\n packed.delete(ref);\n }\n }\n if (packed.refs.size < beforeSize) {\n text = packed.toString();\n await acquireLock(\n \"packed-refs\",\n async () => fs.write(`${gitdir}/packed-refs`, text, { encoding: \"utf8\" })\n );\n }\n }\n /**\n * Resolves a ref to its object ID.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.ref - The ref to resolve.\n * @param {number} [args.depth = undefined] - The maximum depth to resolve symbolic refs.\n * @returns {Promise<string>} - The resolved object ID.\n */\n static async resolve({ fs, gitdir, ref, depth = void 0 }) {\n if (depth !== void 0) {\n depth--;\n if (depth === -1) {\n return ref;\n }\n }\n if (ref.startsWith(\"ref: \")) {\n ref = ref.slice(\"ref: \".length);\n return _GitRefManager.resolve({ fs, gitdir, ref, depth });\n }\n if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {\n return ref;\n }\n const packedMap = await _GitRefManager.packedRefs({ fs, gitdir });\n const allpaths = refpaths(ref).filter((p) => !GIT_FILES.includes(p));\n for (const ref2 of allpaths) {\n const sha = await acquireLock(\n ref2,\n async () => await fs.read(`${gitdir}/${ref2}`, { encoding: \"utf8\" }) || packedMap.get(ref2)\n );\n if (sha) {\n return _GitRefManager.resolve({ fs, gitdir, ref: sha.trim(), depth });\n }\n }\n throw new NotFoundError(ref);\n }\n /**\n * Checks if a ref exists.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.ref - The ref to check.\n * @returns {Promise<boolean>} - True if the ref exists, false otherwise.\n */\n static async exists({ fs, gitdir, ref }) {\n try {\n await _GitRefManager.expand({ fs, gitdir, ref });\n return true;\n } catch (err) {\n return false;\n }\n }\n /**\n * Expands a ref to its full name.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.ref - The ref to expand.\n * @returns {Promise<string>} - The full ref name.\n */\n static async expand({ fs, gitdir, ref }) {\n if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {\n return ref;\n }\n const packedMap = await _GitRefManager.packedRefs({ fs, gitdir });\n const allpaths = refpaths(ref);\n for (const ref2 of allpaths) {\n const refExists = await acquireLock(\n ref2,\n async () => fs.exists(`${gitdir}/${ref2}`)\n );\n if (refExists) return ref2;\n if (packedMap.has(ref2)) return ref2;\n }\n throw new NotFoundError(ref);\n }\n /**\n * Expands a ref against a provided map.\n *\n * @param {Object} args\n * @param {string} args.ref - The ref to expand.\n * @param {Map<string, string>} args.map - The map of refs.\n * @returns {Promise<string>} - The expanded ref.\n */\n static async expandAgainstMap({ ref, map }) {\n const allpaths = refpaths(ref);\n for (const ref2 of allpaths) {\n if (await map.has(ref2)) return ref2;\n }\n throw new NotFoundError(ref);\n }\n /**\n * Resolves a ref against a provided map.\n *\n * @param {Object} args\n * @param {string} args.ref - The ref to resolve.\n * @param {string} [args.fullref = args.ref] - The full ref name.\n * @param {number} [args.depth = undefined] - The maximum depth to resolve symbolic refs.\n * @param {Map<string, string>} args.map - The map of refs.\n * @returns {Object} - An object containing the full ref and its object ID.\n */\n static resolveAgainstMap({ ref, fullref = ref, depth = void 0, map }) {\n if (depth !== void 0) {\n depth--;\n if (depth === -1) {\n return { fullref, oid: ref };\n }\n }\n if (ref.startsWith(\"ref: \")) {\n ref = ref.slice(\"ref: \".length);\n return _GitRefManager.resolveAgainstMap({ ref, fullref, depth, map });\n }\n if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {\n return { fullref, oid: ref };\n }\n const allpaths = refpaths(ref);\n for (const ref2 of allpaths) {\n const sha = map.get(ref2);\n if (sha) {\n return _GitRefManager.resolveAgainstMap({\n ref: sha.trim(),\n fullref: ref2,\n depth,\n map\n });\n }\n }\n throw new NotFoundError(ref);\n }\n /**\n * Reads the packed refs file and returns a map of refs.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @returns {Promise<Map<string, string>>} - A map of packed refs.\n */\n static async packedRefs({ fs, gitdir }) {\n const text = await acquireLock(\n \"packed-refs\",\n async () => fs.read(`${gitdir}/packed-refs`, { encoding: \"utf8\" })\n );\n const packed = GitPackedRefs.from(text);\n return packed.refs;\n }\n /**\n * Lists all refs matching a given filepath prefix.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.filepath - The filepath prefix to match.\n * @returns {Promise<string[]>} - A sorted list of refs.\n */\n static async listRefs({ fs, gitdir, filepath }) {\n const packedMap = _GitRefManager.packedRefs({ fs, gitdir });\n let files = null;\n try {\n files = await fs.readdirDeep(`${gitdir}/${filepath}`);\n files = files.map((x) => x.replace(`${gitdir}/${filepath}/`, \"\"));\n } catch (err) {\n files = [];\n }\n for (let key of (await packedMap).keys()) {\n if (key.startsWith(filepath)) {\n key = key.replace(filepath + \"/\", \"\");\n if (!files.includes(key)) {\n files.push(key);\n }\n }\n }\n files.sort(compareRefNames);\n return files;\n }\n /**\n * Lists all branches, optionally filtered by remote.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} [args.remote] - The remote to filter branches by.\n * @returns {Promise<string[]>} - A list of branch names.\n */\n static async listBranches({ fs, gitdir, remote }) {\n if (remote) {\n return _GitRefManager.listRefs({\n fs,\n gitdir,\n filepath: `refs/remotes/${remote}`\n });\n } else {\n return _GitRefManager.listRefs({ fs, gitdir, filepath: `refs/heads` });\n }\n }\n /**\n * Lists all tags.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @returns {Promise<string[]>} - A list of tag names.\n */\n static async listTags({ fs, gitdir }) {\n const tags = await _GitRefManager.listRefs({\n fs,\n gitdir,\n filepath: `refs/tags`\n });\n return tags.filter((x) => !x.endsWith(\"^{}\"));\n }\n};\nfunction compareTreeEntryPath(a, b) {\n return compareStrings(appendSlashIfDir(a), appendSlashIfDir(b));\n}\nfunction appendSlashIfDir(entry) {\n return entry.mode === \"040000\" ? entry.path + \"/\" : entry.path;\n}\nfunction mode2type$1(mode) {\n switch (mode) {\n case \"040000\":\n return \"tree\";\n case \"100644\":\n return \"blob\";\n case \"100755\":\n return \"blob\";\n case \"120000\":\n return \"blob\";\n case \"160000\":\n return \"commit\";\n }\n throw new InternalError(`Unexpected GitTree entry mode: ${mode}`);\n}\nfunction parseBuffer(buffer) {\n const _entries = [];\n let cursor = 0;\n while (cursor < buffer.length) {\n const space = buffer.indexOf(32, cursor);\n if (space === -1) {\n throw new InternalError(\n `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.`\n );\n }\n const nullchar = buffer.indexOf(0, cursor);\n if (nullchar === -1) {\n throw new InternalError(\n `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.`\n );\n }\n let mode = buffer.slice(cursor, space).toString(\"utf8\");\n if (mode === \"40000\") mode = \"040000\";\n const type = mode2type$1(mode);\n const path = buffer.slice(space + 1, nullchar).toString(\"utf8\");\n if (path.includes(\"\\\\\") || path.includes(\"/\")) {\n throw new UnsafeFilepathError(path);\n }\n const oid = buffer.slice(nullchar + 1, nullchar + 21).toString(\"hex\");\n cursor = nullchar + 21;\n _entries.push({ mode, path, oid, type });\n }\n return _entries;\n}\nfunction limitModeToAllowed(mode) {\n if (typeof mode === \"number\") {\n mode = mode.toString(8);\n }\n if (mode.match(/^0?4.*/)) return \"040000\";\n if (mode.match(/^1006.*/)) return \"100644\";\n if (mode.match(/^1007.*/)) return \"100755\";\n if (mode.match(/^120.*/)) return \"120000\";\n if (mode.match(/^160.*/)) return \"160000\";\n throw new InternalError(`Could not understand file mode: ${mode}`);\n}\nfunction nudgeIntoShape(entry) {\n if (!entry.oid && entry.sha) {\n entry.oid = entry.sha;\n }\n entry.mode = limitModeToAllowed(entry.mode);\n if (!entry.type) {\n entry.type = mode2type$1(entry.mode);\n }\n return entry;\n}\nvar GitTree = class _GitTree {\n constructor(entries) {\n if (Buffer.isBuffer(entries)) {\n this._entries = parseBuffer(entries);\n } else if (Array.isArray(entries)) {\n this._entries = entries.map(nudgeIntoShape);\n } else {\n throw new InternalError(\"invalid type passed to GitTree constructor\");\n }\n this._entries.sort(comparePath);\n }\n static from(tree) {\n return new _GitTree(tree);\n }\n render() {\n return this._entries.map((entry) => `${entry.mode} ${entry.type} ${entry.oid} ${entry.path}`).join(\"\\n\");\n }\n toObject() {\n const entries = [...this._entries];\n entries.sort(compareTreeEntryPath);\n return Buffer.concat(\n entries.map((entry) => {\n const mode = Buffer.from(entry.mode.replace(/^0/, \"\"));\n const space = Buffer.from(\" \");\n const path = Buffer.from(entry.path, \"utf8\");\n const nullchar = Buffer.from([0]);\n const oid = Buffer.from(entry.oid, \"hex\");\n return Buffer.concat([mode, space, path, nullchar, oid]);\n })\n );\n }\n /**\n * @returns {TreeEntry[]}\n */\n entries() {\n return this._entries;\n }\n *[Symbol.iterator]() {\n for (const entry of this._entries) {\n yield entry;\n }\n }\n};\nvar GitObject = class {\n /**\n * Wraps a raw object with a Git header.\n *\n * @param {Object} params - The parameters for wrapping.\n * @param {string} params.type - The type of the Git object (e.g., 'blob', 'tree', 'commit').\n * @param {Uint8Array} params.object - The raw object data to wrap.\n * @returns {Uint8Array} The wrapped Git object as a single buffer.\n */\n static wrap({ type, object }) {\n const header = `${type} ${object.length}\\0`;\n const headerLen = header.length;\n const totalLength = headerLen + object.length;\n const wrappedObject = new Uint8Array(totalLength);\n for (let i = 0; i < headerLen; i++) {\n wrappedObject[i] = header.charCodeAt(i);\n }\n wrappedObject.set(object, headerLen);\n return wrappedObject;\n }\n /**\n * Unwraps a Git object buffer into its type and raw object data.\n *\n * @param {Buffer|Uint8Array} buffer - The buffer containing the wrapped Git object.\n * @returns {{ type: string, object: Buffer }} An object containing the type and the raw object data.\n * @throws {InternalError} If the length specified in the header does not match the actual object length.\n */\n static unwrap(buffer) {\n const s = buffer.indexOf(32);\n const i = buffer.indexOf(0);\n const type = buffer.slice(0, s).toString(\"utf8\");\n const length = buffer.slice(s + 1, i).toString(\"utf8\");\n const actualLength = buffer.length - (i + 1);\n if (parseInt(length) !== actualLength) {\n throw new InternalError(\n `Length mismatch: expected ${length} bytes but got ${actualLength} instead.`\n );\n }\n return {\n type,\n object: Buffer.from(buffer.slice(i + 1))\n };\n }\n};\nasync function readObjectLoose({ fs, gitdir, oid }) {\n const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`;\n const file = await fs.read(`${gitdir}/${source}`);\n if (!file) {\n return null;\n }\n return { object: file, format: \"deflated\", source };\n}\nfunction applyDelta(delta, source) {\n const reader = new BufferCursor(delta);\n const sourceSize = readVarIntLE(reader);\n if (sourceSize !== source.byteLength) {\n throw new InternalError(\n `applyDelta expected source buffer to be ${sourceSize} bytes but the provided buffer was ${source.length} bytes`\n );\n }\n const targetSize = readVarIntLE(reader);\n let target;\n if (targetSize === 0) {\n return Buffer.alloc(0);\n }\n const firstOp = readOp(reader, source);\n if (firstOp.byteLength === targetSize) {\n target = firstOp;\n } else {\n target = Buffer.alloc(targetSize);\n const writer = new BufferCursor(target);\n writer.copy(firstOp);\n while (!reader.eof()) {\n writer.copy(readOp(reader, source));\n }\n const tell = writer.tell();\n if (targetSize !== tell) {\n throw new InternalError(\n `applyDelta expected target buffer to be ${targetSize} bytes but the resulting buffer was ${tell} bytes`\n );\n }\n }\n return target;\n}\nfunction readVarIntLE(reader) {\n let result = 0;\n let shift = 0;\n let byte = null;\n do {\n byte = reader.readUInt8();\n result |= (byte & 127) << shift;\n shift += 7;\n } while (byte & 128);\n return result;\n}\nfunction readCompactLE(reader, flags, size) {\n let result = 0;\n let shift = 0;\n while (size--) {\n if (flags & 1) {\n result |= reader.readUInt8() << shift;\n }\n flags >>= 1;\n shift += 8;\n }\n return result;\n}\nfunction readOp(reader, source) {\n const byte = reader.readUInt8();\n const COPY = 128;\n const OFFS = 15;\n const SIZE = 112;\n if (byte & COPY) {\n const offset = readCompactLE(reader, byte & OFFS, 4);\n let size = readCompactLE(reader, (byte & SIZE) >> 4, 3);\n if (size === 0) size = 65536;\n return source.slice(offset, offset + size);\n } else {\n return reader.slice(byte);\n }\n}\nfunction fromValue(value) {\n let queue = [value];\n return {\n next() {\n return Promise.resolve({ done: queue.length === 0, value: queue.pop() });\n },\n return() {\n queue = [];\n return {};\n },\n [Symbol.asyncIterator]() {\n return this;\n }\n };\n}\nfunction getIterator(iterable) {\n if (iterable[Symbol.asyncIterator]) {\n return iterable[Symbol.asyncIterator]();\n }\n if (iterable[Symbol.iterator]) {\n return iterable[Symbol.iterator]();\n }\n if (iterable.next) {\n return iterable;\n }\n return fromValue(iterable);\n}\nvar StreamReader = class {\n constructor(stream) {\n if (typeof Buffer === \"undefined\") {\n throw new Error(\"Missing Buffer dependency\");\n }\n this.stream = getIterator(stream);\n this.buffer = null;\n this.cursor = 0;\n this.undoCursor = 0;\n this.started = false;\n this._ended = false;\n this._discardedBytes = 0;\n }\n eof() {\n return this._ended && this.cursor === this.buffer.length;\n }\n tell() {\n return this._discardedBytes + this.cursor;\n }\n async byte() {\n if (this.eof()) return;\n if (!this.started) await this._init();\n if (this.cursor === this.buffer.length) {\n await this._loadnext();\n if (this._ended) return;\n }\n this._moveCursor(1);\n return this.buffer[this.undoCursor];\n }\n async chunk() {\n if (this.eof()) return;\n if (!this.started) await this._init();\n if (this.cursor === this.buffer.length) {\n await this._loadnext();\n if (this._ended) return;\n }\n this._moveCursor(this.buffer.length);\n return this.buffer.slice(this.undoCursor, this.cursor);\n }\n async read(n) {\n if (this.eof()) return;\n if (!this.started) await this._init();\n if (this.cursor + n > this.buffer.length) {\n this._trim();\n await this._accumulate(n);\n }\n this._moveCursor(n);\n return this.buffer.slice(this.undoCursor, this.cursor);\n }\n async skip(n) {\n if (this.eof()) return;\n if (!this.started) await this._init();\n if (this.cursor + n > this.buffer.length) {\n this._trim();\n await this._accumulate(n);\n }\n this._moveCursor(n);\n }\n async undo() {\n this.cursor = this.undoCursor;\n }\n async _next() {\n this.started = true;\n let { done, value } = await this.stream.next();\n if (done) {\n this._ended = true;\n if (!value) return Buffer.alloc(0);\n }\n if (value) {\n value = Buffer.from(value);\n }\n return value;\n }\n _trim() {\n this.buffer = this.buffer.slice(this.undoCursor);\n this.cursor -= this.undoCursor;\n this._discardedBytes += this.undoCursor;\n this.undoCursor = 0;\n }\n _moveCursor(n) {\n this.undoCursor = this.cursor;\n this.cursor += n;\n if (this.cursor > this.buffer.length) {\n this.cursor = this.buffer.length;\n }\n }\n async _accumulate(n) {\n if (this._ended) return;\n const buffers = [this.buffer];\n while (this.cursor + n > lengthBuffers(buffers)) {\n const nextbuffer = await this._next();\n if (this._ended) break;\n buffers.push(nextbuffer);\n }\n this.buffer = Buffer.concat(buffers);\n }\n async _loadnext() {\n this._discardedBytes += this.buffer.length;\n this.undoCursor = 0;\n this.cursor = 0;\n this.buffer = await this._next();\n }\n async _init() {\n this.buffer = await this._next();\n }\n};\nfunction lengthBuffers(buffers) {\n return buffers.reduce((acc, buffer) => acc + buffer.length, 0);\n}\nasync function listpack(stream, onData) {\n const reader = new StreamReader(stream);\n let PACK = await reader.read(4);\n PACK = PACK.toString(\"utf8\");\n if (PACK !== \"PACK\") {\n throw new InternalError(`Invalid PACK header '${PACK}'`);\n }\n let version2 = await reader.read(4);\n version2 = version2.readUInt32BE(0);\n if (version2 !== 2) {\n throw new InternalError(`Invalid packfile version: ${version2}`);\n }\n let numObjects = await reader.read(4);\n numObjects = numObjects.readUInt32BE(0);\n if (numObjects < 1) return;\n while (!reader.eof() && numObjects--) {\n const offset = reader.tell();\n const { type, length, ofs, reference } = await parseHeader(reader);\n const inflator = new import_pako.default.Inflate();\n while (!inflator.result) {\n const chunk = await reader.chunk();\n if (!chunk) break;\n inflator.push(chunk, false);\n if (inflator.err) {\n throw new InternalError(`Pako error: ${inflator.msg}`);\n }\n if (inflator.result) {\n if (inflator.result.length !== length) {\n throw new InternalError(\n `Inflated object size is different from that stated in packfile.`\n );\n }\n await reader.undo();\n await reader.read(chunk.length - inflator.strm.avail_in);\n const end = reader.tell();\n await onData({\n data: inflator.result,\n type,\n num: numObjects,\n offset,\n end,\n reference,\n ofs\n });\n }\n }\n }\n}\nasync function parseHeader(reader) {\n let byte = await reader.byte();\n const type = byte >> 4 & 7;\n let length = byte & 15;\n if (byte & 128) {\n let shift = 4;\n do {\n byte = await reader.byte();\n length |= (byte & 127) << shift;\n shift += 7;\n } while (byte & 128);\n }\n let ofs;\n let reference;\n if (type === 6) {\n let shift = 0;\n ofs = 0;\n const bytes = [];\n do {\n byte = await reader.byte();\n ofs |= (byte & 127) << shift;\n shift += 7;\n bytes.push(byte);\n } while (byte & 128);\n reference = Buffer.from(bytes);\n }\n if (type === 7) {\n const buf = await reader.read(20);\n reference = buf;\n }\n return { type, length, ofs, reference };\n}\nvar supportsDecompressionStream = false;\nasync function inflate(buffer) {\n if (supportsDecompressionStream === null) {\n supportsDecompressionStream = testDecompressionStream();\n }\n return supportsDecompressionStream ? browserInflate(buffer) : import_pako.default.inflate(buffer);\n}\nasync function browserInflate(buffer) {\n const ds = new DecompressionStream(\"deflate\");\n const d = new Blob([buffer]).stream().pipeThrough(ds);\n return new Uint8Array(await new Response(d).arrayBuffer());\n}\nfunction testDecompressionStream() {\n try {\n const ds = new DecompressionStream(\"deflate\");\n if (ds) return true;\n } catch (_) {\n }\n return false;\n}\nfunction decodeVarInt(reader) {\n const bytes = [];\n let byte = 0;\n let multibyte = 0;\n do {\n byte = reader.readUInt8();\n const lastSeven = byte & 127;\n bytes.push(lastSeven);\n multibyte = byte & 128;\n } while (multibyte);\n return bytes.reduce((a, b) => a + 1 << 7 | b, -1);\n}\nfunction otherVarIntDecode(reader, startWith) {\n let result = startWith;\n let shift = 4;\n let byte = null;\n do {\n byte = reader.readUInt8();\n result |= (byte & 127) << shift;\n shift += 7;\n } while (byte & 128);\n return result;\n}\nvar GitPackIndex = class _GitPackIndex {\n constructor(stuff) {\n Object.assign(this, stuff);\n this.offsetCache = {};\n }\n static async fromIdx({ idx, getExternalRefDelta }) {\n const reader = new BufferCursor(idx);\n const magic = reader.slice(4).toString(\"hex\");\n if (magic !== \"ff744f63\") {\n return;\n }\n const version2 = reader.readUInt32BE();\n if (version2 !== 2) {\n throw new InternalError(\n `Unable to read version ${version2} packfile IDX. (Only version 2 supported)`\n );\n }\n if (idx.byteLength > 2048 * 1024 * 1024) {\n throw new InternalError(\n `To keep implementation simple, I haven't implemented the layer 5 feature needed to support packfiles > 2GB in size.`\n );\n }\n reader.seek(reader.tell() + 4 * 255);\n const size = reader.readUInt32BE();\n const hashes = [];\n for (let i = 0; i < size; i++) {\n const hash = reader.slice(20).toString(\"hex\");\n hashes[i] = hash;\n }\n reader.seek(reader.tell() + 4 * size);\n const offsets = /* @__PURE__ */ new Map();\n for (let i = 0; i < size; i++) {\n offsets.set(hashes[i], reader.readUInt32BE());\n }\n const packfileSha = reader.slice(20).toString(\"hex\");\n return new _GitPackIndex({\n hashes,\n crcs: {},\n offsets,\n packfileSha,\n getExternalRefDelta\n });\n }\n static async fromPack({ pack, getExternalRefDelta, onProgress }) {\n const listpackTypes = {\n 1: \"commit\",\n 2: \"tree\",\n 3: \"blob\",\n 4: \"tag\",\n 6: \"ofs-delta\",\n 7: \"ref-delta\"\n };\n const offsetToObject = {};\n const packfileSha = pack.slice(-20).toString(\"hex\");\n const hashes = [];\n const crcs = {};\n const offsets = /* @__PURE__ */ new Map();\n let totalObjectCount = null;\n let lastPercent = null;\n await listpack([pack], async ({ data, type, reference, offset, num: num2 }) => {\n if (totalObjectCount === null) totalObjectCount = num2;\n const percent = Math.floor(\n (totalObjectCount - num2) * 100 / totalObjectCount\n );\n if (percent !== lastPercent) {\n if (onProgress) {\n await onProgress({\n phase: \"Receiving objects\",\n loaded: totalObjectCount - num2,\n total: totalObjectCount\n });\n }\n }\n lastPercent = percent;\n type = listpackTypes[type];\n if ([\"commit\", \"tree\", \"blob\", \"tag\"].includes(type)) {\n const oid = await shasum(GitObject.wrap({ type, object: data }));\n offsetToObject[offset] = {\n type,\n offset,\n oid\n };\n } else if (type === \"ofs-delta\") {\n offsetToObject[offset] = {\n type,\n offset\n };\n } else if (type === \"ref-delta\") {\n offsetToObject[offset] = {\n type,\n offset\n };\n }\n });\n const offsetArray = Object.keys(offsetToObject).map(Number);\n for (const [i, start] of offsetArray.entries()) {\n const end = i + 1 === offsetArray.length ? pack.byteLength - 20 : offsetArray[i + 1];\n const o = offsetToObject[start];\n const crc = import_crc_32.default.buf(pack.slice(start, end)) >>> 0;\n o.end = end;\n o.crc = crc;\n }\n const p = new _GitPackIndex({\n pack: Promise.resolve(pack),\n packfileSha,\n crcs,\n hashes,\n offsets,\n getExternalRefDelta\n });\n lastPercent = null;\n let count = 0;\n for (let offset in offsetToObject) {\n offset = Number(offset);\n const percent = Math.floor(count * 100 / totalObjectCount);\n if (percent !== lastPercent) {\n if (onProgress) {\n await onProgress({\n phase: \"Resolving deltas\",\n loaded: count,\n total: totalObjectCount\n });\n }\n }\n count++;\n lastPercent = percent;\n const o = offsetToObject[offset];\n if (o.oid) {\n hashes.push(o.oid);\n offsets.set(o.oid, offset);\n crcs[o.oid] = o.crc;\n continue;\n }\n try {\n const { type, object } = await p.readSlice({ start: offset });\n const oid = await shasum(GitObject.wrap({ type, object }));\n o.oid = oid;\n hashes.push(oid);\n offsets.set(oid, offset);\n crcs[oid] = o.crc;\n } catch (err) {\n continue;\n }\n }\n hashes.sort();\n return p;\n }\n async toBuffer() {\n const buffers = [];\n const write = (str, encoding) => {\n buffers.push(Buffer.from(str, encoding));\n };\n write(\"ff744f63\", \"hex\");\n write(\"00000002\", \"hex\");\n const fanoutBuffer = new BufferCursor(Buffer.alloc(256 * 4));\n const fanout = new Uint32Array(256);\n for (const hash of this.hashes) {\n fanout[parseInt(hash.slice(0, 2), 16)]++;\n }\n let count = 0;\n for (let i = 0; i < 256; i++) {\n count += fanout[i];\n fanoutBuffer.writeUInt32BE(count);\n }\n buffers.push(fanoutBuffer.buffer);\n for (const hash of this.hashes) {\n write(hash, \"hex\");\n }\n const crcsBuffer = new BufferCursor(Buffer.alloc(this.hashes.length * 4));\n for (const hash of this.hashes) {\n crcsBuffer.writeUInt32BE(this.crcs[hash]);\n }\n buffers.push(crcsBuffer.buffer);\n const offsetsBuffer = new BufferCursor(Buffer.alloc(this.hashes.length * 4));\n for (const hash of this.hashes) {\n offsetsBuffer.writeUInt32BE(this.offsets.get(hash));\n }\n buffers.push(offsetsBuffer.buffer);\n write(this.packfileSha, \"hex\");\n const totalBuffer = Buffer.concat(buffers);\n const sha = await shasum(totalBuffer);\n const shaBuffer = Buffer.alloc(20);\n shaBuffer.write(sha, \"hex\");\n return Buffer.concat([totalBuffer, shaBuffer]);\n }\n async load({ pack }) {\n this.pack = pack;\n }\n async unload() {\n this.pack = null;\n }\n async read({ oid, readContext = { depth: 0 } }) {\n if (!this.offsets.get(oid)) {\n if (this.getExternalRefDelta) {\n return this.getExternalRefDelta(oid);\n } else {\n throw new InternalError(`Could not read object ${oid} from packfile`);\n }\n }\n const start = this.offsets.get(oid);\n return this.readSlice({ start, readContext });\n }\n async readSlice({ start, readContext = { depth: 0 } }) {\n if (this.offsetCache[start]) {\n return Object.assign({}, this.offsetCache[start]);\n }\n readContext.depth++;\n try {\n const types2 = {\n 16: \"commit\",\n 32: \"tree\",\n 48: \"blob\",\n 64: \"tag\",\n 96: \"ofs_delta\",\n 112: \"ref_delta\"\n };\n if (!this.pack) {\n throw new InternalError(\n \"Tried to read from a GitPackIndex with no packfile loaded into memory\"\n );\n }\n const raw = (await this.pack).slice(start);\n const reader = new BufferCursor(raw);\n const byte = reader.readUInt8();\n const btype = byte & 112;\n let type = types2[btype];\n if (type === void 0) {\n throw new InternalError(\"Unrecognized type: 0b\" + btype.toString(2));\n }\n const lastFour = byte & 15;\n let length = lastFour;\n const multibyte = byte & 128;\n if (multibyte) {\n length = otherVarIntDecode(reader, lastFour);\n }\n let base = null;\n let object = null;\n if (type === \"ofs_delta\") {\n const offset = decodeVarInt(reader);\n const baseOffset = start - offset;\n ({ object: base, type } = await this.readSlice({\n start: baseOffset,\n readContext\n }));\n }\n if (type === \"ref_delta\") {\n const oid = reader.slice(20).toString(\"hex\");\n ({ object: base, type } = await this.read({ oid, readContext }));\n }\n const buffer = raw.slice(reader.tell());\n object = Buffer.from(await inflate(buffer));\n if (object.byteLength !== length) {\n throw new InternalError(\n `Packfile told us object would have length ${length} but it had length ${object.byteLength}`\n );\n }\n if (base) {\n object = Buffer.from(applyDelta(object, base));\n }\n if (readContext.depth > 3) {\n this.offsetCache[start] = { type, object };\n }\n return { type, format: \"content\", object };\n } finally {\n readContext.depth--;\n }\n }\n};\nvar PackfileCache = /* @__PURE__ */ Symbol(\"PackfileCache\");\nvar packIndexCacheKey = (gitdir, filename) => `${gitdir}/objects/pack/${filename}`;\nfunction seedPackfileCache({ cache, gitdir, packfileSha, index: index3 }) {\n if (!cache[PackfileCache]) cache[PackfileCache] = /* @__PURE__ */ new Map();\n const filename = packIndexCacheKey(\n gitdir,\n `pack-${packfileSha}.idx`\n );\n cache[PackfileCache].set(filename, Promise.resolve(index3));\n}\nasync function loadPackIndex({\n fs,\n filename,\n getExternalRefDelta,\n emitter,\n emitterPrefix\n}) {\n const idx = await fs.read(filename);\n return GitPackIndex.fromIdx({ idx, getExternalRefDelta });\n}\nfunction readPackIndex({\n fs,\n cache,\n filename,\n getExternalRefDelta,\n emitter,\n emitterPrefix\n}) {\n if (!cache[PackfileCache]) cache[PackfileCache] = /* @__PURE__ */ new Map();\n let p = cache[PackfileCache].get(filename);\n if (!p) {\n p = loadPackIndex({\n fs,\n filename,\n getExternalRefDelta,\n emitter,\n emitterPrefix\n });\n cache[PackfileCache].set(filename, p);\n }\n return p;\n}\nasync function readObjectPacked({\n fs,\n cache,\n gitdir,\n oid,\n format = \"content\",\n getExternalRefDelta\n}) {\n let list = await fs.readdir(join2(gitdir, \"objects/pack\"));\n list = list.filter((x) => x.endsWith(\".idx\"));\n for (const filename of list) {\n const indexFile = packIndexCacheKey(gitdir, filename);\n const p = await readPackIndex({\n fs,\n cache,\n filename: indexFile,\n getExternalRefDelta\n });\n if (p.error) throw new InternalError(p.error);\n if (p.offsets.has(oid)) {\n if (!p.pack) {\n const packFile = indexFile.replace(/idx$/, \"pack\");\n p.pack = fs.read(packFile);\n }\n const result = await p.read({ oid, getExternalRefDelta });\n result.format = \"content\";\n result.source = `objects/pack/${filename.replace(/idx$/, \"pack\")}`;\n return result;\n }\n }\n return null;\n}\nasync function _readObject({\n fs,\n cache,\n gitdir,\n oid,\n format = \"content\"\n}) {\n const getExternalRefDelta = (oid2) => _readObject({ fs, cache, gitdir, oid: oid2 });\n let result;\n if (oid === \"4b825dc642cb6eb9a060e54bf8d69288fbee4904\") {\n result = { format: \"wrapped\", object: Buffer.from(`tree 0\\0`) };\n }\n if (!result) {\n result = await readObjectLoose({ fs, gitdir, oid });\n }\n if (!result) {\n result = await readObjectPacked({\n fs,\n cache,\n gitdir,\n oid,\n getExternalRefDelta\n });\n if (!result) {\n throw new NotFoundError(oid);\n }\n return result;\n }\n if (format === \"deflated\") {\n return result;\n }\n if (result.format === \"deflated\") {\n result.object = Buffer.from(await inflate(result.object));\n result.format = \"wrapped\";\n }\n if (format === \"wrapped\") {\n return result;\n }\n const sha = await shasum(result.object);\n if (sha !== oid) {\n throw new InternalError(\n `SHA check failed! Expected ${oid}, computed ${sha}`\n );\n }\n const { object, type } = GitObject.unwrap(result.object);\n result.type = type;\n result.object = object;\n result.format = \"content\";\n if (format === \"content\") {\n return result;\n }\n throw new InternalError(`invalid requested format \"${format}\"`);\n}\nvar AlreadyExistsError = class _AlreadyExistsError extends BaseError {\n /**\n * @param {'note'|'remote'|'tag'|'branch'} noun\n * @param {string} where\n * @param {boolean} canForce\n */\n constructor(noun, where, canForce = true) {\n super(\n `Failed to create ${noun} at ${where} because it already exists.${canForce ? ` (Hint: use 'force: true' parameter to overwrite existing ${noun}.)` : \"\"}`\n );\n this.code = this.name = _AlreadyExistsError.code;\n this.data = { noun, where, canForce };\n }\n};\nAlreadyExistsError.code = \"AlreadyExistsError\";\nvar AmbiguousError = class _AmbiguousError extends BaseError {\n /**\n * @param {'oids'|'refs'} nouns\n * @param {string} short\n * @param {string[]} matches\n */\n constructor(nouns, short, matches) {\n super(\n `Found multiple ${nouns} matching \"${short}\" (${matches.join(\n \", \"\n )}). Use a longer abbreviation length to disambiguate them.`\n );\n this.code = this.name = _AmbiguousError.code;\n this.data = { nouns, short, matches };\n }\n};\nAmbiguousError.code = \"AmbiguousError\";\nvar CheckoutConflictError = class _CheckoutConflictError extends BaseError {\n /**\n * @param {string[]} filepaths\n */\n constructor(filepaths) {\n super(\n `Your local changes to the following files would be overwritten by checkout: ${filepaths.join(\n \", \"\n )}`\n );\n this.code = this.name = _CheckoutConflictError.code;\n this.data = { filepaths };\n }\n};\nCheckoutConflictError.code = \"CheckoutConflictError\";\nvar CommitNotFetchedError = class _CommitNotFetchedError extends BaseError {\n /**\n * @param {string} ref\n * @param {string} oid\n */\n constructor(ref, oid) {\n super(\n `Failed to checkout \"${ref}\" because commit ${oid} is not available locally. Do a git fetch to make the branch available locally.`\n );\n this.code = this.name = _CommitNotFetchedError.code;\n this.data = { ref, oid };\n }\n};\nCommitNotFetchedError.code = \"CommitNotFetchedError\";\nvar EmptyServerResponseError = class _EmptyServerResponseError extends BaseError {\n constructor() {\n super(`Empty response from git server.`);\n this.code = this.name = _EmptyServerResponseError.code;\n this.data = {};\n }\n};\nEmptyServerResponseError.code = \"EmptyServerResponseError\";\nvar FastForwardError = class _FastForwardError extends BaseError {\n constructor() {\n super(`A simple fast-forward merge was not possible.`);\n this.code = this.name = _FastForwardError.code;\n this.data = {};\n }\n};\nFastForwardError.code = \"FastForwardError\";\nvar GitPushError = class _GitPushError extends BaseError {\n /**\n * @param {string} prettyDetails\n * @param {PushResult} result\n */\n constructor(prettyDetails, result) {\n super(`One or more branches were not updated: ${prettyDetails}`);\n this.code = this.name = _GitPushError.code;\n this.data = { prettyDetails, result };\n }\n};\nGitPushError.code = \"GitPushError\";\nvar HttpError = class _HttpError extends BaseError {\n /**\n * @param {number} statusCode\n * @param {string} statusMessage\n * @param {string} response\n */\n constructor(statusCode, statusMessage, response) {\n super(`HTTP Error: ${statusCode} ${statusMessage}`);\n this.code = this.name = _HttpError.code;\n this.data = { statusCode, statusMessage, response };\n }\n};\nHttpError.code = \"HttpError\";\nvar InvalidFilepathError = class _InvalidFilepathError extends BaseError {\n /**\n * @param {'leading-slash'|'trailing-slash'|'directory'} [reason]\n */\n constructor(reason) {\n let message = \"invalid filepath\";\n if (reason === \"leading-slash\" || reason === \"trailing-slash\") {\n message = `\"filepath\" parameter should not include leading or trailing directory separators because these can cause problems on some platforms.`;\n } else if (reason === \"directory\") {\n message = `\"filepath\" should not be a directory.`;\n }\n super(message);\n this.code = this.name = _InvalidFilepathError.code;\n this.data = { reason };\n }\n};\nInvalidFilepathError.code = \"InvalidFilepathError\";\nvar InvalidRefNameError = class _InvalidRefNameError extends BaseError {\n /**\n * @param {string} ref\n * @param {string} suggestion\n * @param {boolean} canForce\n */\n constructor(ref, suggestion) {\n super(\n `\"${ref}\" would be an invalid git reference. (Hint: a valid alternative would be \"${suggestion}\".)`\n );\n this.code = this.name = _InvalidRefNameError.code;\n this.data = { ref, suggestion };\n }\n};\nInvalidRefNameError.code = \"InvalidRefNameError\";\nvar MaxDepthError = class _MaxDepthError extends BaseError {\n /**\n * @param {number} depth\n */\n constructor(depth) {\n super(`Maximum search depth of ${depth} exceeded.`);\n this.code = this.name = _MaxDepthError.code;\n this.data = { depth };\n }\n};\nMaxDepthError.code = \"MaxDepthError\";\nvar MergeNotSupportedError = class _MergeNotSupportedError extends BaseError {\n constructor() {\n super(`Merges with conflicts are not supported yet.`);\n this.code = this.name = _MergeNotSupportedError.code;\n this.data = {};\n }\n};\nMergeNotSupportedError.code = \"MergeNotSupportedError\";\nvar MergeConflictError = class _MergeConflictError extends BaseError {\n /**\n * @param {Array<string>} filepaths\n * @param {Array<string>} bothModified\n * @param {Array<string>} deleteByUs\n * @param {Array<string>} deleteByTheirs\n */\n constructor(filepaths, bothModified, deleteByUs, deleteByTheirs) {\n super(\n `Automatic merge failed with one or more merge conflicts in the following files: ${filepaths.toString()}. Fix conflicts then commit the result.`\n );\n this.code = this.name = _MergeConflictError.code;\n this.data = { filepaths, bothModified, deleteByUs, deleteByTheirs };\n }\n};\nMergeConflictError.code = \"MergeConflictError\";\nvar MissingNameError = class _MissingNameError extends BaseError {\n /**\n * @param {'author'|'committer'|'tagger'} role\n */\n constructor(role) {\n super(\n `No name was provided for ${role} in the argument or in the .git/config file.`\n );\n this.code = this.name = _MissingNameError.code;\n this.data = { role };\n }\n};\nMissingNameError.code = \"MissingNameError\";\nvar MissingParameterError = class _MissingParameterError extends BaseError {\n /**\n * @param {string} parameter\n */\n constructor(parameter) {\n super(\n `The function requires a \"${parameter}\" parameter but none was provided.`\n );\n this.code = this.name = _MissingParameterError.code;\n this.data = { parameter };\n }\n};\nMissingParameterError.code = \"MissingParameterError\";\nvar MultipleGitError = class _MultipleGitError extends BaseError {\n /**\n * @param {Error[]} errors\n * @param {string} message\n */\n constructor(errors) {\n super(\n `There are multiple errors that were thrown by the method. Please refer to the \"errors\" property to see more`\n );\n this.code = this.name = _MultipleGitError.code;\n this.data = { errors };\n this.errors = errors;\n }\n};\nMultipleGitError.code = \"MultipleGitError\";\nvar ParseError = class _ParseError extends BaseError {\n /**\n * @param {string} expected\n * @param {string} actual\n */\n constructor(expected, actual) {\n super(`Expected \"${expected}\" but received \"${actual}\".`);\n this.code = this.name = _ParseError.code;\n this.data = { expected, actual };\n }\n};\nParseError.code = \"ParseError\";\nvar PushRejectedError = class _PushRejectedError extends BaseError {\n /**\n * @param {'not-fast-forward'|'tag-exists'} reason\n */\n constructor(reason) {\n let message = \"\";\n if (reason === \"not-fast-forward\") {\n message = \" because it was not a simple fast-forward\";\n } else if (reason === \"tag-exists\") {\n message = \" because tag already exists\";\n }\n super(`Push rejected${message}. Use \"force: true\" to override.`);\n this.code = this.name = _PushRejectedError.code;\n this.data = { reason };\n }\n};\nPushRejectedError.code = \"PushRejectedError\";\nvar RemoteCapabilityError = class _RemoteCapabilityError extends BaseError {\n /**\n * @param {'shallow'|'deepen-since'|'deepen-not'|'deepen-relative'} capability\n * @param {'depth'|'since'|'exclude'|'relative'} parameter\n */\n constructor(capability, parameter) {\n super(\n `Remote does not support the \"${capability}\" so the \"${parameter}\" parameter cannot be used.`\n );\n this.code = this.name = _RemoteCapabilityError.code;\n this.data = { capability, parameter };\n }\n};\nRemoteCapabilityError.code = \"RemoteCapabilityError\";\nvar SmartHttpError = class _SmartHttpError extends BaseError {\n /**\n * @param {string} preview\n * @param {string} response\n */\n constructor(preview, response) {\n super(\n `Remote did not reply using the \"smart\" HTTP protocol. Expected \"001e# service=git-upload-pack\" but received: ${preview}`\n );\n this.code = this.name = _SmartHttpError.code;\n this.data = { preview, response };\n }\n};\nSmartHttpError.code = \"SmartHttpError\";\nvar UnknownTransportError = class _UnknownTransportError extends BaseError {\n /**\n * @param {string} url\n * @param {string} transport\n * @param {string} [suggestion]\n */\n constructor(url, transport, suggestion) {\n super(\n `Git remote \"${url}\" uses an unrecognized transport protocol: \"${transport}\"`\n );\n this.code = this.name = _UnknownTransportError.code;\n this.data = { url, transport, suggestion };\n }\n};\nUnknownTransportError.code = \"UnknownTransportError\";\nvar UrlParseError = class _UrlParseError extends BaseError {\n /**\n * @param {string} url\n */\n constructor(url) {\n super(`Cannot parse remote URL: \"${url}\"`);\n this.code = this.name = _UrlParseError.code;\n this.data = { url };\n }\n};\nUrlParseError.code = \"UrlParseError\";\nvar UserCanceledError = class _UserCanceledError extends BaseError {\n constructor() {\n super(`The operation was canceled.`);\n this.code = this.name = _UserCanceledError.code;\n this.data = {};\n }\n};\nUserCanceledError.code = \"UserCanceledError\";\nvar IndexResetError = class _IndexResetError extends BaseError {\n /**\n * @param {Array<string>} filepaths\n */\n constructor(filepath) {\n super(\n `Could not merge index: Entry for '${filepath}' is not up to date. Either reset the index entry to HEAD, or stage your unstaged changes.`\n );\n this.code = this.name = _IndexResetError.code;\n this.data = { filepath };\n }\n};\nIndexResetError.code = \"IndexResetError\";\nvar NoCommitError = class _NoCommitError extends BaseError {\n /**\n * @param {string} ref\n */\n constructor(ref) {\n super(\n `\"${ref}\" does not point to any commit. You're maybe working on a repository with no commits yet. `\n );\n this.code = this.name = _NoCommitError.code;\n this.data = { ref };\n }\n};\nNoCommitError.code = \"NoCommitError\";\nvar Errors = /* @__PURE__ */ Object.freeze({\n __proto__: null,\n AlreadyExistsError,\n AmbiguousError,\n CheckoutConflictError,\n CommitNotFetchedError,\n EmptyServerResponseError,\n FastForwardError,\n GitPushError,\n HttpError,\n InternalError,\n InvalidFilepathError,\n InvalidOidError,\n InvalidRefNameError,\n MaxDepthError,\n MergeNotSupportedError,\n MergeConflictError,\n MissingNameError,\n MissingParameterError,\n MultipleGitError,\n NoRefspecError,\n NotFoundError,\n ObjectTypeError,\n ParseError,\n PushRejectedError,\n RemoteCapabilityError,\n SmartHttpError,\n UnknownTransportError,\n UnsafeFilepathError,\n UrlParseError,\n UserCanceledError,\n UnmergedPathsError,\n IndexResetError,\n NoCommitError\n});\nfunction formatAuthor({ name, email, timestamp, timezoneOffset }) {\n timezoneOffset = formatTimezoneOffset(timezoneOffset);\n return `${name} <${email}> ${timestamp} ${timezoneOffset}`;\n}\nfunction formatTimezoneOffset(minutes) {\n const sign = simpleSign(negateExceptForZero(minutes));\n minutes = Math.abs(minutes);\n const hours = Math.floor(minutes / 60);\n minutes -= hours * 60;\n let strHours = String(hours);\n let strMinutes = String(minutes);\n if (strHours.length < 2) strHours = \"0\" + strHours;\n if (strMinutes.length < 2) strMinutes = \"0\" + strMinutes;\n return (sign === -1 ? \"-\" : \"+\") + strHours + strMinutes;\n}\nfunction simpleSign(n) {\n return Math.sign(n) || (Object.is(n, -0) ? -1 : 1);\n}\nfunction negateExceptForZero(n) {\n return n === 0 ? n : -n;\n}\nfunction normalizeNewlines(str) {\n str = str.replace(/\\r/g, \"\");\n str = str.replace(/^\\n+/, \"\");\n str = str.replace(/\\n+$/, \"\") + \"\\n\";\n return str;\n}\nfunction parseAuthor(author) {\n const [, name, email, timestamp, offset] = author.match(\n /^(.*) <(.*)> (.*) (.*)$/\n );\n return {\n name,\n email,\n timestamp: Number(timestamp),\n timezoneOffset: parseTimezoneOffset(offset)\n };\n}\nfunction parseTimezoneOffset(offset) {\n let [, sign, hours, minutes] = offset.match(/(\\+|-)(\\d\\d)(\\d\\d)/);\n minutes = (sign === \"+\" ? 1 : -1) * (Number(hours) * 60 + Number(minutes));\n return negateExceptForZero$1(minutes);\n}\nfunction negateExceptForZero$1(n) {\n return n === 0 ? n : -n;\n}\nvar GitAnnotatedTag = class _GitAnnotatedTag {\n constructor(tag2) {\n if (typeof tag2 === \"string\") {\n this._tag = tag2;\n } else if (Buffer.isBuffer(tag2)) {\n this._tag = tag2.toString(\"utf8\");\n } else if (typeof tag2 === \"object\") {\n this._tag = _GitAnnotatedTag.render(tag2);\n } else {\n throw new InternalError(\n \"invalid type passed to GitAnnotatedTag constructor\"\n );\n }\n }\n static from(tag2) {\n return new _GitAnnotatedTag(tag2);\n }\n static render(obj) {\n return `object ${obj.object}\ntype ${obj.type}\ntag ${obj.tag}\ntagger ${formatAuthor(obj.tagger)}\n\n${obj.message}\n${obj.gpgsig ? obj.gpgsig : \"\"}`;\n }\n justHeaders() {\n return this._tag.slice(0, this._tag.indexOf(\"\\n\\n\"));\n }\n message() {\n const tag2 = this.withoutSignature();\n return tag2.slice(tag2.indexOf(\"\\n\\n\") + 2);\n }\n parse() {\n return Object.assign(this.headers(), {\n message: this.message(),\n gpgsig: this.gpgsig()\n });\n }\n render() {\n return this._tag;\n }\n headers() {\n const headers = this.justHeaders().split(\"\\n\");\n const hs = [];\n for (const h of headers) {\n if (h[0] === \" \") {\n hs[hs.length - 1] += \"\\n\" + h.slice(1);\n } else {\n hs.push(h);\n }\n }\n const obj = {};\n for (const h of hs) {\n const key = h.slice(0, h.indexOf(\" \"));\n const value = h.slice(h.indexOf(\" \") + 1);\n if (Array.isArray(obj[key])) {\n obj[key].push(value);\n } else {\n obj[key] = value;\n }\n }\n if (obj.tagger) {\n obj.tagger = parseAuthor(obj.tagger);\n }\n if (obj.committer) {\n obj.committer = parseAuthor(obj.committer);\n }\n return obj;\n }\n withoutSignature() {\n const tag2 = normalizeNewlines(this._tag);\n if (tag2.indexOf(\"\\n-----BEGIN PGP SIGNATURE-----\") === -1) return tag2;\n return tag2.slice(0, tag2.lastIndexOf(\"\\n-----BEGIN PGP SIGNATURE-----\"));\n }\n gpgsig() {\n if (this._tag.indexOf(\"\\n-----BEGIN PGP SIGNATURE-----\") === -1) return;\n const signature = this._tag.slice(\n this._tag.indexOf(\"-----BEGIN PGP SIGNATURE-----\"),\n this._tag.indexOf(\"-----END PGP SIGNATURE-----\") + \"-----END PGP SIGNATURE-----\".length\n );\n return normalizeNewlines(signature);\n }\n payload() {\n return this.withoutSignature() + \"\\n\";\n }\n toObject() {\n return Buffer.from(this._tag, \"utf8\");\n }\n static async sign(tag2, sign, secretKey) {\n const payload = tag2.payload();\n let { signature } = await sign({ payload, secretKey });\n signature = normalizeNewlines(signature);\n const signedTag = payload + signature;\n return _GitAnnotatedTag.from(signedTag);\n }\n};\nfunction indent(str) {\n return str.trim().split(\"\\n\").map((x) => \" \" + x).join(\"\\n\") + \"\\n\";\n}\nfunction outdent(str) {\n return str.split(\"\\n\").map((x) => x.replace(/^ /, \"\")).join(\"\\n\");\n}\nvar GitCommit = class _GitCommit {\n constructor(commit2) {\n if (typeof commit2 === \"string\") {\n this._commit = commit2;\n } else if (Buffer.isBuffer(commit2)) {\n this._commit = commit2.toString(\"utf8\");\n } else if (typeof commit2 === \"object\") {\n this._commit = _GitCommit.render(commit2);\n } else {\n throw new InternalError(\"invalid type passed to GitCommit constructor\");\n }\n }\n static fromPayloadSignature({ payload, signature }) {\n const headers = _GitCommit.justHeaders(payload);\n const message = _GitCommit.justMessage(payload);\n const commit2 = normalizeNewlines(\n headers + \"\\ngpgsig\" + indent(signature) + \"\\n\" + message\n );\n return new _GitCommit(commit2);\n }\n static from(commit2) {\n return new _GitCommit(commit2);\n }\n toObject() {\n return Buffer.from(this._commit, \"utf8\");\n }\n // Todo: allow setting the headers and message\n headers() {\n return this.parseHeaders();\n }\n // Todo: allow setting the headers and message\n message() {\n return _GitCommit.justMessage(this._commit);\n }\n parse() {\n return Object.assign({ message: this.message() }, this.headers());\n }\n static justMessage(commit2) {\n return normalizeNewlines(commit2.slice(commit2.indexOf(\"\\n\\n\") + 2));\n }\n static justHeaders(commit2) {\n return commit2.slice(0, commit2.indexOf(\"\\n\\n\"));\n }\n parseHeaders() {\n const headers = _GitCommit.justHeaders(this._commit).split(\"\\n\");\n const hs = [];\n for (const h of headers) {\n if (h[0] === \" \") {\n hs[hs.length - 1] += \"\\n\" + h.slice(1);\n } else {\n hs.push(h);\n }\n }\n const obj = {\n parent: []\n };\n for (const h of hs) {\n const key = h.slice(0, h.indexOf(\" \"));\n const value = h.slice(h.indexOf(\" \") + 1);\n if (Array.isArray(obj[key])) {\n obj[key].push(value);\n } else {\n obj[key] = value;\n }\n }\n if (obj.author) {\n obj.author = parseAuthor(obj.author);\n }\n if (obj.committer) {\n obj.committer = parseAuthor(obj.committer);\n }\n return obj;\n }\n static renderHeaders(obj) {\n let headers = \"\";\n if (obj.tree) {\n headers += `tree ${obj.tree}\n`;\n } else {\n headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n`;\n }\n if (obj.parent) {\n if (obj.parent.length === void 0) {\n throw new InternalError(`commit 'parent' property should be an array`);\n }\n for (const p of obj.parent) {\n headers += `parent ${p}\n`;\n }\n }\n const author = obj.author;\n headers += `author ${formatAuthor(author)}\n`;\n const committer = obj.committer || obj.author;\n headers += `committer ${formatAuthor(committer)}\n`;\n if (obj.gpgsig) {\n headers += \"gpgsig\" + indent(obj.gpgsig);\n }\n return headers;\n }\n static render(obj) {\n return _GitCommit.renderHeaders(obj) + \"\\n\" + normalizeNewlines(obj.message);\n }\n render() {\n return this._commit;\n }\n withoutSignature() {\n const commit2 = normalizeNewlines(this._commit);\n if (commit2.indexOf(\"\\ngpgsig\") === -1) return commit2;\n const headers = commit2.slice(0, commit2.indexOf(\"\\ngpgsig\"));\n const message = commit2.slice(\n commit2.indexOf(\"-----END PGP SIGNATURE-----\\n\") + \"-----END PGP SIGNATURE-----\\n\".length\n );\n return normalizeNewlines(headers + \"\\n\" + message);\n }\n isolateSignature() {\n const signature = this._commit.slice(\n this._commit.indexOf(\"-----BEGIN PGP SIGNATURE-----\"),\n this._commit.indexOf(\"-----END PGP SIGNATURE-----\") + \"-----END PGP SIGNATURE-----\".length\n );\n return outdent(signature);\n }\n static async sign(commit2, sign, secretKey) {\n const payload = commit2.withoutSignature();\n const message = _GitCommit.justMessage(commit2._commit);\n let { signature } = await sign({ payload, secretKey });\n signature = normalizeNewlines(signature);\n const headers = _GitCommit.justHeaders(commit2._commit);\n const signedCommit = headers + \"\\ngpgsig\" + indent(signature) + \"\\n\" + message;\n return _GitCommit.from(signedCommit);\n }\n};\nasync function resolveTree({ fs, cache, gitdir, oid }) {\n if (oid === \"4b825dc642cb6eb9a060e54bf8d69288fbee4904\") {\n return { tree: GitTree.from([]), oid };\n }\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type === \"tag\") {\n oid = GitAnnotatedTag.from(object).parse().object;\n return resolveTree({ fs, cache, gitdir, oid });\n }\n if (type === \"commit\") {\n oid = GitCommit.from(object).parse().tree;\n return resolveTree({ fs, cache, gitdir, oid });\n }\n if (type !== \"tree\") {\n throw new ObjectTypeError(oid, type, \"tree\");\n }\n return { tree: GitTree.from(object), oid };\n}\nvar GitWalkerRepo = class {\n constructor({ fs, gitdir, ref, cache }) {\n this.fs = fs;\n this.cache = cache;\n this.gitdir = gitdir;\n this.mapPromise = (async () => {\n const map = /* @__PURE__ */ new Map();\n let oid;\n try {\n oid = await GitRefManager.resolve({ fs, gitdir, ref });\n } catch (e) {\n if (e instanceof NotFoundError) {\n oid = \"4b825dc642cb6eb9a060e54bf8d69288fbee4904\";\n }\n }\n const tree = await resolveTree({ fs, cache: this.cache, gitdir, oid });\n tree.type = \"tree\";\n tree.mode = \"40000\";\n map.set(\".\", tree);\n return map;\n })();\n const walker = this;\n this.ConstructEntry = class TreeEntry {\n constructor(fullpath) {\n this._fullpath = fullpath;\n this._type = false;\n this._mode = false;\n this._stat = false;\n this._content = false;\n this._oid = false;\n }\n async type() {\n return walker.type(this);\n }\n async mode() {\n return walker.mode(this);\n }\n async stat() {\n return walker.stat(this);\n }\n async content() {\n return walker.content(this);\n }\n async oid() {\n return walker.oid(this);\n }\n };\n }\n async readdir(entry) {\n const filepath = entry._fullpath;\n const { fs, cache, gitdir } = this;\n const map = await this.mapPromise;\n const obj = map.get(filepath);\n if (!obj) throw new Error(`No obj for ${filepath}`);\n const oid = obj.oid;\n if (!oid) throw new Error(`No oid for obj ${JSON.stringify(obj)}`);\n if (obj.type !== \"tree\") {\n return null;\n }\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type !== obj.type) {\n throw new ObjectTypeError(oid, type, obj.type);\n }\n const tree = GitTree.from(object);\n for (const entry2 of tree) {\n map.set(join2(filepath, entry2.path), entry2);\n }\n return tree.entries().map((entry2) => join2(filepath, entry2.path));\n }\n async type(entry) {\n if (entry._type === false) {\n const map = await this.mapPromise;\n const { type } = map.get(entry._fullpath);\n entry._type = type;\n }\n return entry._type;\n }\n async mode(entry) {\n if (entry._mode === false) {\n const map = await this.mapPromise;\n const { mode } = map.get(entry._fullpath);\n entry._mode = normalizeMode(parseInt(mode, 8));\n }\n return entry._mode;\n }\n async stat(_entry) {\n }\n async content(entry) {\n if (entry._content === false) {\n const map = await this.mapPromise;\n const { fs, cache, gitdir } = this;\n const obj = map.get(entry._fullpath);\n const oid = obj.oid;\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type !== \"blob\") {\n entry._content = void 0;\n } else {\n entry._content = new Uint8Array(object);\n }\n }\n return entry._content;\n }\n async oid(entry) {\n if (entry._oid === false) {\n const map = await this.mapPromise;\n const obj = map.get(entry._fullpath);\n entry._oid = obj.oid;\n }\n return entry._oid;\n }\n};\nfunction TREE({ ref = \"HEAD\" } = {}) {\n const o = /* @__PURE__ */ Object.create(null);\n Object.defineProperty(o, GitWalkSymbol, {\n value: function({ fs, gitdir, cache }) {\n return new GitWalkerRepo({ fs, gitdir, ref, cache });\n }\n });\n Object.freeze(o);\n return o;\n}\nvar GitWalkerFs = class {\n constructor({ fs, dir, gitdir, cache }) {\n this.fs = fs;\n this.cache = cache;\n this.dir = dir;\n this.gitdir = gitdir;\n this.config = null;\n const walker = this;\n this.ConstructEntry = class WorkdirEntry {\n constructor(fullpath) {\n this._fullpath = fullpath;\n this._type = false;\n this._mode = false;\n this._stat = false;\n this._content = false;\n this._oid = false;\n }\n async type() {\n return walker.type(this);\n }\n async mode() {\n return walker.mode(this);\n }\n async stat() {\n return walker.stat(this);\n }\n async content() {\n return walker.content(this);\n }\n async oid() {\n return walker.oid(this);\n }\n };\n }\n async readdir(entry) {\n const filepath = entry._fullpath;\n const { fs, dir } = this;\n const names = await fs.readdir(join2(dir, filepath));\n if (names === null) return null;\n return names.filter((name) => name !== \".git\").map((name) => join2(filepath, name));\n }\n async type(entry) {\n if (entry._type === false) {\n await entry.stat();\n }\n return entry._type;\n }\n async mode(entry) {\n if (entry._mode === false) {\n await entry.stat();\n }\n return entry._mode;\n }\n async stat(entry) {\n if (entry._stat === false) {\n const { fs, dir } = this;\n let stat = await fs.lstat(`${dir}/${entry._fullpath}`);\n if (!stat) {\n throw new Error(\n `ENOENT: no such file or directory, lstat '${entry._fullpath}'`\n );\n }\n let type = stat.isDirectory() ? \"tree\" : \"blob\";\n if (type === \"blob\" && !stat.isFile() && !stat.isSymbolicLink()) {\n type = \"special\";\n }\n entry._type = type;\n stat = normalizeStats(stat);\n entry._mode = stat.mode;\n if (stat.size === -1 && entry._actualSize) {\n stat.size = entry._actualSize;\n }\n entry._stat = stat;\n }\n return entry._stat;\n }\n async content(entry) {\n if (entry._content === false) {\n const { fs, dir, gitdir } = this;\n if (await entry.type() === \"tree\") {\n entry._content = void 0;\n } else {\n const config = await this._getGitConfig(fs, gitdir);\n const autocrlf = await config.get(\"core.autocrlf\");\n const content = await fs.read(`${dir}/${entry._fullpath}`, { autocrlf });\n entry._actualSize = content.length;\n if (entry._stat && entry._stat.size === -1) {\n entry._stat.size = entry._actualSize;\n }\n entry._content = new Uint8Array(content);\n }\n }\n return entry._content;\n }\n async oid(entry) {\n if (entry._oid === false) {\n const self = this;\n const { fs, gitdir, cache } = this;\n let oid;\n await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n const stage = index3.entriesMap.get(entry._fullpath);\n const stats = await entry.stat();\n const config = await self._getGitConfig(fs, gitdir);\n const filemode = await config.get(\"core.filemode\");\n const trustino = typeof process !== \"undefined\" ? !(process.platform === \"win32\") : true;\n if (!stage || compareStats(stats, stage, filemode, trustino)) {\n const content = await entry.content();\n if (content === void 0) {\n oid = void 0;\n } else {\n oid = await shasum(\n GitObject.wrap({ type: \"blob\", object: content })\n );\n if (stage && oid === stage.oid && (!filemode || stats.mode === stage.mode) && compareStats(stats, stage, filemode, trustino)) {\n index3.insert({\n filepath: entry._fullpath,\n stats,\n oid\n });\n }\n }\n } else {\n oid = stage.oid;\n }\n });\n entry._oid = oid;\n }\n return entry._oid;\n }\n async _getGitConfig(fs, gitdir) {\n if (this.config) {\n return this.config;\n }\n this.config = await GitConfigManager.get({ fs, gitdir });\n return this.config;\n }\n};\nfunction WORKDIR() {\n const o = /* @__PURE__ */ Object.create(null);\n Object.defineProperty(o, GitWalkSymbol, {\n value: function({ fs, dir, gitdir, cache }) {\n return new GitWalkerFs({ fs, dir, gitdir, cache });\n }\n });\n Object.freeze(o);\n return o;\n}\nfunction arrayRange(start, end) {\n const length = end - start;\n return Array.from({ length }, (_, i) => start + i);\n}\nvar flat = typeof Array.prototype.flat === \"undefined\" ? (entries) => entries.reduce((acc, x) => acc.concat(x), []) : (entries) => entries.flat();\nvar RunningMinimum = class {\n constructor() {\n this.value = null;\n }\n consider(value) {\n if (value === null || value === void 0) return;\n if (this.value === null) {\n this.value = value;\n } else if (value < this.value) {\n this.value = value;\n }\n }\n reset() {\n this.value = null;\n }\n};\nfunction* unionOfIterators(sets) {\n const min = new RunningMinimum();\n let minimum;\n const heads = [];\n const numsets = sets.length;\n for (let i = 0; i < numsets; i++) {\n heads[i] = sets[i].next().value;\n if (heads[i] !== void 0) {\n min.consider(heads[i]);\n }\n }\n if (min.value === null) return;\n while (true) {\n const result = [];\n minimum = min.value;\n min.reset();\n for (let i = 0; i < numsets; i++) {\n if (heads[i] !== void 0 && heads[i] === minimum) {\n result[i] = heads[i];\n heads[i] = sets[i].next().value;\n } else {\n result[i] = null;\n }\n if (heads[i] !== void 0) {\n min.consider(heads[i]);\n }\n }\n yield result;\n if (min.value === null) return;\n }\n}\nasync function _walk({\n fs,\n cache,\n dir,\n gitdir,\n trees,\n // @ts-ignore\n map = async (_, entry) => entry,\n // The default reducer is a flatmap that filters out undefineds.\n reduce = async (parent, children) => {\n const flatten = flat(children);\n if (parent !== void 0) flatten.unshift(parent);\n return flatten;\n },\n // The default iterate function walks all children concurrently\n iterate = (walk2, children) => Promise.all([...children].map(walk2))\n}) {\n const walkers = trees.map(\n (proxy) => proxy[GitWalkSymbol]({ fs, dir, gitdir, cache })\n );\n const root = new Array(walkers.length).fill(\".\");\n const range = arrayRange(0, walkers.length);\n const unionWalkerFromReaddir = async (entries) => {\n range.map((i) => {\n const entry = entries[i];\n entries[i] = entry && new walkers[i].ConstructEntry(entry);\n });\n const subdirs = await Promise.all(\n range.map((i) => {\n const entry = entries[i];\n return entry ? walkers[i].readdir(entry) : [];\n })\n );\n const iterators = subdirs.map((array) => {\n return (array === null ? [] : array)[Symbol.iterator]();\n });\n return {\n entries,\n children: unionOfIterators(iterators)\n };\n };\n const walk2 = async (root2) => {\n const { entries, children } = await unionWalkerFromReaddir(root2);\n const fullpath = entries.find((entry) => entry && entry._fullpath)._fullpath;\n const parent = await map(fullpath, entries);\n if (parent !== null) {\n let walkedChildren = await iterate(walk2, children);\n walkedChildren = walkedChildren.filter((x) => x !== void 0);\n return reduce(parent, walkedChildren);\n }\n };\n return walk2(root);\n}\nasync function rmRecursive(fs, filepath) {\n const entries = await fs.readdir(filepath);\n if (entries == null) {\n await fs.rm(filepath);\n } else if (entries.length) {\n await Promise.all(\n entries.map((entry) => {\n const subpath = join2(filepath, entry);\n return fs.lstat(subpath).then((stat) => {\n if (!stat) return;\n return stat.isDirectory() ? rmRecursive(fs, subpath) : fs.rm(subpath);\n });\n })\n ).then(() => fs.rmdir(filepath));\n } else {\n await fs.rmdir(filepath);\n }\n}\nfunction isPromiseLike(obj) {\n return isObject(obj) && isFunction(obj.then) && isFunction(obj.catch);\n}\nfunction isObject(obj) {\n return obj && typeof obj === \"object\";\n}\nfunction isFunction(obj) {\n return typeof obj === \"function\";\n}\nfunction isPromiseFs(fs) {\n const test = (targetFs) => {\n try {\n return targetFs.readFile().catch((e) => e);\n } catch (e) {\n return e;\n }\n };\n return isPromiseLike(test(fs));\n}\nvar commands = [\n \"readFile\",\n \"writeFile\",\n \"mkdir\",\n \"rmdir\",\n \"unlink\",\n \"stat\",\n \"lstat\",\n \"readdir\",\n \"readlink\",\n \"symlink\"\n];\nfunction bindFs(target, fs) {\n if (isPromiseFs(fs)) {\n for (const command of commands) {\n target[`_${command}`] = fs[command].bind(fs);\n }\n } else {\n for (const command of commands) {\n target[`_${command}`] = (0, import_pify.default)(fs[command].bind(fs));\n }\n }\n if (isPromiseFs(fs)) {\n if (fs.rm) target._rm = fs.rm.bind(fs);\n else if (fs.rmdir.length > 1) target._rm = fs.rmdir.bind(fs);\n else target._rm = rmRecursive.bind(null, target);\n } else {\n if (fs.rm) target._rm = (0, import_pify.default)(fs.rm.bind(fs));\n else if (fs.rmdir.length > 2) target._rm = (0, import_pify.default)(fs.rmdir.bind(fs));\n else target._rm = rmRecursive.bind(null, target);\n }\n}\nvar FileSystem = class {\n /**\n * Creates an instance of FileSystem.\n *\n * @param {Object} fs - A file system implementation to wrap.\n */\n constructor(fs) {\n if (typeof fs._original_unwrapped_fs !== \"undefined\") return fs;\n const promises = Object.getOwnPropertyDescriptor(fs, \"promises\");\n if (promises && promises.enumerable) {\n bindFs(this, fs.promises);\n } else {\n bindFs(this, fs);\n }\n this._original_unwrapped_fs = fs;\n }\n /**\n * Return true if a file exists, false if it doesn't exist.\n * Rethrows errors that aren't related to file existence.\n *\n * @param {string} filepath - The path to the file.\n * @param {Object} [options] - Additional options.\n * @returns {Promise<boolean>} - `true` if the file exists, `false` otherwise.\n */\n async exists(filepath, options = {}) {\n try {\n await this._stat(filepath);\n return true;\n } catch (err) {\n if (err.code === \"ENOENT\" || err.code === \"ENOTDIR\" || (err.code || \"\").includes(\"ENS\")) {\n return false;\n } else {\n console.log('Unhandled error in \"FileSystem.exists()\" function', err);\n throw err;\n }\n }\n }\n /**\n * Return the contents of a file if it exists, otherwise returns null.\n *\n * @param {string} filepath - The path to the file.\n * @param {Object} [options] - Options for reading the file.\n * @returns {Promise<Buffer|string|null>} - The file contents, or `null` if the file doesn't exist.\n */\n async read(filepath, options = {}) {\n try {\n let buffer = await this._readFile(filepath, options);\n if (options.autocrlf === \"true\") {\n try {\n buffer = new TextDecoder(\"utf8\", { fatal: true }).decode(buffer);\n buffer = buffer.replace(/\\r\\n/g, \"\\n\");\n buffer = new TextEncoder().encode(buffer);\n } catch (error) {\n }\n }\n if (typeof buffer !== \"string\") {\n buffer = Buffer.from(buffer);\n }\n return buffer;\n } catch (err) {\n return null;\n }\n }\n /**\n * Write a file (creating missing directories if need be) without throwing errors.\n *\n * @param {string} filepath - The path to the file.\n * @param {Buffer|Uint8Array|string} contents - The data to write.\n * @param {Object|string} [options] - Options for writing the file.\n * @returns {Promise<void>}\n */\n async write(filepath, contents, options = {}) {\n try {\n await this._writeFile(filepath, contents, options);\n return;\n } catch (err) {\n await this.mkdir(dirname(filepath));\n await this._writeFile(filepath, contents, options);\n }\n }\n /**\n * Make a directory (or series of nested directories) without throwing an error if it already exists.\n *\n * @param {string} filepath - The path to the directory.\n * @param {boolean} [_selfCall=false] - Internal flag to prevent infinite recursion.\n * @returns {Promise<void>}\n */\n async mkdir(filepath, _selfCall = false) {\n try {\n await this._mkdir(filepath);\n return;\n } catch (err) {\n if (err === null) return;\n if (err.code === \"EEXIST\") return;\n if (_selfCall) throw err;\n if (err.code === \"ENOENT\") {\n const parent = dirname(filepath);\n if (parent === \".\" || parent === \"/\" || parent === filepath) throw err;\n await this.mkdir(parent);\n await this.mkdir(filepath, true);\n }\n }\n }\n /**\n * Delete a file without throwing an error if it is already deleted.\n *\n * @param {string} filepath - The path to the file.\n * @returns {Promise<void>}\n */\n async rm(filepath) {\n try {\n await this._unlink(filepath);\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n }\n }\n /**\n * Delete a directory without throwing an error if it is already deleted.\n *\n * @param {string} filepath - The path to the directory.\n * @param {Object} [opts] - Options for deleting the directory.\n * @returns {Promise<void>}\n */\n async rmdir(filepath, opts) {\n try {\n if (opts && opts.recursive) {\n await this._rm(filepath, opts);\n } else {\n await this._rmdir(filepath);\n }\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n }\n }\n /**\n * Read a directory without throwing an error is the directory doesn't exist\n *\n * @param {string} filepath - The path to the directory.\n * @returns {Promise<string[]|null>} - An array of file names, or `null` if the path is not a directory.\n */\n async readdir(filepath) {\n try {\n const names = await this._readdir(filepath);\n names.sort(compareStrings);\n return names;\n } catch (err) {\n if (err.code === \"ENOTDIR\") return null;\n return [];\n }\n }\n /**\n * Return a flat list of all the files nested inside a directory\n *\n * Based on an elegant concurrent recursive solution from SO\n * https://stackoverflow.com/a/45130990/2168416\n *\n * @param {string} dir - The directory to read.\n * @returns {Promise<string[]>} - A flat list of all files in the directory.\n */\n async readdirDeep(dir) {\n const subdirs = await this._readdir(dir);\n const files = await Promise.all(\n subdirs.map(async (subdir) => {\n const res = dir + \"/\" + subdir;\n return (await this._stat(res)).isDirectory() ? this.readdirDeep(res) : res;\n })\n );\n return files.reduce((a, f) => a.concat(f), []);\n }\n /**\n * Return the Stats of a file/symlink if it exists, otherwise returns null.\n * Rethrows errors that aren't related to file existence.\n *\n * @param {string} filename - The path to the file or symlink.\n * @returns {Promise<Object|null>} - The stats object, or `null` if the file doesn't exist.\n */\n async lstat(filename) {\n try {\n const stats = await this._lstat(filename);\n return stats;\n } catch (err) {\n if (err.code === \"ENOENT\" || (err.code || \"\").includes(\"ENS\")) {\n return null;\n }\n throw err;\n }\n }\n /**\n * Reads the contents of a symlink if it exists, otherwise returns null.\n * Rethrows errors that aren't related to file existence.\n *\n * @param {string} filename - The path to the symlink.\n * @param {Object} [opts={ encoding: 'buffer' }] - Options for reading the symlink.\n * @returns {Promise<Buffer|null>} - The symlink target, or `null` if it doesn't exist.\n */\n async readlink(filename, opts = { encoding: \"buffer\" }) {\n try {\n const link = await this._readlink(filename, opts);\n return Buffer.isBuffer(link) ? link : Buffer.from(link);\n } catch (err) {\n if (err.code === \"ENOENT\" || (err.code || \"\").includes(\"ENS\")) {\n return null;\n }\n throw err;\n }\n }\n /**\n * Write the contents of buffer to a symlink.\n *\n * @param {string} filename - The path to the symlink.\n * @param {Buffer} buffer - The symlink target.\n * @returns {Promise<void>}\n */\n async writelink(filename, buffer) {\n return this._symlink(buffer.toString(\"utf8\"), filename);\n }\n};\nfunction assertParameter(name, value) {\n if (value === void 0) {\n throw new MissingParameterError(name);\n }\n}\nasync function modified(entry, base) {\n if (!entry && !base) return false;\n if (entry && !base) return true;\n if (!entry && base) return true;\n if (await entry.type() === \"tree\" && await base.type() === \"tree\") {\n return false;\n }\n if (await entry.type() === await base.type() && await entry.mode() === await base.mode() && await entry.oid() === await base.oid()) {\n return false;\n }\n return true;\n}\nasync function abortMerge({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n commit: commit2 = \"HEAD\",\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"dir\", dir);\n assertParameter(\"gitdir\", gitdir);\n const fs = new FileSystem(_fs);\n const trees = [TREE({ ref: commit2 }), WORKDIR(), STAGE()];\n let unmergedPaths = [];\n await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n unmergedPaths = index3.unmergedPaths;\n });\n const results = await _walk({\n fs,\n cache,\n dir,\n gitdir,\n trees,\n map: async function(path, [head, workdir, index3]) {\n const staged = !await modified(workdir, index3);\n const unmerged = unmergedPaths.includes(path);\n const unmodified = !await modified(index3, head);\n if (staged || unmerged) {\n return head ? {\n path,\n mode: await head.mode(),\n oid: await head.oid(),\n type: await head.type(),\n content: await head.content()\n } : void 0;\n }\n if (unmodified) return false;\n else throw new IndexResetError(path);\n }\n });\n await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n for (const entry of results) {\n if (entry === false) continue;\n if (!entry) {\n await fs.rmdir(`${dir}/${entry.path}`, { recursive: true });\n index3.delete({ filepath: entry.path });\n continue;\n }\n if (entry.type === \"blob\") {\n const content = new TextDecoder().decode(entry.content);\n await fs.write(`${dir}/${entry.path}`, content, { mode: entry.mode });\n index3.insert({\n filepath: entry.path,\n oid: entry.oid,\n stage: 0\n });\n }\n }\n });\n } catch (err) {\n err.caller = \"git.abortMerge\";\n throw err;\n }\n}\nvar GitIgnoreManager = class {\n /**\n * Determines whether a given file is ignored based on `.gitignore` rules and exclusion files.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} args.dir - The working directory.\n * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {string} args.filepath - The path of the file to check.\n * @returns {Promise<boolean>} - `true` if the file is ignored, `false` otherwise.\n */\n static async isIgnored({ fs, dir, gitdir = join2(dir, \".git\"), filepath }) {\n if (basename(filepath) === \".git\") return true;\n if (filepath === \".\") return false;\n let excludes = \"\";\n const excludesFile = join2(gitdir, \"info\", \"exclude\");\n if (await fs.exists(excludesFile)) {\n excludes = await fs.read(excludesFile, \"utf8\");\n }\n const pairs = [\n {\n gitignore: join2(dir, \".gitignore\"),\n filepath\n }\n ];\n const pieces = filepath.split(\"/\").filter(Boolean);\n for (let i = 1; i < pieces.length; i++) {\n const folder = pieces.slice(0, i).join(\"/\");\n const file = pieces.slice(i).join(\"/\");\n pairs.push({\n gitignore: join2(dir, folder, \".gitignore\"),\n filepath: file\n });\n }\n let ignoredStatus = false;\n for (const p of pairs) {\n let file;\n try {\n file = await fs.read(p.gitignore, \"utf8\");\n } catch (err) {\n if (err.code === \"NOENT\") continue;\n }\n const ign = (0, import_ignore.default)().add(excludes);\n ign.add(file);\n const parentdir = dirname(p.filepath);\n if (parentdir !== \".\" && ign.ignores(parentdir)) return true;\n if (ignoredStatus) {\n ignoredStatus = !ign.test(p.filepath).unignored;\n } else {\n ignoredStatus = ign.test(p.filepath).ignored;\n }\n }\n return ignoredStatus;\n }\n};\nasync function writeObjectLoose({ fs, gitdir, object, format, oid }) {\n if (format !== \"deflated\") {\n throw new InternalError(\n \"GitObjectStoreLoose expects objects to write to be in deflated format\"\n );\n }\n const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`;\n const filepath = `${gitdir}/${source}`;\n if (!await fs.exists(filepath)) await fs.write(filepath, object);\n}\nvar supportsCompressionStream = null;\nasync function deflate(buffer) {\n if (supportsCompressionStream === null) {\n supportsCompressionStream = testCompressionStream();\n }\n return supportsCompressionStream ? browserDeflate(buffer) : import_pako.default.deflate(buffer);\n}\nasync function browserDeflate(buffer) {\n const cs = new CompressionStream(\"deflate\");\n const c = new Blob([buffer]).stream().pipeThrough(cs);\n return new Uint8Array(await new Response(c).arrayBuffer());\n}\nfunction testCompressionStream() {\n try {\n const cs = new CompressionStream(\"deflate\");\n cs.writable.close();\n const stream = new Blob([]).stream();\n stream.cancel();\n return true;\n } catch (_) {\n return false;\n }\n}\nasync function _writeObject({\n fs,\n gitdir,\n type,\n object,\n format = \"content\",\n oid = void 0,\n dryRun = false\n}) {\n if (format !== \"deflated\") {\n if (format !== \"wrapped\") {\n object = GitObject.wrap({ type, object });\n }\n oid = await shasum(object);\n object = Buffer.from(await deflate(object));\n }\n if (!dryRun) {\n await writeObjectLoose({ fs, gitdir, object, format: \"deflated\", oid });\n }\n return oid;\n}\nfunction posixifyPathBuffer(buffer) {\n let idx;\n while (~(idx = buffer.indexOf(92))) buffer[idx] = 47;\n return buffer;\n}\nasync function add({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath,\n cache = {},\n force = false,\n parallel = true\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"dir\", dir);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"filepath\", filepath);\n const fs = new FileSystem(_fs);\n await GitIndexManager.acquire({ fs, gitdir, cache }, async (index3) => {\n const config = await GitConfigManager.get({ fs, gitdir });\n const autocrlf = await config.get(\"core.autocrlf\");\n return addToIndex({\n dir,\n gitdir,\n fs,\n filepath,\n index: index3,\n force,\n parallel,\n autocrlf\n });\n });\n } catch (err) {\n err.caller = \"git.add\";\n throw err;\n }\n}\nasync function addToIndex({\n dir,\n gitdir,\n fs,\n filepath,\n index: index3,\n force,\n parallel,\n autocrlf\n}) {\n filepath = Array.isArray(filepath) ? filepath : [filepath];\n const promises = filepath.map(async (currentFilepath) => {\n if (!force) {\n const ignored = await GitIgnoreManager.isIgnored({\n fs,\n dir,\n gitdir,\n filepath: currentFilepath\n });\n if (ignored) return;\n }\n const stats = await fs.lstat(join2(dir, currentFilepath));\n if (!stats) throw new NotFoundError(currentFilepath);\n if (stats.isDirectory()) {\n const children = await fs.readdir(join2(dir, currentFilepath));\n if (parallel) {\n const promises2 = children.map(\n (child) => addToIndex({\n dir,\n gitdir,\n fs,\n filepath: [join2(currentFilepath, child)],\n index: index3,\n force,\n parallel,\n autocrlf\n })\n );\n await Promise.all(promises2);\n } else {\n for (const child of children) {\n await addToIndex({\n dir,\n gitdir,\n fs,\n filepath: [join2(currentFilepath, child)],\n index: index3,\n force,\n parallel,\n autocrlf\n });\n }\n }\n } else {\n const object = stats.isSymbolicLink() ? await fs.readlink(join2(dir, currentFilepath)).then(posixifyPathBuffer) : await fs.read(join2(dir, currentFilepath), { autocrlf });\n if (object === null) throw new NotFoundError(currentFilepath);\n const oid = await _writeObject({ fs, gitdir, type: \"blob\", object });\n index3.insert({ filepath: currentFilepath, stats, oid });\n }\n });\n const settledPromises = await Promise.allSettled(promises);\n const rejectedPromises = settledPromises.filter((settle) => settle.status === \"rejected\").map((settle) => settle.reason);\n if (rejectedPromises.length > 1) {\n throw new MultipleGitError(rejectedPromises);\n }\n if (rejectedPromises.length === 1) {\n throw rejectedPromises[0];\n }\n const fulfilledPromises = settledPromises.filter((settle) => settle.status === \"fulfilled\" && settle.value).map((settle) => settle.value);\n return fulfilledPromises;\n}\nasync function _getConfig({ fs, gitdir, path }) {\n const config = await GitConfigManager.get({ fs, gitdir });\n return config.get(path);\n}\nfunction assignDefined(target, ...sources) {\n for (const source of sources) {\n if (source) {\n for (const key of Object.keys(source)) {\n const val = source[key];\n if (val !== void 0) {\n target[key] = val;\n }\n }\n }\n }\n return target;\n}\nasync function normalizeAuthorObject({ fs, gitdir, author, commit: commit2 }) {\n const timestamp = Math.floor(Date.now() / 1e3);\n const defaultAuthor = {\n name: await _getConfig({ fs, gitdir, path: \"user.name\" }),\n email: await _getConfig({ fs, gitdir, path: \"user.email\" }) || \"\",\n // author.email is allowed to be empty string\n timestamp,\n timezoneOffset: new Date(timestamp * 1e3).getTimezoneOffset()\n };\n const normalizedAuthor = assignDefined(\n {},\n defaultAuthor,\n commit2 ? commit2.author : void 0,\n author\n );\n if (normalizedAuthor.name === void 0) {\n return void 0;\n }\n return normalizedAuthor;\n}\nasync function normalizeCommitterObject({\n fs,\n gitdir,\n author,\n committer,\n commit: commit2\n}) {\n const timestamp = Math.floor(Date.now() / 1e3);\n const defaultCommitter = {\n name: await _getConfig({ fs, gitdir, path: \"user.name\" }),\n email: await _getConfig({ fs, gitdir, path: \"user.email\" }) || \"\",\n // committer.email is allowed to be empty string\n timestamp,\n timezoneOffset: new Date(timestamp * 1e3).getTimezoneOffset()\n };\n const normalizedCommitter = assignDefined(\n {},\n defaultCommitter,\n commit2 ? commit2.committer : void 0,\n author,\n committer\n );\n if (normalizedCommitter.name === void 0) {\n return void 0;\n }\n return normalizedCommitter;\n}\nasync function resolveCommit({ fs, cache, gitdir, oid }) {\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type === \"tag\") {\n oid = GitAnnotatedTag.from(object).parse().object;\n return resolveCommit({ fs, cache, gitdir, oid });\n }\n if (type !== \"commit\") {\n throw new ObjectTypeError(oid, type, \"commit\");\n }\n return { commit: GitCommit.from(object), oid };\n}\nasync function _readCommit({ fs, cache, gitdir, oid }) {\n const { commit: commit2, oid: commitOid } = await resolveCommit({\n fs,\n cache,\n gitdir,\n oid\n });\n const result = {\n oid: commitOid,\n commit: commit2.parse(),\n payload: commit2.withoutSignature()\n };\n return result;\n}\nasync function _commit({\n fs,\n cache,\n onSign,\n gitdir,\n message,\n author: _author,\n committer: _committer,\n signingKey,\n amend = false,\n dryRun = false,\n noUpdateBranch = false,\n ref,\n parent,\n tree\n}) {\n let initialCommit = false;\n if (!ref) {\n ref = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: \"HEAD\",\n depth: 2\n });\n }\n let refOid, refCommit;\n try {\n refOid = await GitRefManager.resolve({\n fs,\n gitdir,\n ref\n });\n refCommit = await _readCommit({ fs, gitdir, oid: refOid, cache: {} });\n } catch {\n initialCommit = true;\n }\n if (amend && initialCommit) {\n throw new NoCommitError(ref);\n }\n const author = !amend ? await normalizeAuthorObject({ fs, gitdir, author: _author }) : await normalizeAuthorObject({\n fs,\n gitdir,\n author: _author,\n commit: refCommit.commit\n });\n if (!author) throw new MissingNameError(\"author\");\n const committer = !amend ? await normalizeCommitterObject({\n fs,\n gitdir,\n author,\n committer: _committer\n }) : await normalizeCommitterObject({\n fs,\n gitdir,\n author,\n committer: _committer,\n commit: refCommit.commit\n });\n if (!committer) throw new MissingNameError(\"committer\");\n return GitIndexManager.acquire(\n { fs, gitdir, cache, allowUnmerged: false },\n async function(index3) {\n const inodes = flatFileListToDirectoryStructure(index3.entries);\n const inode = inodes.get(\".\");\n if (!tree) {\n tree = await constructTree({ fs, gitdir, inode, dryRun });\n }\n if (!parent) {\n if (!amend) {\n parent = refOid ? [refOid] : [];\n } else {\n parent = refCommit.commit.parent;\n }\n } else {\n parent = await Promise.all(\n parent.map((p) => {\n return GitRefManager.resolve({ fs, gitdir, ref: p });\n })\n );\n }\n if (!message) {\n if (!amend) {\n throw new MissingParameterError(\"message\");\n } else {\n message = refCommit.commit.message;\n }\n }\n let comm = GitCommit.from({\n tree,\n parent,\n author,\n committer,\n message\n });\n if (signingKey) {\n comm = await GitCommit.sign(comm, onSign, signingKey);\n }\n const oid = await _writeObject({\n fs,\n gitdir,\n type: \"commit\",\n object: comm.toObject(),\n dryRun\n });\n if (!noUpdateBranch && !dryRun) {\n await GitRefManager.writeRef({\n fs,\n gitdir,\n ref,\n value: oid\n });\n }\n return oid;\n }\n );\n}\nasync function constructTree({ fs, gitdir, inode, dryRun }) {\n const children = inode.children;\n for (const inode2 of children) {\n if (inode2.type === \"tree\") {\n inode2.metadata.mode = \"040000\";\n inode2.metadata.oid = await constructTree({ fs, gitdir, inode: inode2, dryRun });\n }\n }\n const entries = children.map((inode2) => ({\n mode: inode2.metadata.mode,\n path: inode2.basename,\n oid: inode2.metadata.oid,\n type: inode2.type\n }));\n const tree = GitTree.from(entries);\n const oid = await _writeObject({\n fs,\n gitdir,\n type: \"tree\",\n object: tree.toObject(),\n dryRun\n });\n return oid;\n}\nasync function resolveFilepath({ fs, cache, gitdir, oid, filepath }) {\n if (filepath.startsWith(\"/\")) {\n throw new InvalidFilepathError(\"leading-slash\");\n } else if (filepath.endsWith(\"/\")) {\n throw new InvalidFilepathError(\"trailing-slash\");\n }\n const _oid = oid;\n const result = await resolveTree({ fs, cache, gitdir, oid });\n const tree = result.tree;\n if (filepath === \"\") {\n oid = result.oid;\n } else {\n const pathArray = filepath.split(\"/\");\n oid = await _resolveFilepath({\n fs,\n cache,\n gitdir,\n tree,\n pathArray,\n oid: _oid,\n filepath\n });\n }\n return oid;\n}\nasync function _resolveFilepath({\n fs,\n cache,\n gitdir,\n tree,\n pathArray,\n oid,\n filepath\n}) {\n const name = pathArray.shift();\n for (const entry of tree) {\n if (entry.path === name) {\n if (pathArray.length === 0) {\n return entry.oid;\n } else {\n const { type, object } = await _readObject({\n fs,\n cache,\n gitdir,\n oid: entry.oid\n });\n if (type !== \"tree\") {\n throw new ObjectTypeError(oid, type, \"tree\", filepath);\n }\n tree = GitTree.from(object);\n return _resolveFilepath({\n fs,\n cache,\n gitdir,\n tree,\n pathArray,\n oid,\n filepath\n });\n }\n }\n }\n throw new NotFoundError(`file or directory found at \"${oid}:${filepath}\"`);\n}\nasync function _readTree({\n fs,\n cache,\n gitdir,\n oid,\n filepath = void 0\n}) {\n if (filepath !== void 0) {\n oid = await resolveFilepath({ fs, cache, gitdir, oid, filepath });\n }\n const { tree, oid: treeOid } = await resolveTree({ fs, cache, gitdir, oid });\n const result = {\n oid: treeOid,\n tree: tree.entries()\n };\n return result;\n}\nasync function _writeTree({ fs, gitdir, tree }) {\n const object = GitTree.from(tree).toObject();\n const oid = await _writeObject({\n fs,\n gitdir,\n type: \"tree\",\n object,\n format: \"content\"\n });\n return oid;\n}\nasync function _addNote({\n fs,\n cache,\n onSign,\n gitdir,\n ref,\n oid,\n note,\n force,\n author,\n committer,\n signingKey\n}) {\n let parent;\n try {\n parent = await GitRefManager.resolve({ gitdir, fs, ref });\n } catch (err) {\n if (!(err instanceof NotFoundError)) {\n throw err;\n }\n }\n const result = await _readTree({\n fs,\n cache,\n gitdir,\n oid: parent || \"4b825dc642cb6eb9a060e54bf8d69288fbee4904\"\n });\n let tree = result.tree;\n if (force) {\n tree = tree.filter((entry) => entry.path !== oid);\n } else {\n for (const entry of tree) {\n if (entry.path === oid) {\n throw new AlreadyExistsError(\"note\", oid);\n }\n }\n }\n if (typeof note === \"string\") {\n note = Buffer.from(note, \"utf8\");\n }\n const noteOid = await _writeObject({\n fs,\n gitdir,\n type: \"blob\",\n object: note,\n format: \"content\"\n });\n tree.push({ mode: \"100644\", path: oid, oid: noteOid, type: \"blob\" });\n const treeOid = await _writeTree({\n fs,\n gitdir,\n tree\n });\n const commitOid = await _commit({\n fs,\n cache,\n onSign,\n gitdir,\n ref,\n tree: treeOid,\n parent: parent && [parent],\n message: `Note added by 'isomorphic-git addNote'\n`,\n author,\n committer,\n signingKey\n });\n return commitOid;\n}\nasync function addNote({\n fs: _fs,\n onSign,\n dir,\n gitdir = join2(dir, \".git\"),\n ref = \"refs/notes/commits\",\n oid,\n note,\n force,\n author: _author,\n committer: _committer,\n signingKey,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n assertParameter(\"note\", note);\n if (signingKey) {\n assertParameter(\"onSign\", onSign);\n }\n const fs = new FileSystem(_fs);\n const author = await normalizeAuthorObject({ fs, gitdir, author: _author });\n if (!author) throw new MissingNameError(\"author\");\n const committer = await normalizeCommitterObject({\n fs,\n gitdir,\n author,\n committer: _committer\n });\n if (!committer) throw new MissingNameError(\"committer\");\n return await _addNote({\n fs: new FileSystem(fs),\n cache,\n onSign,\n gitdir,\n ref,\n oid,\n note,\n force,\n author,\n committer,\n signingKey\n });\n } catch (err) {\n err.caller = \"git.addNote\";\n throw err;\n }\n}\nasync function _addRemote({ fs, gitdir, remote, url, force }) {\n if (!(0, import_is_git_ref_name_valid.default)(remote, true)) {\n throw new InvalidRefNameError(remote, import_clean_git_ref.default.clean(remote));\n }\n const config = await GitConfigManager.get({ fs, gitdir });\n if (!force) {\n const remoteNames = await config.getSubsections(\"remote\");\n if (remoteNames.includes(remote)) {\n if (url !== await config.get(`remote.${remote}.url`)) {\n throw new AlreadyExistsError(\"remote\", remote);\n }\n }\n }\n await config.set(`remote.${remote}.url`, url);\n await config.set(\n `remote.${remote}.fetch`,\n `+refs/heads/*:refs/remotes/${remote}/*`\n );\n await GitConfigManager.save({ fs, gitdir, config });\n}\nasync function addRemote({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n remote,\n url,\n force = false\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"remote\", remote);\n assertParameter(\"url\", url);\n return await _addRemote({\n fs: new FileSystem(fs),\n gitdir,\n remote,\n url,\n force\n });\n } catch (err) {\n err.caller = \"git.addRemote\";\n throw err;\n }\n}\nasync function _annotatedTag({\n fs,\n cache,\n onSign,\n gitdir,\n ref,\n tagger,\n message = ref,\n gpgsig,\n object,\n signingKey,\n force = false\n}) {\n ref = ref.startsWith(\"refs/tags/\") ? ref : `refs/tags/${ref}`;\n if (!force && await GitRefManager.exists({ fs, gitdir, ref })) {\n throw new AlreadyExistsError(\"tag\", ref);\n }\n const oid = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: object || \"HEAD\"\n });\n const { type } = await _readObject({ fs, cache, gitdir, oid });\n let tagObject = GitAnnotatedTag.from({\n object: oid,\n type,\n tag: ref.replace(\"refs/tags/\", \"\"),\n tagger,\n message,\n gpgsig\n });\n if (signingKey) {\n tagObject = await GitAnnotatedTag.sign(tagObject, onSign, signingKey);\n }\n const value = await _writeObject({\n fs,\n gitdir,\n type: \"tag\",\n object: tagObject.toObject()\n });\n await GitRefManager.writeRef({ fs, gitdir, ref, value });\n}\nasync function annotatedTag({\n fs: _fs,\n onSign,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n tagger: _tagger,\n message = ref,\n gpgsig,\n object,\n signingKey,\n force = false,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n if (signingKey) {\n assertParameter(\"onSign\", onSign);\n }\n const fs = new FileSystem(_fs);\n const tagger = await normalizeAuthorObject({ fs, gitdir, author: _tagger });\n if (!tagger) throw new MissingNameError(\"tagger\");\n return await _annotatedTag({\n fs,\n cache,\n onSign,\n gitdir,\n ref,\n tagger,\n message,\n gpgsig,\n object,\n signingKey,\n force\n });\n } catch (err) {\n err.caller = \"git.annotatedTag\";\n throw err;\n }\n}\nasync function _branch({\n fs,\n gitdir,\n ref,\n object,\n checkout: checkout2 = false,\n force = false\n}) {\n if (!(0, import_is_git_ref_name_valid.default)(ref, true)) {\n throw new InvalidRefNameError(ref, import_clean_git_ref.default.clean(ref));\n }\n const fullref = `refs/heads/${ref}`;\n if (!force) {\n const exist = await GitRefManager.exists({ fs, gitdir, ref: fullref });\n if (exist) {\n throw new AlreadyExistsError(\"branch\", ref, false);\n }\n }\n let oid;\n try {\n oid = await GitRefManager.resolve({ fs, gitdir, ref: object || \"HEAD\" });\n } catch (e) {\n }\n if (oid) {\n await GitRefManager.writeRef({ fs, gitdir, ref: fullref, value: oid });\n }\n if (checkout2) {\n await GitRefManager.writeSymbolicRef({\n fs,\n gitdir,\n ref: \"HEAD\",\n value: fullref\n });\n }\n}\nasync function branch({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n object,\n checkout: checkout2 = false,\n force = false\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n return await _branch({\n fs: new FileSystem(fs),\n gitdir,\n ref,\n object,\n checkout: checkout2,\n force\n });\n } catch (err) {\n err.caller = \"git.branch\";\n throw err;\n }\n}\nvar worthWalking = (filepath, root) => {\n if (filepath === \".\" || root == null || root.length === 0 || root === \".\") {\n return true;\n }\n const filepathPrefix = filepath.endsWith(\"/\") ? filepath : `${filepath}/`;\n const rootPrefix = root.endsWith(\"/\") ? root : `${root}/`;\n return filepath === root || filepath.startsWith(rootPrefix) || root.startsWith(filepathPrefix);\n};\nasync function _checkout({\n fs,\n cache,\n onProgress,\n onPostCheckout,\n dir,\n gitdir,\n remote,\n ref,\n filepaths,\n noCheckout,\n noUpdateHead,\n dryRun,\n force,\n track = true,\n nonBlocking = false,\n batchSize = 100\n}) {\n let oldOid;\n if (onPostCheckout) {\n try {\n oldOid = await GitRefManager.resolve({ fs, gitdir, ref: \"HEAD\" });\n } catch (err) {\n oldOid = \"0000000000000000000000000000000000000000\";\n }\n }\n let oid;\n try {\n oid = await GitRefManager.resolve({ fs, gitdir, ref });\n } catch (err) {\n if (ref === \"HEAD\") throw err;\n const remoteRef = `${remote}/${ref}`;\n oid = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: remoteRef\n });\n if (track) {\n const config = await GitConfigManager.get({ fs, gitdir });\n await config.set(`branch.${ref}.remote`, remote);\n await config.set(`branch.${ref}.merge`, `refs/heads/${ref}`);\n await GitConfigManager.save({ fs, gitdir, config });\n }\n await GitRefManager.writeRef({\n fs,\n gitdir,\n ref: `refs/heads/${ref}`,\n value: oid\n });\n }\n if (!noCheckout) {\n let ops;\n try {\n ops = await analyze({\n fs,\n cache,\n onProgress,\n dir,\n gitdir,\n ref,\n force,\n filepaths\n });\n } catch (err) {\n if (err instanceof NotFoundError && err.data.what === oid) {\n throw new CommitNotFetchedError(ref, oid);\n } else {\n throw err;\n }\n }\n const conflicts = ops.filter(([method]) => method === \"conflict\").map(([method, fullpath]) => fullpath);\n if (conflicts.length > 0) {\n throw new CheckoutConflictError(conflicts);\n }\n const errors = ops.filter(([method]) => method === \"error\").map(([method, fullpath]) => fullpath);\n if (errors.length > 0) {\n throw new InternalError(errors.join(\", \"));\n }\n if (dryRun) {\n if (onPostCheckout) {\n await onPostCheckout({\n previousHead: oldOid,\n newHead: oid,\n type: filepaths != null && filepaths.length > 0 ? \"file\" : \"branch\"\n });\n }\n return;\n }\n let count = 0;\n const total = ops.length;\n await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n await Promise.all(\n ops.filter(\n ([method]) => method === \"delete\" || method === \"delete-index\"\n ).map(async function([method, fullpath]) {\n const filepath = `${dir}/${fullpath}`;\n if (method === \"delete\") {\n await fs.rm(filepath);\n }\n index3.delete({ filepath: fullpath });\n if (onProgress) {\n await onProgress({\n phase: \"Updating workdir\",\n loaded: ++count,\n total\n });\n }\n })\n );\n });\n await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n for (const [method, fullpath] of ops) {\n if (method === \"rmdir\" || method === \"rmdir-index\") {\n const filepath = `${dir}/${fullpath}`;\n try {\n if (method === \"rmdir\") {\n await fs.rmdir(filepath);\n }\n index3.delete({ filepath: fullpath });\n if (onProgress) {\n await onProgress({\n phase: \"Updating workdir\",\n loaded: ++count,\n total\n });\n }\n } catch (e) {\n if (e.code === \"ENOTEMPTY\") {\n console.log(\n `Did not delete ${fullpath} because directory is not empty`\n );\n } else {\n throw e;\n }\n }\n }\n }\n });\n await Promise.all(\n ops.filter(([method]) => method === \"mkdir\" || method === \"mkdir-index\").map(async function([_, fullpath]) {\n const filepath = `${dir}/${fullpath}`;\n await fs.mkdir(filepath);\n if (onProgress) {\n await onProgress({\n phase: \"Updating workdir\",\n loaded: ++count,\n total\n });\n }\n })\n );\n if (nonBlocking) {\n const eligibleOps = ops.filter(\n ([method]) => method === \"create\" || method === \"create-index\" || method === \"update\" || method === \"mkdir-index\"\n );\n const updateWorkingDirResults = await batchAllSettled(\n \"Update Working Dir\",\n eligibleOps.map(\n ([method, fullpath, oid2, mode, chmod]) => () => updateWorkingDir({ fs, cache, gitdir, dir }, [\n method,\n fullpath,\n oid2,\n mode,\n chmod\n ])\n ),\n onProgress,\n batchSize\n );\n await GitIndexManager.acquire(\n { fs, gitdir, cache, allowUnmerged: true },\n async function(index3) {\n await batchAllSettled(\n \"Update Index\",\n updateWorkingDirResults.map(\n ([fullpath, oid2, stats]) => () => updateIndex({ index: index3, fullpath, oid: oid2, stats })\n ),\n onProgress,\n batchSize\n );\n }\n );\n } else {\n await GitIndexManager.acquire(\n { fs, gitdir, cache, allowUnmerged: true },\n async function(index3) {\n await Promise.all(\n ops.filter(\n ([method]) => method === \"create\" || method === \"create-index\" || method === \"update\" || method === \"mkdir-index\"\n ).map(async function([method, fullpath, oid2, mode, chmod]) {\n const filepath = `${dir}/${fullpath}`;\n try {\n if (method !== \"create-index\" && method !== \"mkdir-index\") {\n const { object } = await _readObject({\n fs,\n cache,\n gitdir,\n oid: oid2\n });\n if (chmod) {\n await fs.rm(filepath);\n }\n if (mode === 33188) {\n await fs.write(filepath, object);\n } else if (mode === 33261) {\n await fs.write(filepath, object, { mode: 511 });\n } else if (mode === 40960) {\n await fs.writelink(filepath, object);\n } else {\n throw new InternalError(\n `Invalid mode 0o${mode.toString(\n 8\n )} detected in blob ${oid2}`\n );\n }\n }\n const stats = await fs.lstat(filepath);\n if (mode === 33261) {\n stats.mode = 493;\n }\n if (method === \"mkdir-index\") {\n stats.mode = 57344;\n }\n index3.insert({\n filepath: fullpath,\n stats,\n oid: oid2\n });\n if (onProgress) {\n await onProgress({\n phase: \"Updating workdir\",\n loaded: ++count,\n total\n });\n }\n } catch (e) {\n console.log(e);\n }\n })\n );\n }\n );\n }\n if (onPostCheckout) {\n await onPostCheckout({\n previousHead: oldOid,\n newHead: oid,\n type: filepaths != null && filepaths.length > 0 ? \"file\" : \"branch\"\n });\n }\n }\n if (!noUpdateHead) {\n const fullRef = await GitRefManager.expand({ fs, gitdir, ref });\n if (fullRef.startsWith(\"refs/heads\")) {\n await GitRefManager.writeSymbolicRef({\n fs,\n gitdir,\n ref: \"HEAD\",\n value: fullRef\n });\n } else {\n await GitRefManager.writeRef({ fs, gitdir, ref: \"HEAD\", value: oid });\n }\n }\n}\nasync function analyze({\n fs,\n cache,\n onProgress,\n dir,\n gitdir,\n ref,\n force,\n filepaths\n}) {\n let count = 0;\n return _walk({\n fs,\n cache,\n dir,\n gitdir,\n trees: [TREE({ ref }), WORKDIR(), STAGE()],\n map: async function(fullpath, [commit2, workdir, stage]) {\n if (fullpath === \".\") return;\n if (filepaths && !filepaths.some((base) => worthWalking(fullpath, base))) {\n return null;\n }\n if (onProgress) {\n await onProgress({ phase: \"Analyzing workdir\", loaded: ++count });\n }\n const key = [!!stage, !!commit2, !!workdir].map(Number).join(\"\");\n switch (key) {\n // Impossible case.\n case \"000\":\n return;\n // Ignore workdir files that are not tracked and not part of the new commit.\n case \"001\":\n if (force && filepaths && filepaths.includes(fullpath)) {\n return [\"delete\", fullpath];\n }\n return;\n // New entries\n case \"010\": {\n switch (await commit2.type()) {\n case \"tree\": {\n return [\"mkdir\", fullpath];\n }\n case \"blob\": {\n return [\n \"create\",\n fullpath,\n await commit2.oid(),\n await commit2.mode()\n ];\n }\n case \"commit\": {\n return [\n \"mkdir-index\",\n fullpath,\n await commit2.oid(),\n await commit2.mode()\n ];\n }\n default: {\n return [\n \"error\",\n `new entry Unhandled type ${await commit2.type()}`\n ];\n }\n }\n }\n // New entries but there is already something in the workdir there.\n case \"011\": {\n switch (`${await commit2.type()}-${await workdir.type()}`) {\n case \"tree-tree\": {\n return;\n }\n case \"tree-blob\":\n case \"blob-tree\": {\n return [\"conflict\", fullpath];\n }\n case \"blob-blob\": {\n if (await commit2.oid() !== await workdir.oid()) {\n if (force) {\n return [\n \"update\",\n fullpath,\n await commit2.oid(),\n await commit2.mode(),\n await commit2.mode() !== await workdir.mode()\n ];\n } else {\n return [\"conflict\", fullpath];\n }\n } else {\n if (await commit2.mode() !== await workdir.mode()) {\n if (force) {\n return [\n \"update\",\n fullpath,\n await commit2.oid(),\n await commit2.mode(),\n true\n ];\n } else {\n return [\"conflict\", fullpath];\n }\n } else {\n return [\n \"create-index\",\n fullpath,\n await commit2.oid(),\n await commit2.mode()\n ];\n }\n }\n }\n case \"commit-tree\": {\n return;\n }\n case \"commit-blob\": {\n return [\"conflict\", fullpath];\n }\n default: {\n return [\"error\", `new entry Unhandled type ${commit2.type}`];\n }\n }\n }\n // Something in stage but not in the commit OR the workdir.\n // Note: I verified this behavior against canonical git.\n case \"100\": {\n return [\"delete-index\", fullpath];\n }\n // Deleted entries\n // TODO: How to handle if stage type and workdir type mismatch?\n case \"101\": {\n switch (await stage.type()) {\n case \"tree\": {\n return [\"rmdir-index\", fullpath];\n }\n case \"blob\": {\n if (await stage.oid() !== await workdir.oid()) {\n if (force) {\n return [\"delete\", fullpath];\n } else {\n return [\"conflict\", fullpath];\n }\n } else {\n return [\"delete\", fullpath];\n }\n }\n case \"commit\": {\n return [\"rmdir-index\", fullpath];\n }\n default: {\n return [\n \"error\",\n `delete entry Unhandled type ${await stage.type()}`\n ];\n }\n }\n }\n /* eslint-disable no-fallthrough */\n // File missing from workdir\n case \"110\":\n // Possibly modified entries\n case \"111\": {\n switch (`${await stage.type()}-${await commit2.type()}`) {\n case \"tree-tree\": {\n return;\n }\n case \"blob-blob\": {\n if (await stage.oid() === await commit2.oid() && await stage.mode() === await commit2.mode() && !force) {\n return;\n }\n if (workdir) {\n if (await workdir.oid() !== await stage.oid() && await workdir.oid() !== await commit2.oid()) {\n if (force) {\n return [\n \"update\",\n fullpath,\n await commit2.oid(),\n await commit2.mode(),\n await commit2.mode() !== await workdir.mode()\n ];\n } else {\n return [\"conflict\", fullpath];\n }\n }\n } else if (force) {\n return [\n \"update\",\n fullpath,\n await commit2.oid(),\n await commit2.mode(),\n await commit2.mode() !== await stage.mode()\n ];\n }\n if (await commit2.mode() !== await stage.mode()) {\n return [\n \"update\",\n fullpath,\n await commit2.oid(),\n await commit2.mode(),\n true\n ];\n }\n if (await commit2.oid() !== await stage.oid()) {\n return [\n \"update\",\n fullpath,\n await commit2.oid(),\n await commit2.mode(),\n false\n ];\n } else {\n return;\n }\n }\n case \"tree-blob\": {\n return [\"update-dir-to-blob\", fullpath, await commit2.oid()];\n }\n case \"blob-tree\": {\n return [\"update-blob-to-tree\", fullpath];\n }\n case \"commit-commit\": {\n return [\n \"mkdir-index\",\n fullpath,\n await commit2.oid(),\n await commit2.mode()\n ];\n }\n default: {\n return [\n \"error\",\n `update entry Unhandled type ${await stage.type()}-${await commit2.type()}`\n ];\n }\n }\n }\n }\n },\n // Modify the default flat mapping\n reduce: async function(parent, children) {\n children = flat(children);\n if (!parent) {\n return children;\n } else if (parent && parent[0] === \"rmdir\") {\n children.push(parent);\n return children;\n } else {\n children.unshift(parent);\n return children;\n }\n }\n });\n}\nasync function updateIndex({ index: index3, fullpath, stats, oid }) {\n index3.insert({\n filepath: fullpath,\n stats,\n oid\n });\n}\nasync function updateWorkingDir({ fs, cache, gitdir, dir }, [method, fullpath, oid, mode, chmod]) {\n const filepath = `${dir}/${fullpath}`;\n if (method !== \"create-index\" && method !== \"mkdir-index\") {\n const { object } = await _readObject({ fs, cache, gitdir, oid });\n if (chmod) {\n await fs.rm(filepath);\n }\n if (mode === 33188) {\n await fs.write(filepath, object);\n } else if (mode === 33261) {\n await fs.write(filepath, object, { mode: 511 });\n } else if (mode === 40960) {\n await fs.writelink(filepath, object);\n } else {\n throw new InternalError(\n `Invalid mode 0o${mode.toString(8)} detected in blob ${oid}`\n );\n }\n }\n const stats = await fs.lstat(filepath);\n if (mode === 33261) {\n stats.mode = 493;\n }\n if (method === \"mkdir-index\") {\n stats.mode = 57344;\n }\n return [fullpath, oid, stats];\n}\nasync function batchAllSettled(operationName, tasks, onProgress, batchSize) {\n const results = [];\n const errors = [];\n for (let i = 0; i < tasks.length; i += batchSize) {\n const batch = tasks.slice(i, i + batchSize).map((task) => task());\n const batchResults = await Promise.allSettled(batch);\n batchResults.forEach((result) => {\n if (result.status === \"fulfilled\") results.push(result.value);\n else errors.push(result.reason);\n });\n if (onProgress) {\n await onProgress({\n phase: \"Updating workdir\",\n loaded: i + batch.length,\n total: tasks.length\n });\n }\n }\n if (errors.length > 0) {\n const detail = errors.slice(0, 5).map((e) => e && e.message || String(e)).join(\"; \");\n const more = errors.length > 5 ? ` (+${errors.length - 5} more)` : \"\";\n throw new InternalError(\n `${operationName} failed for ${errors.length} of ${tasks.length} task(s): ${detail}${more}`\n );\n }\n return results;\n}\nasync function checkout({\n fs,\n onProgress,\n onPostCheckout,\n dir,\n gitdir = join2(dir, \".git\"),\n remote = \"origin\",\n ref: _ref,\n filepaths,\n noCheckout = false,\n noUpdateHead = _ref === void 0,\n dryRun = false,\n force = false,\n track = true,\n cache = {},\n nonBlocking = false,\n batchSize = 100\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"dir\", dir);\n assertParameter(\"gitdir\", gitdir);\n const ref = _ref || \"HEAD\";\n return await _checkout({\n fs: new FileSystem(fs),\n cache,\n onProgress,\n onPostCheckout,\n dir,\n gitdir,\n remote,\n ref,\n filepaths,\n noCheckout,\n noUpdateHead,\n dryRun,\n force,\n track,\n nonBlocking,\n batchSize\n });\n } catch (err) {\n err.caller = \"git.checkout\";\n throw err;\n }\n}\nvar freshCheckoutOidPattern = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;\nvar freshCheckoutMaxDirectories = 2e4;\nvar freshCheckoutMaxDirectoryBytes = 4 * 1024 * 1024;\nvar freshCheckoutMaxIndexChunks = 2e4;\nfunction freshCheckoutError(message) {\n return new InternalError(`Fresh checkout: ${message}`);\n}\nvar FreshCheckoutResourceLimitError = class extends BaseError {\n constructor(filepath, decodedBytes, maxDecodedBytes) {\n super(\n `Fresh checkout: ${filepath} decodes to ${decodedBytes} bytes, exceeding maxDecodedBytes ${maxDecodedBytes}`\n );\n this.code = this.name = \"FreshCheckoutResourceLimitError\";\n this.data = { filepath, decodedBytes, maxDecodedBytes };\n }\n};\nvar FreshCheckoutDirectoryLimitError = class extends BaseError {\n constructor(directories, directoryBytes) {\n super(\n `Fresh checkout: directory cursor exceeds its bound (${directories} directories, ${directoryBytes} bytes; max ${freshCheckoutMaxDirectories} directories, ${freshCheckoutMaxDirectoryBytes} bytes)`\n );\n this.code = this.name = \"FreshCheckoutDirectoryLimitError\";\n this.data = {\n directories,\n directoryBytes,\n maxDirectories: freshCheckoutMaxDirectories,\n maxDirectoryBytes: freshCheckoutMaxDirectoryBytes\n };\n }\n};\nfunction validateFreshCheckoutBound(value, name) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw freshCheckoutError(`${name} must be a positive safe integer`);\n }\n return value;\n}\nfunction validateFreshCheckoutFrame(value, index3) {\n if (!value || typeof value !== \"object\" || !freshCheckoutOidPattern.test(value.treeOid) || typeof value.path !== \"string\" || value.path.length > 4096 || (index3 === 0 ? value.path !== \"\" : value.path.length === 0) || !Number.isSafeInteger(value.nextChildIndex) || value.nextChildIndex < 0) {\n throw freshCheckoutError(`cursor frame ${index3} is invalid`);\n }\n return {\n treeOid: value.treeOid,\n path: value.path,\n nextChildIndex: value.nextChildIndex\n };\n}\nfunction validateFreshCheckoutDirectories(value) {\n if (value === void 0) return { directories: /* @__PURE__ */ new Set(), directoryBytes: 0 };\n if (!Array.isArray(value)) {\n throw freshCheckoutError(\"cursor directories are invalid\");\n }\n if (value.length > freshCheckoutMaxDirectories) {\n throw new FreshCheckoutDirectoryLimitError(value.length, 0);\n }\n const directories = /* @__PURE__ */ new Set();\n let directoryBytes = 0;\n for (const path of value) {\n if (typeof path !== \"string\" || path.length === 0 || path.length > 4096 || path.startsWith(\"/\") || path.split(\"/\").some((part) => !part || part === \".\" || part === \"..\") || directories.has(path)) {\n throw freshCheckoutError(\"cursor directory is invalid\");\n }\n directoryBytes += Buffer.byteLength(path);\n if (directoryBytes > freshCheckoutMaxDirectoryBytes) {\n throw new FreshCheckoutDirectoryLimitError(value.length, directoryBytes);\n }\n directories.add(path);\n }\n return { directories, directoryBytes };\n}\nfunction addFreshCheckoutDirectory(directories, directoryBytes, path) {\n if (directories.has(path)) return directoryBytes;\n const nextBytes = directoryBytes + Buffer.byteLength(path);\n if (directories.size + 1 > freshCheckoutMaxDirectories || nextBytes > freshCheckoutMaxDirectoryBytes) {\n throw new FreshCheckoutDirectoryLimitError(directories.size + 1, nextBytes);\n }\n directories.add(path);\n return nextBytes;\n}\nasync function readFreshCheckoutTree({ fs, cache, gitdir, oid }) {\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type !== \"tree\") throw new ObjectTypeError(oid, type, \"tree\");\n return GitTree.from(object).entries();\n}\nfunction strictFreshCheckoutFs(input) {\n const base = new FileSystem(input);\n const fs = Object.create(base);\n const assertParentDirectory = async function(filepath) {\n const parent = dirname(filepath);\n const stats = await this._lstat(parent);\n if (!stats || !stats.isDirectory()) {\n throw freshCheckoutError(`parent directory is missing for ${filepath}`);\n }\n };\n fs.read = async function(filepath, options = {}) {\n try {\n const value = await this._readFile(filepath, options);\n return typeof value === \"string\" ? value : Buffer.from(value);\n } catch (error) {\n if (error && (error.code === \"ENOENT\" || error.code === \"ENOTDIR\")) return null;\n throw error;\n }\n };\n fs.readdir = async function(filepath) {\n try {\n const names = await this._readdir(filepath);\n names.sort(compareStrings);\n return names;\n } catch (error) {\n if (error && error.code === \"ENOENT\") return [];\n if (error && error.code === \"ENOTDIR\") return null;\n throw error;\n }\n };\n fs.write = async function(filepath, contents, options = {}) {\n await assertParentDirectory.call(this, filepath);\n await this._writeFile(filepath, contents, options);\n };\n fs.mkdir = async function(filepath) {\n try {\n await assertParentDirectory.call(this, filepath);\n await this._mkdir(filepath);\n } catch (error) {\n if (!error || error.code !== \"EEXIST\") throw error;\n }\n };\n fs.writelink = async function(filepath, buffer) {\n await assertParentDirectory.call(this, filepath);\n try {\n await this._unlink(filepath);\n } catch (error) {\n if (!error || error.code !== \"ENOENT\") throw error;\n }\n await this._symlink(buffer.toString(\"utf8\"), filepath);\n };\n return fs;\n}\nasync function validateFreshCheckoutCursor({ fs, cache, gitdir, treeOid, cursor }) {\n if (cursor === null || cursor === void 0) {\n return {\n stack: [{ treeOid, path: \"\", nextChildIndex: 0 }],\n directories: /* @__PURE__ */ new Set(),\n directoryBytes: 0,\n indexChunks: 0,\n indexEntries: 0\n };\n }\n if (!cursor || typeof cursor !== \"object\" || cursor.version !== 2 || cursor.tree !== treeOid || !Array.isArray(cursor.stack) || cursor.stack.length === 0 || cursor.stack.length > 4096 || !Number.isSafeInteger(cursor.indexChunks) || cursor.indexChunks <= 0 || cursor.indexChunks > freshCheckoutMaxIndexChunks || !Number.isSafeInteger(cursor.indexEntries) || cursor.indexEntries < 0) {\n throw freshCheckoutError(\"cursor does not match the resolved tree\");\n }\n const stack = cursor.stack.map(validateFreshCheckoutFrame);\n const { directories, directoryBytes } = validateFreshCheckoutDirectories(cursor.directories);\n if (stack[0].treeOid !== treeOid || stack[0].path !== \"\") {\n throw freshCheckoutError(\"cursor root frame does not match the resolved tree\");\n }\n const trees = /* @__PURE__ */ new Map();\n for (let index3 = 0; index3 < stack.length; index3++) {\n const frame = stack[index3];\n let entries = trees.get(frame.treeOid);\n if (!entries) {\n entries = await readFreshCheckoutTree({\n fs,\n cache,\n gitdir,\n oid: frame.treeOid\n });\n trees.set(frame.treeOid, entries);\n }\n if (frame.nextChildIndex > entries.length) {\n throw freshCheckoutError(`cursor frame ${index3} is past the end of its tree`);\n }\n if (index3 === 0) continue;\n const parent = stack[index3 - 1];\n if (parent.nextChildIndex === 0) {\n throw freshCheckoutError(`cursor frame ${index3} has no parent entry`);\n }\n const parentEntries = trees.get(parent.treeOid);\n const entry = parentEntries[parent.nextChildIndex - 1];\n const path = parent.path ? `${parent.path}/${entry && entry.path}` : entry && entry.path;\n if (!entry || entry.mode !== \"040000\" || entry.oid !== frame.treeOid || path !== frame.path) {\n throw freshCheckoutError(`cursor frame ${index3} does not match its parent tree`);\n }\n }\n return {\n stack,\n directories,\n directoryBytes,\n indexChunks: cursor.indexChunks,\n indexEntries: cursor.indexEntries\n };\n}\nasync function checkoutFreshChunk({\n fs: inputFs,\n cache = {},\n onProgress,\n dir,\n gitdir = join2(dir, \".git\"),\n ref = \"HEAD\",\n cursor = null,\n maxEntries,\n maxDecodedBytes,\n maxWallMs,\n deferIndexFragmentCleanup = false\n}) {\n try {\n assertParameter(\"fs\", inputFs);\n assertParameter(\"dir\", dir);\n assertParameter(\"gitdir\", gitdir);\n validateFreshCheckoutBound(maxEntries, \"maxEntries\");\n validateFreshCheckoutBound(maxDecodedBytes, \"maxDecodedBytes\");\n validateFreshCheckoutBound(maxWallMs, \"maxWallMs\");\n const fs = strictFreshCheckoutFs(inputFs);\n const commitOid = await GitRefManager.resolve({ fs, gitdir, ref });\n const { oid: treeOid } = await resolveTree({ fs, cache, gitdir, oid: commitOid });\n const checkoutCursor = await validateFreshCheckoutCursor({\n fs,\n cache,\n gitdir,\n treeOid,\n cursor\n });\n const { stack, directories, indexChunks, indexEntries: priorIndexEntries } = checkoutCursor;\n let directoryBytes = checkoutCursor.directoryBytes;\n const startedAt = Date.now();\n const trees = /* @__PURE__ */ new Map();\n let files = 0;\n let decodedBytes = 0;\n let treeEntriesVisited = 0;\n let indexEntries = priorIndexEntries;\n const committedIndex = await GitIndexManager.acquireFreshCheckout(\n {\n fs,\n gitdir,\n priorChunks: indexChunks,\n priorEntries: priorIndexEntries,\n deferFragmentCleanup: deferIndexFragmentCleanup\n },\n async function(index3) {\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n let entries = trees.get(frame.treeOid);\n if (!entries) {\n entries = await readFreshCheckoutTree({\n fs,\n cache,\n gitdir,\n oid: frame.treeOid\n });\n trees.clear();\n trees.set(frame.treeOid, entries);\n }\n if (frame.nextChildIndex === entries.length) {\n stack.pop();\n continue;\n }\n if (treeEntriesVisited >= maxEntries || treeEntriesVisited > 0 && Date.now() - startedAt >= maxWallMs) {\n break;\n }\n const entry = entries[frame.nextChildIndex];\n const fullpath = frame.path ? `${frame.path}/${entry.path}` : entry.path;\n const filepath = join2(dir, fullpath);\n const mode = parseInt(entry.mode, 8);\n let object = null;\n if (mode === 33188 || mode === 33261 || mode === 40960) {\n const result = await _readObject({ fs, cache, gitdir, oid: entry.oid });\n if (result.type !== \"blob\") {\n throw new ObjectTypeError(entry.oid, result.type, \"blob\");\n }\n object = result.object;\n if (object.byteLength > maxDecodedBytes) {\n throw new FreshCheckoutResourceLimitError(\n fullpath,\n object.byteLength,\n maxDecodedBytes\n );\n }\n if (treeEntriesVisited > 0 && Date.now() - startedAt >= maxWallMs) break;\n if (decodedBytes + object.byteLength > maxDecodedBytes) break;\n }\n if (mode === 16384) {\n directoryBytes = addFreshCheckoutDirectory(directories, directoryBytes, fullpath);\n await fs.mkdir(filepath);\n } else if (mode === 33188 || mode === 33261) {\n await fs.write(filepath, object, mode === 33261 ? { mode: 511 } : {});\n } else if (mode === 40960) {\n await fs.writelink(filepath, object);\n } else if (mode === 57344) {\n directoryBytes = addFreshCheckoutDirectory(directories, directoryBytes, fullpath);\n await fs.mkdir(filepath);\n } else {\n throw freshCheckoutError(\n `invalid mode 0o${mode.toString(8)} detected at ${fullpath}`\n );\n }\n if (mode !== 16384) {\n const stats = await fs.lstat(filepath);\n if (!stats) throw freshCheckoutError(`lstat returned no result for ${fullpath}`);\n if (mode === 33188) stats.mode = 420;\n if (mode === 33261) stats.mode = 493;\n if (mode === 57344) stats.mode = 57344;\n index3.insert({ filepath: fullpath, stats, oid: entry.oid });\n if (mode !== 57344) files++;\n }\n if (object) decodedBytes += object.byteLength;\n frame.nextChildIndex++;\n treeEntriesVisited++;\n if (mode === 16384) {\n stack.push({ treeOid: entry.oid, path: fullpath, nextChildIndex: 0 });\n }\n if (onProgress) {\n await onProgress({\n phase: \"Updating workdir\",\n loaded: treeEntriesVisited\n });\n }\n }\n return { complete: stack.length === 0 };\n }\n );\n indexEntries = committedIndex.indexEntries;\n return {\n nextCursor: stack.length === 0 ? null : {\n version: 2,\n tree: treeOid,\n stack,\n directories: [...directories],\n indexChunks: indexChunks + 1,\n indexEntries\n },\n files,\n decodedBytes,\n treeEntriesVisited,\n indexEntries\n };\n } catch (err) {\n err.caller = \"git.checkoutFreshChunk\";\n throw err;\n }\n}\nvar abbreviateRx = new RegExp(\"^refs/(heads/|tags/|remotes/)?(.*)\");\nfunction abbreviateRef(ref) {\n const match = abbreviateRx.exec(ref);\n if (match) {\n if (match[1] === \"remotes/\" && ref.endsWith(\"/HEAD\")) {\n return match[2].slice(0, -5);\n } else {\n return match[2];\n }\n }\n return ref;\n}\nasync function _currentBranch({\n fs,\n gitdir,\n fullname = false,\n test = false\n}) {\n const ref = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: \"HEAD\",\n depth: 2\n });\n if (test) {\n try {\n await GitRefManager.resolve({ fs, gitdir, ref });\n } catch (_) {\n return;\n }\n }\n if (!ref.startsWith(\"refs/\")) return;\n return fullname ? ref : abbreviateRef(ref);\n}\nfunction translateSSHtoHTTP(url) {\n url = url.replace(/^git@([^:]+):/, \"https://$1/\");\n url = url.replace(/^ssh:\\/\\//, \"https://\");\n return url;\n}\nfunction calculateBasicAuthHeader({ username = \"\", password = \"\" }) {\n return `Basic ${Buffer.from(`${username}:${password}`).toString(\"base64\")}`;\n}\nasync function forAwait(iterable, cb) {\n const iter = getIterator(iterable);\n while (true) {\n const { value, done } = await iter.next();\n if (value) await cb(value);\n if (done) break;\n }\n if (iter.return) iter.return();\n}\nasync function collect(iterable) {\n let size = 0;\n const buffers = [];\n await forAwait(iterable, (value) => {\n buffers.push(value);\n size += value.byteLength;\n });\n const result = new Uint8Array(size);\n let nextIndex = 0;\n for (const buffer of buffers) {\n result.set(buffer, nextIndex);\n nextIndex += buffer.byteLength;\n }\n return result;\n}\nfunction extractAuthFromUrl(url) {\n let userpass = url.match(/^https?:\\/\\/([^/]+)@/);\n if (userpass == null) return { url, auth: {} };\n userpass = userpass[1];\n const [username, password] = userpass.split(\":\");\n url = url.replace(`${userpass}@`, \"\");\n return { url, auth: { username, password } };\n}\nfunction padHex(b, n) {\n const s = n.toString(16);\n return \"0\".repeat(b - s.length) + s;\n}\nvar GitPktLine = class {\n static flush() {\n return Buffer.from(\"0000\", \"utf8\");\n }\n static delim() {\n return Buffer.from(\"0001\", \"utf8\");\n }\n static encode(line) {\n if (typeof line === \"string\") {\n line = Buffer.from(line);\n }\n const length = line.length + 4;\n const hexlength = padHex(4, length);\n return Buffer.concat([Buffer.from(hexlength, \"utf8\"), line]);\n }\n static streamReader(stream) {\n const reader = new StreamReader(stream);\n return async function read() {\n try {\n let length = await reader.read(4);\n if (length == null) return true;\n length = parseInt(length.toString(\"utf8\"), 16);\n if (length === 0) return null;\n if (length === 1) return null;\n const buffer = await reader.read(length - 4);\n if (buffer == null) return true;\n return buffer;\n } catch (err) {\n stream.error = err;\n return true;\n }\n };\n }\n};\nasync function parseCapabilitiesV2(read) {\n const capabilities2 = {};\n let line;\n while (true) {\n line = await read();\n if (line === true) break;\n if (line === null) continue;\n line = line.toString(\"utf8\").replace(/\\n$/, \"\");\n const i = line.indexOf(\"=\");\n if (i > -1) {\n const key = line.slice(0, i);\n const value = line.slice(i + 1);\n capabilities2[key] = value;\n } else {\n capabilities2[line] = true;\n }\n }\n return { protocolVersion: 2, capabilities2 };\n}\nasync function parseRefsAdResponse(stream, { service }) {\n const capabilities = /* @__PURE__ */ new Set();\n const refs = /* @__PURE__ */ new Map();\n const symrefs = /* @__PURE__ */ new Map();\n const read = GitPktLine.streamReader(stream);\n let lineOne = await read();\n while (lineOne === null) lineOne = await read();\n if (lineOne === true) throw new EmptyServerResponseError();\n if (lineOne.includes(\"version 2\")) {\n return parseCapabilitiesV2(read);\n }\n if (lineOne.toString(\"utf8\").replace(/\\n$/, \"\") !== `# service=${service}`) {\n throw new ParseError(`# service=${service}\\\\n`, lineOne.toString(\"utf8\"));\n }\n let lineTwo = await read();\n while (lineTwo === null) lineTwo = await read();\n if (lineTwo === true) return { capabilities, refs, symrefs };\n lineTwo = lineTwo.toString(\"utf8\");\n if (lineTwo.includes(\"version 2\")) {\n return parseCapabilitiesV2(read);\n }\n const [firstRef, capabilitiesLine] = splitAndAssert(lineTwo, \"\\0\", \"\\\\x00\");\n capabilitiesLine.split(\" \").map((x) => capabilities.add(x));\n if (firstRef !== \"0000000000000000000000000000000000000000 capabilities^{}\") {\n const [ref, name] = splitAndAssert(firstRef, \" \", \" \");\n refs.set(name, ref);\n while (true) {\n const line = await read();\n if (line === true) break;\n if (line !== null) {\n const [ref2, name2] = splitAndAssert(line.toString(\"utf8\"), \" \", \" \");\n refs.set(name2, ref2);\n }\n }\n }\n for (const cap of capabilities) {\n if (cap.startsWith(\"symref=\")) {\n const m = cap.match(/symref=([^:]+):(.*)/);\n if (m.length === 3) {\n symrefs.set(m[1], m[2]);\n }\n }\n }\n return { protocolVersion: 1, capabilities, refs, symrefs };\n}\nfunction splitAndAssert(line, sep, expected) {\n const split = line.trim().split(sep);\n if (split.length !== 2) {\n throw new ParseError(\n `Two strings separated by '${expected}'`,\n line.toString(\"utf8\")\n );\n }\n return split;\n}\nvar corsProxify = (corsProxy, url) => corsProxy.endsWith(\"?\") ? `${corsProxy}${url}` : `${corsProxy}/${url.replace(/^https?:\\/\\//, \"\")}`;\nvar updateHeaders = (headers, auth) => {\n if (auth.username || auth.password) {\n headers.Authorization = calculateBasicAuthHeader(auth);\n }\n if (auth.headers) {\n Object.assign(headers, auth.headers);\n }\n};\nvar stringifyBody = async (res) => {\n try {\n const data = Buffer.from(await collect(res.body));\n const response = data.toString(\"utf8\");\n const preview = response.length < 256 ? response : response.slice(0, 256) + \"...\";\n return { preview, response, data };\n } catch (e) {\n return {};\n }\n};\nvar GitRemoteHTTP = class {\n /**\n * Returns the capabilities of the GitRemoteHTTP class.\n *\n * @returns {Promise<string[]>} - An array of supported capabilities.\n */\n static async capabilities() {\n return [\"discover\", \"connect\"];\n }\n /**\n * Discovers references from a remote Git repository.\n *\n * @param {Object} args\n * @param {HttpClient} args.http - The HTTP client to use for requests.\n * @param {ProgressCallback} [args.onProgress] - Callback for progress updates.\n * @param {AuthCallback} [args.onAuth] - Callback for providing authentication credentials.\n * @param {AuthFailureCallback} [args.onAuthFailure] - Callback for handling authentication failures.\n * @param {AuthSuccessCallback} [args.onAuthSuccess] - Callback for handling successful authentication.\n * @param {string} [args.corsProxy] - Optional CORS proxy URL.\n * @param {string} args.service - The Git service (e.g., \"git-upload-pack\").\n * @param {string} args.url - The URL of the remote repository.\n * @param {Object<string, string>} args.headers - HTTP headers to include in the request.\n * @param {1 | 2} args.protocolVersion - The Git protocol version to use.\n * @returns {Promise<Object>} - The parsed response from the remote repository.\n * @throws {HttpError} - If the HTTP request fails.\n * @throws {SmartHttpError} - If the response cannot be parsed.\n * @throws {UserCanceledError} - If the user cancels the operation.\n */\n static async discover({\n http,\n onProgress,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n service,\n url: _origUrl,\n headers,\n protocolVersion\n }) {\n let { url, auth } = extractAuthFromUrl(_origUrl);\n const proxifiedURL = corsProxy ? corsProxify(corsProxy, url) : url;\n if (auth.username || auth.password) {\n headers.Authorization = calculateBasicAuthHeader(auth);\n }\n if (protocolVersion === 2) {\n headers[\"Git-Protocol\"] = \"version=2\";\n }\n let res;\n let tryAgain;\n let providedAuthBefore = false;\n do {\n res = await http.request({\n onProgress,\n method: \"GET\",\n url: `${proxifiedURL}/info/refs?service=${service}`,\n headers\n });\n tryAgain = false;\n if (res.statusCode === 401 || res.statusCode === 203) {\n const getAuth = providedAuthBefore ? onAuthFailure : onAuth;\n if (getAuth) {\n auth = await getAuth(url, {\n ...auth,\n headers: { ...headers }\n });\n if (auth && auth.cancel) {\n throw new UserCanceledError();\n } else if (auth) {\n updateHeaders(headers, auth);\n providedAuthBefore = true;\n tryAgain = true;\n }\n }\n } else if (res.statusCode === 200 && providedAuthBefore && onAuthSuccess) {\n await onAuthSuccess(url, auth);\n }\n } while (tryAgain);\n if (res.statusCode !== 200) {\n const { response } = await stringifyBody(res);\n throw new HttpError(res.statusCode, res.statusMessage, response);\n }\n if (res.headers[\"content-type\"] === `application/x-${service}-advertisement`) {\n const remoteHTTP = await parseRefsAdResponse(res.body, { service });\n remoteHTTP.auth = auth;\n return remoteHTTP;\n } else {\n const { preview, response, data } = await stringifyBody(res);\n try {\n const remoteHTTP = await parseRefsAdResponse([data], { service });\n remoteHTTP.auth = auth;\n return remoteHTTP;\n } catch (e) {\n throw new SmartHttpError(preview, response);\n }\n }\n }\n /**\n * Connects to a remote Git repository and sends a request.\n *\n * @param {Object} args\n * @param {HttpClient} args.http - The HTTP client to use for requests.\n * @param {ProgressCallback} [args.onProgress] - Callback for progress updates.\n * @param {string} [args.corsProxy] - Optional CORS proxy URL.\n * @param {string} args.service - The Git service (e.g., \"git-upload-pack\").\n * @param {string} args.url - The URL of the remote repository.\n * @param {Object<string, string>} [args.headers] - HTTP headers to include in the request.\n * @param {any} args.body - The request body to send.\n * @param {any} args.auth - Authentication credentials.\n * @returns {Promise<GitHttpResponse>} - The HTTP response from the remote repository.\n * @throws {HttpError} - If the HTTP request fails.\n */\n static async connect({\n http,\n onProgress,\n corsProxy,\n service,\n url,\n auth,\n body,\n headers\n }) {\n const urlAuth = extractAuthFromUrl(url);\n if (urlAuth) url = urlAuth.url;\n if (corsProxy) url = corsProxify(corsProxy, url);\n headers[\"content-type\"] = `application/x-${service}-request`;\n headers.accept = `application/x-${service}-result`;\n updateHeaders(headers, auth);\n const res = await http.request({\n onProgress,\n method: \"POST\",\n url: `${url}/${service}`,\n body,\n headers\n });\n if (res.statusCode !== 200) {\n const { response } = stringifyBody(res);\n throw new HttpError(res.statusCode, res.statusMessage, response);\n }\n return res;\n }\n};\nvar GitRemoteManager = class {\n /**\n * Determines the appropriate remote helper for the given URL.\n *\n * @param {Object} args\n * @param {string} args.url - The URL of the remote repository.\n * @returns {Object} - The remote helper class for the specified transport.\n * @throws {UrlParseError} - If the URL cannot be parsed.\n * @throws {UnknownTransportError} - If the transport is not supported.\n */\n static getRemoteHelperFor({ url }) {\n const remoteHelpers = /* @__PURE__ */ new Map();\n remoteHelpers.set(\"http\", GitRemoteHTTP);\n remoteHelpers.set(\"https\", GitRemoteHTTP);\n const parts = parseRemoteUrl({ url });\n if (!parts) {\n throw new UrlParseError(url);\n }\n if (remoteHelpers.has(parts.transport)) {\n return remoteHelpers.get(parts.transport);\n }\n throw new UnknownTransportError(\n url,\n parts.transport,\n parts.transport === \"ssh\" ? translateSSHtoHTTP(url) : void 0\n );\n }\n};\nfunction parseRemoteUrl({ url }) {\n if (url.startsWith(\"git@\")) {\n return {\n transport: \"ssh\",\n address: url\n };\n }\n const matches = url.match(/(\\w+)(:\\/\\/|::)(.*)/);\n if (matches === null) return;\n if (matches[2] === \"://\") {\n return {\n transport: matches[1],\n address: matches[0]\n };\n }\n if (matches[2] === \"::\") {\n return {\n transport: matches[1],\n address: matches[3]\n };\n }\n}\nvar lock$2 = null;\nvar GitShallowManager = class {\n /**\n * Reads the `shallow` file in the Git repository and returns a set of object IDs (OIDs).\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path\n * @returns {Promise<Set<string>>} - A set of shallow object IDs.\n */\n static async read({ fs, gitdir }) {\n if (lock$2 === null) lock$2 = new AsyncLock();\n const filepath = join2(gitdir, \"shallow\");\n const oids = /* @__PURE__ */ new Set();\n await lock$2.acquire(filepath, async function() {\n const text = await fs.read(filepath, { encoding: \"utf8\" });\n if (text === null) return oids;\n if (text.trim() === \"\") return oids;\n text.trim().split(\"\\n\").map((oid) => oids.add(oid));\n });\n return oids;\n }\n /**\n * Writes a set of object IDs (OIDs) to the `shallow` file in the Git repository.\n * If the set is empty, the `shallow` file is removed.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path\n * @param {Set<string>} args.oids - A set of shallow object IDs to write.\n * @returns {Promise<void>}\n */\n static async write({ fs, gitdir, oids }) {\n if (lock$2 === null) lock$2 = new AsyncLock();\n const filepath = join2(gitdir, \"shallow\");\n if (oids.size > 0) {\n const text = [...oids].join(\"\\n\") + \"\\n\";\n await lock$2.acquire(filepath, async function() {\n await fs.write(filepath, text, {\n encoding: \"utf8\"\n });\n });\n } else {\n await lock$2.acquire(filepath, async function() {\n await fs.rm(filepath);\n });\n }\n }\n};\nasync function hasObjectLoose({ fs, gitdir, oid }) {\n const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`;\n return fs.exists(`${gitdir}/${source}`);\n}\nasync function hasObjectPacked({\n fs,\n cache,\n gitdir,\n oid,\n getExternalRefDelta\n}) {\n let list = await fs.readdir(join2(gitdir, \"objects/pack\"));\n list = list.filter((x) => x.endsWith(\".idx\"));\n for (const filename of list) {\n const indexFile = packIndexCacheKey(gitdir, filename);\n const p = await readPackIndex({\n fs,\n cache,\n filename: indexFile,\n getExternalRefDelta\n });\n if (p.error) throw new InternalError(p.error);\n if (p.offsets.has(oid)) {\n return true;\n }\n }\n return false;\n}\nasync function hasObject({\n fs,\n cache,\n gitdir,\n oid,\n format = \"content\"\n}) {\n const getExternalRefDelta = (oid2) => _readObject({ fs, cache, gitdir, oid: oid2 });\n let result = await hasObjectLoose({ fs, gitdir, oid });\n if (!result) {\n result = await hasObjectPacked({\n fs,\n cache,\n gitdir,\n oid,\n getExternalRefDelta\n });\n }\n return result;\n}\nfunction emptyPackfile(pack) {\n const pheader = \"5041434b\";\n const version2 = \"00000002\";\n const obCount = \"00000000\";\n const header = pheader + version2 + obCount;\n return pack.slice(0, 12).toString(\"hex\") === header;\n}\nfunction filterCapabilities(server, client) {\n const serverNames = server.map((cap) => cap.split(\"=\", 1)[0]);\n return client.filter((cap) => {\n const name = cap.split(\"=\", 1)[0];\n return serverNames.includes(name);\n });\n}\nvar pkg = {\n name: \"@ashishkumar472/cf-git\",\n version: \"1.0.4\",\n agent: \"git/cf-git@1.0.4\"\n};\nvar FIFO = class {\n constructor() {\n this._queue = [];\n }\n write(chunk) {\n if (this._ended) {\n throw Error(\"You cannot write to a FIFO that has already been ended!\");\n }\n if (this._waiting) {\n const resolve = this._waiting;\n this._waiting = null;\n resolve({ value: chunk });\n } else {\n this._queue.push(chunk);\n }\n }\n end() {\n this._ended = true;\n if (this._waiting) {\n const resolve = this._waiting;\n this._waiting = null;\n resolve({ done: true });\n }\n }\n destroy(err) {\n this.error = err;\n this.end();\n }\n async next() {\n if (this._queue.length > 0) {\n return { value: this._queue.shift() };\n }\n if (this._ended) {\n return { done: true };\n }\n if (this._waiting) {\n throw Error(\n \"You cannot call read until the previous call to read has returned!\"\n );\n }\n return new Promise((resolve) => {\n this._waiting = resolve;\n });\n }\n};\nfunction findSplit(str) {\n const r = str.indexOf(\"\\r\");\n const n = str.indexOf(\"\\n\");\n if (r === -1 && n === -1) return -1;\n if (r === -1) return n + 1;\n if (n === -1) return r + 1;\n if (n === r + 1) return n + 1;\n return Math.min(r, n) + 1;\n}\nfunction splitLines(input) {\n const output = new FIFO();\n let tmp = \"\";\n (async () => {\n await forAwait(input, (chunk) => {\n chunk = chunk.toString(\"utf8\");\n tmp += chunk;\n while (true) {\n const i = findSplit(tmp);\n if (i === -1) break;\n output.write(tmp.slice(0, i));\n tmp = tmp.slice(i);\n }\n });\n if (tmp.length > 0) {\n output.write(tmp);\n }\n output.end();\n })();\n return output;\n}\nvar GitSideBand = class {\n static demux(input) {\n const read = GitPktLine.streamReader(input);\n const packetlines = new FIFO();\n const packfile = new FIFO();\n const progress = new FIFO();\n const nextBit = async function() {\n const line = await read();\n if (line === null) return nextBit();\n if (line === true) {\n packetlines.end();\n progress.end();\n input.error ? packfile.destroy(input.error) : packfile.end();\n return;\n }\n switch (line[0]) {\n case 1: {\n packfile.write(line.slice(1));\n break;\n }\n case 2: {\n progress.write(line.slice(1));\n break;\n }\n case 3: {\n const error = line.slice(1);\n progress.write(error);\n packetlines.end();\n progress.end();\n packfile.destroy(new Error(error.toString(\"utf8\")));\n return;\n }\n default: {\n packetlines.write(line);\n }\n }\n nextBit();\n };\n nextBit();\n return {\n packetlines,\n packfile,\n progress\n };\n }\n // static mux ({\n // protocol, // 'side-band' or 'side-band-64k'\n // packetlines,\n // packfile,\n // progress,\n // error\n // }) {\n // const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519\n // let output = new PassThrough()\n // packetlines.on('data', data => {\n // if (data === null) {\n // output.write(GitPktLine.flush())\n // } else {\n // output.write(GitPktLine.encode(data))\n // }\n // })\n // let packfileWasEmpty = true\n // let packfileEnded = false\n // let progressEnded = false\n // let errorEnded = false\n // let goodbye = Buffer.concat([\n // GitPktLine.encode(Buffer.from('010A', 'hex')),\n // GitPktLine.flush()\n // ])\n // packfile\n // .on('data', data => {\n // packfileWasEmpty = false\n // const buffers = splitBuffer(data, MAX_PACKET_LENGTH)\n // for (const buffer of buffers) {\n // output.write(\n // GitPktLine.encode(Buffer.concat([Buffer.from('01', 'hex'), buffer]))\n // )\n // }\n // })\n // .on('end', () => {\n // packfileEnded = true\n // if (!packfileWasEmpty) output.write(goodbye)\n // if (progressEnded && errorEnded) output.end()\n // })\n // progress\n // .on('data', data => {\n // const buffers = splitBuffer(data, MAX_PACKET_LENGTH)\n // for (const buffer of buffers) {\n // output.write(\n // GitPktLine.encode(Buffer.concat([Buffer.from('02', 'hex'), buffer]))\n // )\n // }\n // })\n // .on('end', () => {\n // progressEnded = true\n // if (packfileEnded && errorEnded) output.end()\n // })\n // error\n // .on('data', data => {\n // const buffers = splitBuffer(data, MAX_PACKET_LENGTH)\n // for (const buffer of buffers) {\n // output.write(\n // GitPktLine.encode(Buffer.concat([Buffer.from('03', 'hex'), buffer]))\n // )\n // }\n // })\n // .on('end', () => {\n // errorEnded = true\n // if (progressEnded && packfileEnded) output.end()\n // })\n // return output\n // }\n};\nasync function parseUploadPackResponse(stream) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream);\n const shallows = [];\n const unshallows = [];\n const acks = [];\n let nak = false;\n let done = false;\n return new Promise((resolve, reject) => {\n forAwait(packetlines, (data) => {\n const line = data.toString(\"utf8\").trim();\n if (line.startsWith(\"shallow\")) {\n const oid = line.slice(-41).trim();\n if (oid.length !== 40) {\n reject(new InvalidOidError(oid));\n }\n shallows.push(oid);\n } else if (line.startsWith(\"unshallow\")) {\n const oid = line.slice(-41).trim();\n if (oid.length !== 40) {\n reject(new InvalidOidError(oid));\n }\n unshallows.push(oid);\n } else if (line.startsWith(\"ACK\")) {\n const [, oid, status2] = line.split(\" \");\n acks.push({ oid, status: status2 });\n if (!status2) done = true;\n } else if (line.startsWith(\"NAK\")) {\n nak = true;\n done = true;\n } else {\n done = true;\n nak = true;\n }\n if (done) {\n stream.error ? reject(stream.error) : resolve({ shallows, unshallows, acks, nak, packfile, progress });\n }\n }).finally(() => {\n if (!done) {\n stream.error ? reject(stream.error) : resolve({ shallows, unshallows, acks, nak, packfile, progress });\n }\n });\n });\n}\nfunction writeUploadPackRequest({\n capabilities = [],\n wants = [],\n haves = [],\n shallows = [],\n depth = null,\n since = null,\n exclude = []\n}) {\n const packstream = [];\n wants = [...new Set(wants)];\n let firstLineCapabilities = ` ${capabilities.join(\" \")}`;\n for (const oid of wants) {\n packstream.push(GitPktLine.encode(`want ${oid}${firstLineCapabilities}\n`));\n firstLineCapabilities = \"\";\n }\n for (const oid of shallows) {\n packstream.push(GitPktLine.encode(`shallow ${oid}\n`));\n }\n if (depth !== null) {\n packstream.push(GitPktLine.encode(`deepen ${depth}\n`));\n }\n if (since !== null) {\n packstream.push(\n GitPktLine.encode(`deepen-since ${Math.floor(since.valueOf() / 1e3)}\n`)\n );\n }\n for (const oid of exclude) {\n packstream.push(GitPktLine.encode(`deepen-not ${oid}\n`));\n }\n packstream.push(GitPktLine.flush());\n for (const oid of haves) {\n packstream.push(GitPktLine.encode(`have ${oid}\n`));\n }\n packstream.push(GitPktLine.encode(`done\n`));\n return packstream;\n}\nasync function _fetch({\n fs,\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n gitdir,\n ref: _ref,\n remoteRef: _remoteRef,\n remote: _remote,\n url: _url,\n corsProxy,\n depth = null,\n since = null,\n exclude = [],\n relative = false,\n tags = false,\n singleBranch = false,\n headers = {},\n prune = false,\n pruneTags = false\n}) {\n const ref = _ref || await _currentBranch({ fs, gitdir, test: true });\n const config = await GitConfigManager.get({ fs, gitdir });\n const remote = _remote || ref && await config.get(`branch.${ref}.remote`) || \"origin\";\n const url = _url || await config.get(`remote.${remote}.url`);\n if (typeof url === \"undefined\") {\n throw new MissingParameterError(\"remote OR url\");\n }\n const remoteRef = _remoteRef || ref && await config.get(`branch.${ref}.merge`) || _ref || \"HEAD\";\n if (corsProxy === void 0) {\n corsProxy = await config.get(\"http.corsProxy\");\n }\n const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });\n const remoteHTTP = await GitRemoteHTTP2.discover({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n service: \"git-upload-pack\",\n url,\n headers,\n protocolVersion: 1\n });\n const auth = remoteHTTP.auth;\n const remoteRefs = remoteHTTP.refs;\n if (remoteRefs.size === 0) {\n return {\n defaultBranch: null,\n fetchHead: null,\n fetchHeadDescription: null\n };\n }\n if (depth !== null && !remoteHTTP.capabilities.has(\"shallow\")) {\n throw new RemoteCapabilityError(\"shallow\", \"depth\");\n }\n if (since !== null && !remoteHTTP.capabilities.has(\"deepen-since\")) {\n throw new RemoteCapabilityError(\"deepen-since\", \"since\");\n }\n if (exclude.length > 0 && !remoteHTTP.capabilities.has(\"deepen-not\")) {\n throw new RemoteCapabilityError(\"deepen-not\", \"exclude\");\n }\n if (relative === true && !remoteHTTP.capabilities.has(\"deepen-relative\")) {\n throw new RemoteCapabilityError(\"deepen-relative\", \"relative\");\n }\n const { oid, fullref } = GitRefManager.resolveAgainstMap({\n ref: remoteRef,\n map: remoteRefs\n });\n for (const remoteRef2 of remoteRefs.keys()) {\n if (remoteRef2 === fullref || remoteRef2 === \"HEAD\" || remoteRef2.startsWith(\"refs/heads/\") || tags && remoteRef2.startsWith(\"refs/tags/\")) {\n continue;\n }\n remoteRefs.delete(remoteRef2);\n }\n const capabilities = filterCapabilities(\n [...remoteHTTP.capabilities],\n [\n \"multi_ack_detailed\",\n \"no-done\",\n \"side-band-64k\",\n // Note: I removed 'thin-pack' option since our code doesn't \"fatten\" packfiles,\n // which is necessary for compatibility with git. It was the cause of mysterious\n // 'fatal: pack has [x] unresolved deltas' errors that plagued us for some time.\n // isomorphic-git is perfectly happy with thin packfiles in .git/objects/pack but\n // canonical git it turns out is NOT.\n \"ofs-delta\",\n `agent=${pkg.agent}`\n ]\n );\n if (relative) capabilities.push(\"deepen-relative\");\n const wants = singleBranch ? [oid] : remoteRefs.values();\n const haveRefs = singleBranch ? [ref] : await GitRefManager.listRefs({\n fs,\n gitdir,\n filepath: `refs`\n });\n let haves = [];\n for (let ref2 of haveRefs) {\n try {\n ref2 = await GitRefManager.expand({ fs, gitdir, ref: ref2 });\n const oid2 = await GitRefManager.resolve({ fs, gitdir, ref: ref2 });\n if (await hasObject({ fs, cache, gitdir, oid: oid2 })) {\n haves.push(oid2);\n }\n } catch (err) {\n }\n }\n haves = [...new Set(haves)];\n const oids = await GitShallowManager.read({ fs, gitdir });\n const shallows = remoteHTTP.capabilities.has(\"shallow\") ? [...oids] : [];\n const packstream = writeUploadPackRequest({\n capabilities,\n wants,\n haves,\n shallows,\n depth,\n since,\n exclude\n });\n const packbuffer = Buffer.from(await collect(packstream));\n const raw = await GitRemoteHTTP2.connect({\n http,\n onProgress,\n corsProxy,\n service: \"git-upload-pack\",\n url,\n auth,\n body: [packbuffer],\n headers\n });\n const response = await parseUploadPackResponse(raw.body);\n if (raw.headers) {\n response.headers = raw.headers;\n }\n for (const oid2 of response.shallows) {\n if (!oids.has(oid2)) {\n try {\n const { object } = await _readObject({ fs, cache, gitdir, oid: oid2 });\n const commit2 = new GitCommit(object);\n const hasParents = await Promise.all(\n commit2.headers().parent.map((oid3) => hasObject({ fs, cache, gitdir, oid: oid3 }))\n );\n const haveAllParents = hasParents.length === 0 || hasParents.every((has) => has);\n if (!haveAllParents) {\n oids.add(oid2);\n }\n } catch (err) {\n oids.add(oid2);\n }\n }\n }\n for (const oid2 of response.unshallows) {\n oids.delete(oid2);\n }\n await GitShallowManager.write({ fs, gitdir, oids });\n if (singleBranch) {\n const refs = /* @__PURE__ */ new Map([[fullref, oid]]);\n const symrefs = /* @__PURE__ */ new Map();\n let bail = 10;\n let key = fullref;\n while (bail--) {\n const value = remoteHTTP.symrefs.get(key);\n if (value === void 0) break;\n symrefs.set(key, value);\n key = value;\n }\n const realRef = remoteRefs.get(key);\n if (realRef) {\n refs.set(key, realRef);\n }\n const { pruned } = await GitRefManager.updateRemoteRefs({\n fs,\n gitdir,\n remote,\n refs,\n symrefs,\n tags,\n prune\n });\n if (prune) {\n response.pruned = pruned;\n }\n } else {\n const { pruned } = await GitRefManager.updateRemoteRefs({\n fs,\n gitdir,\n remote,\n refs: remoteRefs,\n symrefs: remoteHTTP.symrefs,\n tags,\n prune,\n pruneTags\n });\n if (prune) {\n response.pruned = pruned;\n }\n }\n response.HEAD = remoteHTTP.symrefs.get(\"HEAD\");\n if (response.HEAD === void 0) {\n const { oid: oid2 } = GitRefManager.resolveAgainstMap({\n ref: \"HEAD\",\n map: remoteRefs\n });\n for (const [key, value] of remoteRefs.entries()) {\n if (key !== \"HEAD\" && value === oid2) {\n response.HEAD = key;\n break;\n }\n }\n }\n const noun = fullref.startsWith(\"refs/tags\") ? \"tag\" : \"branch\";\n response.FETCH_HEAD = {\n oid,\n description: `${noun} '${abbreviateRef(fullref)}' of ${url}`\n };\n if (onProgress || onMessage) {\n const lines = splitLines(response.progress);\n forAwait(lines, async (line) => {\n if (onMessage) await onMessage(line);\n if (onProgress) {\n const matches = line.match(/([^:]*).*\\((\\d+?)\\/(\\d+?)\\)/);\n if (matches) {\n await onProgress({\n phase: matches[1].trim(),\n loaded: parseInt(matches[2], 10),\n total: parseInt(matches[3], 10)\n });\n }\n }\n });\n }\n const packfile = Buffer.from(await collect(response.packfile));\n if (raw.body.error) throw raw.body.error;\n const packfileSha = packfile.slice(-20).toString(\"hex\");\n const res = {\n defaultBranch: response.HEAD,\n fetchHead: response.FETCH_HEAD.oid,\n fetchHeadDescription: response.FETCH_HEAD.description\n };\n if (response.headers) {\n res.headers = response.headers;\n }\n if (prune) {\n res.pruned = response.pruned;\n }\n if (packfileSha !== \"\" && !emptyPackfile(packfile)) {\n res.packfile = `objects/pack/pack-${packfileSha}.pack`;\n const fullpath = join2(gitdir, res.packfile);\n await fs.write(fullpath, packfile);\n const getExternalRefDelta = (oid2) => _readObject({ fs, cache, gitdir, oid: oid2 });\n const idx = await GitPackIndex.fromPack({\n pack: packfile,\n getExternalRefDelta,\n onProgress\n });\n const idxPath = fullpath.replace(/\\.pack$/, \".idx\");\n await fs.write(idxPath, await idx.toBuffer());\n seedPackfileCache({ cache, gitdir, packfileSha, index: idx });\n }\n return res;\n}\nasync function _init({\n fs,\n bare = false,\n dir,\n gitdir = bare ? dir : join2(dir, \".git\"),\n defaultBranch = \"master\"\n}) {\n if (await fs.exists(gitdir + \"/config\")) return;\n let folders = [\n \"hooks\",\n \"info\",\n \"objects/info\",\n \"objects/pack\",\n \"refs/heads\",\n \"refs/tags\"\n ];\n folders = folders.map((dir2) => gitdir + \"/\" + dir2);\n for (const folder of folders) {\n await fs.mkdir(folder);\n }\n await fs.write(\n gitdir + \"/config\",\n `[core]\n\trepositoryformatversion = 0\n\tfilemode = false\n\tbare = ${bare}\n` + (bare ? \"\" : \"\tlogallrefupdates = true\\n\") + \"\tsymlinks = false\\n\tignorecase = true\\n\"\n );\n await fs.write(gitdir + \"/HEAD\", `ref: refs/heads/${defaultBranch}\n`);\n}\nasync function _clone({\n fs,\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n onPostCheckout,\n dir,\n gitdir,\n url,\n corsProxy,\n ref,\n remote,\n depth,\n since,\n exclude,\n relative,\n singleBranch,\n noCheckout,\n noTags,\n headers,\n nonBlocking,\n batchSize = 100\n}) {\n try {\n await _init({ fs, gitdir });\n await _addRemote({ fs, gitdir, remote, url, force: false });\n if (corsProxy) {\n const config = await GitConfigManager.get({ fs, gitdir });\n await config.set(`http.corsProxy`, corsProxy);\n await GitConfigManager.save({ fs, gitdir, config });\n }\n const { defaultBranch, fetchHead } = await _fetch({\n fs,\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n gitdir,\n ref,\n remote,\n corsProxy,\n depth,\n since,\n exclude,\n relative,\n singleBranch,\n headers,\n tags: !noTags\n });\n if (fetchHead === null) return;\n ref = ref || defaultBranch;\n ref = ref.replace(\"refs/heads/\", \"\");\n await _checkout({\n fs,\n cache,\n onProgress,\n onPostCheckout,\n dir,\n gitdir,\n ref,\n remote,\n noCheckout,\n nonBlocking,\n batchSize\n });\n } catch (err) {\n await fs.rmdir(gitdir, { recursive: true, maxRetries: 10 }).catch(() => void 0);\n throw err;\n }\n}\nasync function clone({\n fs,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n onPostCheckout,\n dir,\n gitdir = join2(dir, \".git\"),\n url,\n corsProxy = void 0,\n ref = void 0,\n remote = \"origin\",\n depth = void 0,\n since = void 0,\n exclude = [],\n relative = false,\n singleBranch = false,\n noCheckout = false,\n noTags = false,\n headers = {},\n cache = {},\n nonBlocking = false,\n batchSize = 100\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"http\", http);\n assertParameter(\"gitdir\", gitdir);\n if (!noCheckout) {\n assertParameter(\"dir\", dir);\n }\n assertParameter(\"url\", url);\n return await _clone({\n fs: new FileSystem(fs),\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n onPostCheckout,\n dir,\n gitdir,\n url,\n corsProxy,\n ref,\n remote,\n depth,\n since,\n exclude,\n relative,\n singleBranch,\n noCheckout,\n noTags,\n headers,\n nonBlocking,\n batchSize\n });\n } catch (err) {\n err.caller = \"git.clone\";\n throw err;\n }\n}\nasync function commit({\n fs: _fs,\n onSign,\n dir,\n gitdir = join2(dir, \".git\"),\n message,\n author,\n committer,\n signingKey,\n amend = false,\n dryRun = false,\n noUpdateBranch = false,\n ref,\n parent,\n tree,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n if (!amend) {\n assertParameter(\"message\", message);\n }\n if (signingKey) {\n assertParameter(\"onSign\", onSign);\n }\n const fs = new FileSystem(_fs);\n return await _commit({\n fs,\n cache,\n onSign,\n gitdir,\n message,\n author,\n committer,\n signingKey,\n amend,\n dryRun,\n noUpdateBranch,\n ref,\n parent,\n tree\n });\n } catch (err) {\n err.caller = \"git.commit\";\n throw err;\n }\n}\nasync function currentBranch({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n fullname = false,\n test = false\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n return await _currentBranch({\n fs: new FileSystem(fs),\n gitdir,\n fullname,\n test\n });\n } catch (err) {\n err.caller = \"git.currentBranch\";\n throw err;\n }\n}\nasync function _deleteBranch({ fs, gitdir, ref }) {\n ref = ref.startsWith(\"refs/heads/\") ? ref : `refs/heads/${ref}`;\n const exist = await GitRefManager.exists({ fs, gitdir, ref });\n if (!exist) {\n throw new NotFoundError(ref);\n }\n const fullRef = await GitRefManager.expand({ fs, gitdir, ref });\n const currentRef = await _currentBranch({ fs, gitdir, fullname: true });\n if (fullRef === currentRef) {\n const value = await GitRefManager.resolve({ fs, gitdir, ref: fullRef });\n await GitRefManager.writeRef({ fs, gitdir, ref: \"HEAD\", value });\n }\n await GitRefManager.deleteRef({ fs, gitdir, ref: fullRef });\n const abbrevRef = abbreviateRef(ref);\n const config = await GitConfigManager.get({ fs, gitdir });\n await config.deleteSection(\"branch\", abbrevRef);\n await GitConfigManager.save({ fs, gitdir, config });\n}\nasync function deleteBranch({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"ref\", ref);\n return await _deleteBranch({\n fs: new FileSystem(fs),\n gitdir,\n ref\n });\n } catch (err) {\n err.caller = \"git.deleteBranch\";\n throw err;\n }\n}\nasync function deleteRef({ fs, dir, gitdir = join2(dir, \".git\"), ref }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"ref\", ref);\n await GitRefManager.deleteRef({ fs: new FileSystem(fs), gitdir, ref });\n } catch (err) {\n err.caller = \"git.deleteRef\";\n throw err;\n }\n}\nasync function _deleteRemote({ fs, gitdir, remote }) {\n const config = await GitConfigManager.get({ fs, gitdir });\n await config.deleteSection(\"remote\", remote);\n await GitConfigManager.save({ fs, gitdir, config });\n}\nasync function deleteRemote({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n remote\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"remote\", remote);\n return await _deleteRemote({\n fs: new FileSystem(fs),\n gitdir,\n remote\n });\n } catch (err) {\n err.caller = \"git.deleteRemote\";\n throw err;\n }\n}\nasync function _deleteTag({ fs, gitdir, ref }) {\n ref = ref.startsWith(\"refs/tags/\") ? ref : `refs/tags/${ref}`;\n await GitRefManager.deleteRef({ fs, gitdir, ref });\n}\nasync function deleteTag({ fs, dir, gitdir = join2(dir, \".git\"), ref }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"ref\", ref);\n return await _deleteTag({\n fs: new FileSystem(fs),\n gitdir,\n ref\n });\n } catch (err) {\n err.caller = \"git.deleteTag\";\n throw err;\n }\n}\nasync function expandOidLoose({ fs, gitdir, oid: short }) {\n const prefix = short.slice(0, 2);\n const objectsSuffixes = await fs.readdir(`${gitdir}/objects/${prefix}`);\n return objectsSuffixes.map((suffix) => `${prefix}${suffix}`).filter((_oid) => _oid.startsWith(short));\n}\nasync function expandOidPacked({\n fs,\n cache,\n gitdir,\n oid: short,\n getExternalRefDelta\n}) {\n const results = [];\n let list = await fs.readdir(join2(gitdir, \"objects/pack\"));\n list = list.filter((x) => x.endsWith(\".idx\"));\n for (const filename of list) {\n const indexFile = packIndexCacheKey(gitdir, filename);\n const p = await readPackIndex({\n fs,\n cache,\n filename: indexFile,\n getExternalRefDelta\n });\n if (p.error) throw new InternalError(p.error);\n for (const oid of p.offsets.keys()) {\n if (oid.startsWith(short)) results.push(oid);\n }\n }\n return results;\n}\nasync function _expandOid({ fs, cache, gitdir, oid: short }) {\n const getExternalRefDelta = (oid) => _readObject({ fs, cache, gitdir, oid });\n const results = await expandOidLoose({ fs, gitdir, oid: short });\n const packedOids = await expandOidPacked({\n fs,\n cache,\n gitdir,\n oid: short,\n getExternalRefDelta\n });\n for (const packedOid of packedOids) {\n if (results.indexOf(packedOid) === -1) {\n results.push(packedOid);\n }\n }\n if (results.length === 1) {\n return results[0];\n }\n if (results.length > 1) {\n throw new AmbiguousError(\"oids\", short, results);\n }\n throw new NotFoundError(`an object matching \"${short}\"`);\n}\nasync function expandOid({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oid,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n return await _expandOid({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oid\n });\n } catch (err) {\n err.caller = \"git.expandOid\";\n throw err;\n }\n}\nasync function expandRef({ fs, dir, gitdir = join2(dir, \".git\"), ref }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n return await GitRefManager.expand({\n fs: new FileSystem(fs),\n gitdir,\n ref\n });\n } catch (err) {\n err.caller = \"git.expandRef\";\n throw err;\n }\n}\nasync function _findMergeBase({ fs, cache, gitdir, oids }) {\n const visits = {};\n const passes = oids.length;\n let heads = oids.map((oid, index3) => ({ index: index3, oid }));\n while (heads.length) {\n const result = /* @__PURE__ */ new Set();\n for (const { oid, index: index3 } of heads) {\n if (!visits[oid]) visits[oid] = /* @__PURE__ */ new Set();\n visits[oid].add(index3);\n if (visits[oid].size === passes) {\n result.add(oid);\n }\n }\n if (result.size > 0) {\n return [...result];\n }\n const newheads = /* @__PURE__ */ new Map();\n for (const { oid, index: index3 } of heads) {\n try {\n const { object } = await _readObject({ fs, cache, gitdir, oid });\n const commit2 = GitCommit.from(object);\n const { parent } = commit2.parseHeaders();\n for (const oid2 of parent) {\n if (!visits[oid2] || !visits[oid2].has(index3)) {\n newheads.set(oid2 + \":\" + index3, { oid: oid2, index: index3 });\n }\n }\n } catch (err) {\n }\n }\n heads = Array.from(newheads.values());\n }\n return [];\n}\nvar LINEBREAKS = /^.*(\\r?\\n|$)/gm;\nfunction mergeFile({ branches, contents }) {\n const ourName = branches[1];\n const theirName = branches[2];\n const baseContent = contents[0];\n const ourContent = contents[1];\n const theirContent = contents[2];\n const ours = ourContent.match(LINEBREAKS);\n const base = baseContent.match(LINEBREAKS);\n const theirs = theirContent.match(LINEBREAKS);\n const result = (0, import_diff3.default)(ours, base, theirs);\n const markerSize = 7;\n let mergedText = \"\";\n let cleanMerge = true;\n for (const item of result) {\n if (item.ok) {\n mergedText += item.ok.join(\"\");\n }\n if (item.conflict) {\n cleanMerge = false;\n mergedText += `${\"<\".repeat(markerSize)} ${ourName}\n`;\n mergedText += item.conflict.a.join(\"\");\n mergedText += `${\"=\".repeat(markerSize)}\n`;\n mergedText += item.conflict.b.join(\"\");\n mergedText += `${\">\".repeat(markerSize)} ${theirName}\n`;\n }\n }\n return { cleanMerge, mergedText };\n}\nasync function mergeTree({\n fs,\n cache,\n dir,\n gitdir = join2(dir, \".git\"),\n index: index3,\n ourOid,\n baseOid,\n theirOid,\n ourName = \"ours\",\n baseName = \"base\",\n theirName = \"theirs\",\n dryRun = false,\n abortOnConflict = true,\n mergeDriver\n}) {\n const ourTree = TREE({ ref: ourOid });\n const baseTree = TREE({ ref: baseOid });\n const theirTree = TREE({ ref: theirOid });\n const unmergedFiles = [];\n const bothModified = [];\n const deleteByUs = [];\n const deleteByTheirs = [];\n const results = await _walk({\n fs,\n cache,\n dir,\n gitdir,\n trees: [ourTree, baseTree, theirTree],\n map: async function(filepath, [ours, base, theirs]) {\n const path = basename(filepath);\n const ourChange = await modified(ours, base);\n const theirChange = await modified(theirs, base);\n switch (`${ourChange}-${theirChange}`) {\n case \"false-false\": {\n return {\n mode: await base.mode(),\n path,\n oid: await base.oid(),\n type: await base.type()\n };\n }\n case \"false-true\": {\n if (!theirs && await ours.type() === \"tree\") {\n return {\n mode: await ours.mode(),\n path,\n oid: await ours.oid(),\n type: await ours.type()\n };\n }\n return theirs ? {\n mode: await theirs.mode(),\n path,\n oid: await theirs.oid(),\n type: await theirs.type()\n } : void 0;\n }\n case \"true-false\": {\n if (!ours && await theirs.type() === \"tree\") {\n return {\n mode: await theirs.mode(),\n path,\n oid: await theirs.oid(),\n type: await theirs.type()\n };\n }\n return ours ? {\n mode: await ours.mode(),\n path,\n oid: await ours.oid(),\n type: await ours.type()\n } : void 0;\n }\n case \"true-true\": {\n if (ours && theirs && await ours.type() === \"tree\" && await theirs.type() === \"tree\") {\n return {\n mode: await ours.mode(),\n path,\n oid: await ours.oid(),\n type: \"tree\"\n };\n }\n if (ours && theirs && await ours.type() === \"blob\" && await theirs.type() === \"blob\") {\n return mergeBlobs({\n fs,\n gitdir,\n path,\n ours,\n base,\n theirs,\n ourName,\n baseName,\n theirName,\n mergeDriver\n }).then(async (r) => {\n if (!r.cleanMerge) {\n unmergedFiles.push(filepath);\n bothModified.push(filepath);\n if (!abortOnConflict) {\n let baseOid2 = \"\";\n if (base && await base.type() === \"blob\") {\n baseOid2 = await base.oid();\n }\n const ourOid2 = await ours.oid();\n const theirOid2 = await theirs.oid();\n index3.delete({ filepath });\n if (baseOid2) {\n index3.insert({ filepath, oid: baseOid2, stage: 1 });\n }\n index3.insert({ filepath, oid: ourOid2, stage: 2 });\n index3.insert({ filepath, oid: theirOid2, stage: 3 });\n }\n } else if (!abortOnConflict) {\n index3.insert({ filepath, oid: r.mergeResult.oid, stage: 0 });\n }\n return r.mergeResult;\n });\n }\n if (base && !ours && theirs && await base.type() === \"blob\" && await theirs.type() === \"blob\") {\n unmergedFiles.push(filepath);\n deleteByUs.push(filepath);\n if (!abortOnConflict) {\n const baseOid2 = await base.oid();\n const theirOid2 = await theirs.oid();\n index3.delete({ filepath });\n index3.insert({ filepath, oid: baseOid2, stage: 1 });\n index3.insert({ filepath, oid: theirOid2, stage: 3 });\n }\n return {\n mode: await theirs.mode(),\n oid: await theirs.oid(),\n type: \"blob\",\n path\n };\n }\n if (base && ours && !theirs && await base.type() === \"blob\" && await ours.type() === \"blob\") {\n unmergedFiles.push(filepath);\n deleteByTheirs.push(filepath);\n if (!abortOnConflict) {\n const baseOid2 = await base.oid();\n const ourOid2 = await ours.oid();\n index3.delete({ filepath });\n index3.insert({ filepath, oid: baseOid2, stage: 1 });\n index3.insert({ filepath, oid: ourOid2, stage: 2 });\n }\n return {\n mode: await ours.mode(),\n oid: await ours.oid(),\n type: \"blob\",\n path\n };\n }\n if (base && !ours && !theirs && (await base.type() === \"blob\" || await base.type() === \"tree\")) {\n return void 0;\n }\n throw new MergeNotSupportedError();\n }\n }\n },\n /**\n * @param {TreeEntry} [parent]\n * @param {Array<TreeEntry>} children\n */\n reduce: unmergedFiles.length !== 0 && (!dir || abortOnConflict) ? void 0 : async (parent, children) => {\n const entries = children.filter(Boolean);\n if (!parent) return;\n if (parent && parent.type === \"tree\" && entries.length === 0 && parent.path !== \".\")\n return;\n if (entries.length > 0 || parent.path === \".\" && entries.length === 0) {\n const tree = new GitTree(entries);\n const object = tree.toObject();\n const oid = await _writeObject({\n fs,\n gitdir,\n type: \"tree\",\n object,\n dryRun\n });\n parent.oid = oid;\n }\n return parent;\n }\n });\n if (unmergedFiles.length !== 0) {\n if (dir && !abortOnConflict) {\n await _walk({\n fs,\n cache,\n dir,\n gitdir,\n trees: [TREE({ ref: results.oid })],\n map: async function(filepath, [entry]) {\n const path = `${dir}/${filepath}`;\n if (await entry.type() === \"blob\") {\n const mode = await entry.mode();\n const content = new TextDecoder().decode(await entry.content());\n await fs.write(path, content, { mode });\n }\n return true;\n }\n });\n }\n return new MergeConflictError(\n unmergedFiles,\n bothModified,\n deleteByUs,\n deleteByTheirs\n );\n }\n return results.oid;\n}\nasync function mergeBlobs({\n fs,\n gitdir,\n path,\n ours,\n base,\n theirs,\n ourName,\n theirName,\n baseName,\n dryRun,\n mergeDriver = mergeFile\n}) {\n const type = \"blob\";\n let baseMode = \"100755\";\n let baseOid = \"\";\n let baseContent = \"\";\n if (base && await base.type() === \"blob\") {\n baseMode = await base.mode();\n baseOid = await base.oid();\n baseContent = Buffer.from(await base.content()).toString(\"utf8\");\n }\n const mode = baseMode === await ours.mode() ? await theirs.mode() : await ours.mode();\n if (await ours.oid() === await theirs.oid()) {\n return {\n cleanMerge: true,\n mergeResult: { mode, path, oid: await ours.oid(), type }\n };\n }\n if (await ours.oid() === baseOid) {\n return {\n cleanMerge: true,\n mergeResult: { mode, path, oid: await theirs.oid(), type }\n };\n }\n if (await theirs.oid() === baseOid) {\n return {\n cleanMerge: true,\n mergeResult: { mode, path, oid: await ours.oid(), type }\n };\n }\n const ourContent = Buffer.from(await ours.content()).toString(\"utf8\");\n const theirContent = Buffer.from(await theirs.content()).toString(\"utf8\");\n const { mergedText, cleanMerge } = await mergeDriver({\n branches: [baseName, ourName, theirName],\n contents: [baseContent, ourContent, theirContent],\n path\n });\n const oid = await _writeObject({\n fs,\n gitdir,\n type: \"blob\",\n object: Buffer.from(mergedText, \"utf8\"),\n dryRun\n });\n return { cleanMerge, mergeResult: { mode, path, oid, type } };\n}\nasync function _merge({\n fs,\n cache,\n dir,\n gitdir,\n ours,\n theirs,\n fastForward: fastForward2 = true,\n fastForwardOnly = false,\n dryRun = false,\n noUpdateBranch = false,\n abortOnConflict = true,\n message,\n author,\n committer,\n signingKey,\n onSign,\n mergeDriver,\n allowUnrelatedHistories = false\n}) {\n if (ours === void 0) {\n ours = await _currentBranch({ fs, gitdir, fullname: true });\n }\n ours = await GitRefManager.expand({\n fs,\n gitdir,\n ref: ours\n });\n theirs = await GitRefManager.expand({\n fs,\n gitdir,\n ref: theirs\n });\n const ourOid = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: ours\n });\n const theirOid = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: theirs\n });\n const baseOids = await _findMergeBase({\n fs,\n cache,\n gitdir,\n oids: [ourOid, theirOid]\n });\n if (baseOids.length !== 1) {\n if (baseOids.length === 0 && allowUnrelatedHistories) {\n baseOids.push(\"4b825dc642cb6eb9a060e54bf8d69288fbee4904\");\n } else {\n throw new MergeNotSupportedError();\n }\n }\n const baseOid = baseOids[0];\n if (baseOid === theirOid) {\n return {\n oid: ourOid,\n alreadyMerged: true\n };\n }\n if (fastForward2 && baseOid === ourOid) {\n if (!dryRun && !noUpdateBranch) {\n await GitRefManager.writeRef({ fs, gitdir, ref: ours, value: theirOid });\n }\n return {\n oid: theirOid,\n fastForward: true\n };\n } else {\n if (fastForwardOnly) {\n throw new FastForwardError();\n }\n const tree = await GitIndexManager.acquire(\n { fs, gitdir, cache, allowUnmerged: false },\n async (index3) => {\n return mergeTree({\n fs,\n cache,\n dir,\n gitdir,\n index: index3,\n ourOid,\n theirOid,\n baseOid,\n ourName: abbreviateRef(ours),\n baseName: \"base\",\n theirName: abbreviateRef(theirs),\n dryRun,\n abortOnConflict,\n mergeDriver\n });\n }\n );\n if (tree instanceof MergeConflictError) throw tree;\n if (!message) {\n message = `Merge branch '${abbreviateRef(theirs)}' into ${abbreviateRef(\n ours\n )}`;\n }\n const oid = await _commit({\n fs,\n cache,\n gitdir,\n message,\n ref: ours,\n tree,\n parent: [ourOid, theirOid],\n author,\n committer,\n signingKey,\n onSign,\n dryRun,\n noUpdateBranch\n });\n return {\n oid,\n tree,\n mergeCommit: true\n };\n }\n}\nasync function _pull({\n fs,\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n dir,\n gitdir,\n ref,\n url,\n remote,\n remoteRef,\n prune,\n pruneTags,\n fastForward: fastForward2,\n fastForwardOnly,\n corsProxy,\n singleBranch,\n headers,\n author,\n committer,\n signingKey\n}) {\n try {\n if (!ref) {\n const head = await _currentBranch({ fs, gitdir });\n if (!head) {\n throw new MissingParameterError(\"ref\");\n }\n ref = head;\n }\n const { fetchHead, fetchHeadDescription } = await _fetch({\n fs,\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n gitdir,\n corsProxy,\n ref,\n url,\n remote,\n remoteRef,\n singleBranch,\n headers,\n prune,\n pruneTags\n });\n await _merge({\n fs,\n cache,\n gitdir,\n ours: ref,\n theirs: fetchHead,\n fastForward: fastForward2,\n fastForwardOnly,\n message: `Merge ${fetchHeadDescription}`,\n author,\n committer,\n signingKey,\n dryRun: false,\n noUpdateBranch: false\n });\n await _checkout({\n fs,\n cache,\n onProgress,\n dir,\n gitdir,\n ref,\n remote,\n noCheckout: false\n });\n } catch (err) {\n err.caller = \"git.pull\";\n throw err;\n }\n}\nasync function fastForward({\n fs,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n url,\n remote,\n remoteRef,\n corsProxy,\n singleBranch,\n headers = {},\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"http\", http);\n assertParameter(\"gitdir\", gitdir);\n const thisWillNotBeUsed = {\n name: \"\",\n email: \"\",\n timestamp: Date.now(),\n timezoneOffset: 0\n };\n return await _pull({\n fs: new FileSystem(fs),\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n dir,\n gitdir,\n ref,\n url,\n remote,\n remoteRef,\n fastForwardOnly: true,\n corsProxy,\n singleBranch,\n headers,\n author: thisWillNotBeUsed,\n committer: thisWillNotBeUsed\n });\n } catch (err) {\n err.caller = \"git.fastForward\";\n throw err;\n }\n}\nasync function fetch2({\n fs,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n remote,\n remoteRef,\n url,\n corsProxy,\n depth = null,\n since = null,\n exclude = [],\n relative = false,\n tags = false,\n singleBranch = false,\n headers = {},\n prune = false,\n pruneTags = false,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"http\", http);\n assertParameter(\"gitdir\", gitdir);\n return await _fetch({\n fs: new FileSystem(fs),\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n gitdir,\n ref,\n remote,\n remoteRef,\n url,\n corsProxy,\n depth,\n since,\n exclude,\n relative,\n tags,\n singleBranch,\n headers,\n prune,\n pruneTags\n });\n } catch (err) {\n err.caller = \"git.fetch\";\n throw err;\n }\n}\nasync function findMergeBase({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oids,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oids\", oids);\n return await _findMergeBase({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oids\n });\n } catch (err) {\n err.caller = \"git.findMergeBase\";\n throw err;\n }\n}\nasync function _findRoot({ fs, filepath }) {\n if (await fs.exists(join2(filepath, \".git\"))) {\n return filepath;\n } else {\n const parent = dirname(filepath);\n if (parent === filepath) {\n throw new NotFoundError(`git root for ${filepath}`);\n }\n return _findRoot({ fs, filepath: parent });\n }\n}\nasync function findRoot({ fs, filepath }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"filepath\", filepath);\n return await _findRoot({ fs: new FileSystem(fs), filepath });\n } catch (err) {\n err.caller = \"git.findRoot\";\n throw err;\n }\n}\nasync function getConfig({ fs, dir, gitdir = join2(dir, \".git\"), path }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"path\", path);\n return await _getConfig({\n fs: new FileSystem(fs),\n gitdir,\n path\n });\n } catch (err) {\n err.caller = \"git.getConfig\";\n throw err;\n }\n}\nasync function _getConfigAll({ fs, gitdir, path }) {\n const config = await GitConfigManager.get({ fs, gitdir });\n return config.getall(path);\n}\nasync function getConfigAll({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n path\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"path\", path);\n return await _getConfigAll({\n fs: new FileSystem(fs),\n gitdir,\n path\n });\n } catch (err) {\n err.caller = \"git.getConfigAll\";\n throw err;\n }\n}\nasync function getRemoteInfo({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n url,\n headers = {},\n forPush = false\n}) {\n try {\n assertParameter(\"http\", http);\n assertParameter(\"url\", url);\n const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });\n const remote = await GitRemoteHTTP2.discover({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n service: forPush ? \"git-receive-pack\" : \"git-upload-pack\",\n url,\n headers,\n protocolVersion: 1\n });\n const result = {\n capabilities: [...remote.capabilities]\n };\n for (const [ref, oid] of remote.refs) {\n const parts = ref.split(\"/\");\n const last = parts.pop();\n let o = result;\n for (const part of parts) {\n o[part] = o[part] || {};\n o = o[part];\n }\n o[last] = oid;\n }\n for (const [symref, ref] of remote.symrefs) {\n const parts = symref.split(\"/\");\n const last = parts.pop();\n let o = result;\n for (const part of parts) {\n o[part] = o[part] || {};\n o = o[part];\n }\n o[last] = ref;\n }\n return result;\n } catch (err) {\n err.caller = \"git.getRemoteInfo\";\n throw err;\n }\n}\nfunction formatInfoRefs(remote, prefix, symrefs, peelTags) {\n const refs = [];\n for (const [key, value] of remote.refs) {\n if (prefix && !key.startsWith(prefix)) continue;\n if (key.endsWith(\"^{}\")) {\n if (peelTags) {\n const _key = key.replace(\"^{}\", \"\");\n const last = refs[refs.length - 1];\n const r = last.ref === _key ? last : refs.find((x) => x.ref === _key);\n if (r === void 0) {\n throw new Error(\"I did not expect this to happen\");\n }\n r.peeled = value;\n }\n continue;\n }\n const ref = { ref: key, oid: value };\n if (symrefs) {\n if (remote.symrefs.has(key)) {\n ref.target = remote.symrefs.get(key);\n }\n }\n refs.push(ref);\n }\n return refs;\n}\nasync function getRemoteInfo2({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n url,\n headers = {},\n forPush = false,\n protocolVersion = 2\n}) {\n try {\n assertParameter(\"http\", http);\n assertParameter(\"url\", url);\n const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });\n const remote = await GitRemoteHTTP2.discover({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n service: forPush ? \"git-receive-pack\" : \"git-upload-pack\",\n url,\n headers,\n protocolVersion\n });\n if (remote.protocolVersion === 2) {\n return {\n protocolVersion: remote.protocolVersion,\n capabilities: remote.capabilities2\n };\n }\n const capabilities = {};\n for (const cap of remote.capabilities) {\n const [key, value] = cap.split(\"=\");\n if (value) {\n capabilities[key] = value;\n } else {\n capabilities[key] = true;\n }\n }\n return {\n protocolVersion: 1,\n capabilities,\n refs: formatInfoRefs(remote, void 0, true, true)\n };\n } catch (err) {\n err.caller = \"git.getRemoteInfo2\";\n throw err;\n }\n}\nasync function hashObject({\n type,\n object,\n format = \"content\",\n oid = void 0\n}) {\n if (format !== \"deflated\") {\n if (format !== \"wrapped\") {\n object = GitObject.wrap({ type, object });\n }\n oid = await shasum(object);\n }\n return { oid, object };\n}\nasync function hashBlob({ object }) {\n try {\n assertParameter(\"object\", object);\n if (typeof object === \"string\") {\n object = Buffer.from(object, \"utf8\");\n } else if (!(object instanceof Uint8Array)) {\n object = new Uint8Array(object);\n }\n const type = \"blob\";\n const { oid, object: _object } = await hashObject({\n type,\n format: \"content\",\n object\n });\n return { oid, type, object: _object, format: \"wrapped\" };\n } catch (err) {\n err.caller = \"git.hashBlob\";\n throw err;\n }\n}\nasync function _indexPack({\n fs,\n cache,\n onProgress,\n dir,\n gitdir,\n filepath\n}) {\n try {\n filepath = join2(dir, filepath);\n const pack = await fs.read(filepath);\n const getExternalRefDelta = (oid) => _readObject({ fs, cache, gitdir, oid });\n const idx = await GitPackIndex.fromPack({\n pack,\n getExternalRefDelta,\n onProgress\n });\n await fs.write(filepath.replace(/\\.pack$/, \".idx\"), await idx.toBuffer());\n return {\n oids: [...idx.hashes]\n };\n } catch (err) {\n err.caller = \"git.indexPack\";\n throw err;\n }\n}\nasync function indexPack({\n fs,\n onProgress,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"dir\", dir);\n assertParameter(\"gitdir\", dir);\n assertParameter(\"filepath\", filepath);\n return await _indexPack({\n fs: new FileSystem(fs),\n cache,\n onProgress,\n dir,\n gitdir,\n filepath\n });\n } catch (err) {\n err.caller = \"git.indexPack\";\n throw err;\n }\n}\nasync function init({\n fs,\n bare = false,\n dir,\n gitdir = bare ? dir : join2(dir, \".git\"),\n defaultBranch = \"master\"\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n if (!bare) {\n assertParameter(\"dir\", dir);\n }\n return await _init({\n fs: new FileSystem(fs),\n bare,\n dir,\n gitdir,\n defaultBranch\n });\n } catch (err) {\n err.caller = \"git.init\";\n throw err;\n }\n}\nasync function _isDescendent({\n fs,\n cache,\n gitdir,\n oid,\n ancestor,\n depth\n}) {\n const shallows = await GitShallowManager.read({ fs, gitdir });\n if (!oid) {\n throw new MissingParameterError(\"oid\");\n }\n if (!ancestor) {\n throw new MissingParameterError(\"ancestor\");\n }\n if (oid === ancestor) return false;\n const queue = [oid];\n const visited = /* @__PURE__ */ new Set();\n let searchdepth = 0;\n while (queue.length) {\n if (searchdepth++ === depth) {\n throw new MaxDepthError(depth);\n }\n const oid2 = queue.shift();\n const { type, object } = await _readObject({\n fs,\n cache,\n gitdir,\n oid: oid2\n });\n if (type !== \"commit\") {\n throw new ObjectTypeError(oid2, type, \"commit\");\n }\n const commit2 = GitCommit.from(object).parse();\n for (const parent of commit2.parent) {\n if (parent === ancestor) return true;\n }\n if (!shallows.has(oid2)) {\n for (const parent of commit2.parent) {\n if (!visited.has(parent)) {\n queue.push(parent);\n visited.add(parent);\n }\n }\n }\n }\n return false;\n}\nasync function isDescendent({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oid,\n ancestor,\n depth = -1,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n assertParameter(\"ancestor\", ancestor);\n return await _isDescendent({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oid,\n ancestor,\n depth\n });\n } catch (err) {\n err.caller = \"git.isDescendent\";\n throw err;\n }\n}\nasync function isIgnored({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"dir\", dir);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"filepath\", filepath);\n return GitIgnoreManager.isIgnored({\n fs: new FileSystem(fs),\n dir,\n gitdir,\n filepath\n });\n } catch (err) {\n err.caller = \"git.isIgnored\";\n throw err;\n }\n}\nasync function listBranches({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n remote\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n return GitRefManager.listBranches({\n fs: new FileSystem(fs),\n gitdir,\n remote\n });\n } catch (err) {\n err.caller = \"git.listBranches\";\n throw err;\n }\n}\nasync function _listFiles({ fs, gitdir, ref, cache }) {\n if (ref) {\n const oid = await GitRefManager.resolve({ gitdir, fs, ref });\n const filenames = [];\n await accumulateFilesFromOid({\n fs,\n cache,\n gitdir,\n oid,\n filenames,\n prefix: \"\"\n });\n return filenames;\n } else {\n return GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n return index3.entries.map((x) => x.path);\n });\n }\n}\nasync function accumulateFilesFromOid({\n fs,\n cache,\n gitdir,\n oid,\n filenames,\n prefix\n}) {\n const { tree } = await _readTree({ fs, cache, gitdir, oid });\n for (const entry of tree) {\n if (entry.type === \"tree\") {\n await accumulateFilesFromOid({\n fs,\n cache,\n gitdir,\n oid: entry.oid,\n filenames,\n prefix: join2(prefix, entry.path)\n });\n } else {\n filenames.push(join2(prefix, entry.path));\n }\n }\n}\nasync function listFiles({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n return await _listFiles({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n ref\n });\n } catch (err) {\n err.caller = \"git.listFiles\";\n throw err;\n }\n}\nasync function _listNotes({ fs, cache, gitdir, ref }) {\n let parent;\n try {\n parent = await GitRefManager.resolve({ gitdir, fs, ref });\n } catch (err) {\n if (err instanceof NotFoundError) {\n return [];\n }\n }\n const result = await _readTree({\n fs,\n cache,\n gitdir,\n oid: parent\n });\n const notes = result.tree.map((entry) => ({\n target: entry.path,\n note: entry.oid\n }));\n return notes;\n}\nasync function listNotes({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref = \"refs/notes/commits\",\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n return await _listNotes({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n ref\n });\n } catch (err) {\n err.caller = \"git.listNotes\";\n throw err;\n }\n}\nasync function listRefs({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n return GitRefManager.listRefs({ fs: new FileSystem(fs), gitdir, filepath });\n } catch (err) {\n err.caller = \"git.listRefs\";\n throw err;\n }\n}\nasync function _listRemotes({ fs, gitdir }) {\n const config = await GitConfigManager.get({ fs, gitdir });\n const remoteNames = await config.getSubsections(\"remote\");\n const remotes = Promise.all(\n remoteNames.map(async (remote) => {\n const url = await config.get(`remote.${remote}.url`);\n return { remote, url };\n })\n );\n return remotes;\n}\nasync function listRemotes({ fs, dir, gitdir = join2(dir, \".git\") }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n return await _listRemotes({\n fs: new FileSystem(fs),\n gitdir\n });\n } catch (err) {\n err.caller = \"git.listRemotes\";\n throw err;\n }\n}\nasync function parseListRefsResponse(stream) {\n const read = GitPktLine.streamReader(stream);\n const refs = [];\n let line;\n while (true) {\n line = await read();\n if (line === true) break;\n if (line === null) continue;\n line = line.toString(\"utf8\").replace(/\\n$/, \"\");\n const [oid, ref, ...attrs] = line.split(\" \");\n const r = { ref, oid };\n for (const attr of attrs) {\n const [name, value] = attr.split(\":\");\n if (name === \"symref-target\") {\n r.target = value;\n } else if (name === \"peeled\") {\n r.peeled = value;\n }\n }\n refs.push(r);\n }\n return refs;\n}\nasync function writeListRefsRequest({ prefix, symrefs, peelTags }) {\n const packstream = [];\n packstream.push(GitPktLine.encode(\"command=ls-refs\\n\"));\n packstream.push(GitPktLine.encode(`agent=${pkg.agent}\n`));\n if (peelTags || symrefs || prefix) {\n packstream.push(GitPktLine.delim());\n }\n if (peelTags) packstream.push(GitPktLine.encode(\"peel\"));\n if (symrefs) packstream.push(GitPktLine.encode(\"symrefs\"));\n if (prefix) packstream.push(GitPktLine.encode(`ref-prefix ${prefix}`));\n packstream.push(GitPktLine.flush());\n return packstream;\n}\nasync function listServerRefs({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n url,\n headers = {},\n forPush = false,\n protocolVersion = 2,\n prefix,\n symrefs,\n peelTags\n}) {\n try {\n assertParameter(\"http\", http);\n assertParameter(\"url\", url);\n const remote = await GitRemoteHTTP.discover({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n service: forPush ? \"git-receive-pack\" : \"git-upload-pack\",\n url,\n headers,\n protocolVersion\n });\n if (remote.protocolVersion === 1) {\n return formatInfoRefs(remote, prefix, symrefs, peelTags);\n }\n const body = await writeListRefsRequest({ prefix, symrefs, peelTags });\n const res = await GitRemoteHTTP.connect({\n http,\n auth: remote.auth,\n headers,\n corsProxy,\n service: forPush ? \"git-receive-pack\" : \"git-upload-pack\",\n url,\n body\n });\n return parseListRefsResponse(res.body);\n } catch (err) {\n err.caller = \"git.listServerRefs\";\n throw err;\n }\n}\nasync function listTags({ fs, dir, gitdir = join2(dir, \".git\") }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n return GitRefManager.listTags({ fs: new FileSystem(fs), gitdir });\n } catch (err) {\n err.caller = \"git.listTags\";\n throw err;\n }\n}\nfunction compareAge(a, b) {\n return a.committer.timestamp - b.committer.timestamp;\n}\nvar EMPTY_OID = \"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391\";\nasync function resolveFileIdInTree({ fs, cache, gitdir, oid, fileId }) {\n if (fileId === EMPTY_OID) return;\n const _oid = oid;\n let filepath;\n const result = await resolveTree({ fs, cache, gitdir, oid });\n const tree = result.tree;\n if (fileId === result.oid) {\n filepath = result.path;\n } else {\n filepath = await _resolveFileId({\n fs,\n cache,\n gitdir,\n tree,\n fileId,\n oid: _oid\n });\n if (Array.isArray(filepath)) {\n if (filepath.length === 0) filepath = void 0;\n else if (filepath.length === 1) filepath = filepath[0];\n }\n }\n return filepath;\n}\nasync function _resolveFileId({\n fs,\n cache,\n gitdir,\n tree,\n fileId,\n oid,\n filepaths = [],\n parentPath = \"\"\n}) {\n const walks = tree.entries().map(function(entry) {\n let result;\n if (entry.oid === fileId) {\n result = join2(parentPath, entry.path);\n filepaths.push(result);\n } else if (entry.type === \"tree\") {\n result = _readObject({\n fs,\n cache,\n gitdir,\n oid: entry.oid\n }).then(function({ object }) {\n return _resolveFileId({\n fs,\n cache,\n gitdir,\n tree: GitTree.from(object),\n fileId,\n oid,\n filepaths,\n parentPath: join2(parentPath, entry.path)\n });\n });\n }\n return result;\n });\n await Promise.all(walks);\n return filepaths;\n}\nasync function _log({\n fs,\n cache,\n gitdir,\n filepath,\n ref,\n depth,\n since,\n force,\n follow\n}) {\n const sinceTimestamp = typeof since === \"undefined\" ? void 0 : Math.floor(since.valueOf() / 1e3);\n const commits = [];\n const shallowCommits = await GitShallowManager.read({ fs, gitdir });\n const oid = await GitRefManager.resolve({ fs, gitdir, ref });\n const tips = [await _readCommit({ fs, cache, gitdir, oid })];\n let lastFileOid;\n let lastCommit;\n let isOk;\n function endCommit(commit2) {\n if (isOk && filepath) commits.push(commit2);\n }\n while (tips.length > 0) {\n const commit2 = tips.pop();\n if (sinceTimestamp !== void 0 && commit2.commit.committer.timestamp <= sinceTimestamp) {\n break;\n }\n if (filepath) {\n let vFileOid;\n try {\n vFileOid = await resolveFilepath({\n fs,\n cache,\n gitdir,\n oid: commit2.commit.tree,\n filepath\n });\n if (lastCommit && lastFileOid !== vFileOid) {\n commits.push(lastCommit);\n }\n lastFileOid = vFileOid;\n lastCommit = commit2;\n isOk = true;\n } catch (e) {\n if (e instanceof NotFoundError) {\n let found = follow && lastFileOid;\n if (found) {\n found = await resolveFileIdInTree({\n fs,\n cache,\n gitdir,\n oid: commit2.commit.tree,\n fileId: lastFileOid\n });\n if (found) {\n if (Array.isArray(found)) {\n if (lastCommit) {\n const lastFound = await resolveFileIdInTree({\n fs,\n cache,\n gitdir,\n oid: lastCommit.commit.tree,\n fileId: lastFileOid\n });\n if (Array.isArray(lastFound)) {\n found = found.filter((p) => lastFound.indexOf(p) === -1);\n if (found.length === 1) {\n found = found[0];\n filepath = found;\n if (lastCommit) commits.push(lastCommit);\n } else {\n found = false;\n if (lastCommit) commits.push(lastCommit);\n break;\n }\n }\n }\n } else {\n filepath = found;\n if (lastCommit) commits.push(lastCommit);\n }\n }\n }\n if (!found) {\n if (isOk && lastFileOid) {\n commits.push(lastCommit);\n if (!force) break;\n }\n if (!force && !follow) throw e;\n }\n lastCommit = commit2;\n isOk = false;\n } else throw e;\n }\n } else {\n commits.push(commit2);\n }\n if (depth !== void 0 && commits.length === depth) {\n endCommit(commit2);\n break;\n }\n if (!shallowCommits.has(commit2.oid)) {\n for (const oid2 of commit2.commit.parent) {\n const commit3 = await _readCommit({ fs, cache, gitdir, oid: oid2 });\n if (!tips.map((commit4) => commit4.oid).includes(commit3.oid)) {\n tips.push(commit3);\n }\n }\n }\n if (tips.length === 0) {\n endCommit(commit2);\n }\n tips.sort((a, b) => compareAge(a.commit, b.commit));\n }\n return commits;\n}\nasync function log({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath,\n ref = \"HEAD\",\n depth,\n since,\n // Date\n force,\n follow,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n return await _log({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n filepath,\n ref,\n depth,\n since,\n force,\n follow\n });\n } catch (err) {\n err.caller = \"git.log\";\n throw err;\n }\n}\nasync function merge({\n fs: _fs,\n onSign,\n dir,\n gitdir = join2(dir, \".git\"),\n ours,\n theirs,\n fastForward: fastForward2 = true,\n fastForwardOnly = false,\n dryRun = false,\n noUpdateBranch = false,\n abortOnConflict = true,\n message,\n author: _author,\n committer: _committer,\n signingKey,\n cache = {},\n mergeDriver,\n allowUnrelatedHistories = false\n}) {\n try {\n assertParameter(\"fs\", _fs);\n if (signingKey) {\n assertParameter(\"onSign\", onSign);\n }\n const fs = new FileSystem(_fs);\n const author = await normalizeAuthorObject({ fs, gitdir, author: _author });\n if (!author && (!fastForwardOnly || !fastForward2)) {\n throw new MissingNameError(\"author\");\n }\n const committer = await normalizeCommitterObject({\n fs,\n gitdir,\n author,\n committer: _committer\n });\n if (!committer && (!fastForwardOnly || !fastForward2)) {\n throw new MissingNameError(\"committer\");\n }\n return await _merge({\n fs,\n cache,\n dir,\n gitdir,\n ours,\n theirs,\n fastForward: fastForward2,\n fastForwardOnly,\n dryRun,\n noUpdateBranch,\n abortOnConflict,\n message,\n author,\n committer,\n signingKey,\n onSign,\n mergeDriver,\n allowUnrelatedHistories\n });\n } catch (err) {\n err.caller = \"git.merge\";\n throw err;\n }\n}\nvar types = {\n commit: 16,\n tree: 32,\n blob: 48,\n tag: 64,\n ofs_delta: 96,\n ref_delta: 112\n};\nvar Hash = class {\n constructor() {\n this.data = [];\n }\n update(chunk) {\n this.data.push(chunk);\n return this;\n }\n digest() {\n const totalLength = this.data.reduce((sum, arr) => sum + arr.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of this.data) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle && crypto.subtle.digestSync) {\n const hashBuffer = crypto.subtle.digestSync(\"SHA-1\", combined);\n return Buffer.from(hashBuffer);\n }\n const hash = createHash(\"sha1\");\n hash.update(combined);\n return hash.digest();\n }\n};\nasync function _pack({\n fs,\n cache,\n dir,\n gitdir = join2(dir, \".git\"),\n oids\n}) {\n const hash = new Hash();\n const outputStream = [];\n function write(chunk, enc) {\n const buff = Buffer.from(chunk, enc);\n outputStream.push(buff);\n hash.update(buff);\n }\n async function writeObject2({ stype, object }) {\n const type = types[stype];\n let length = object.length;\n let multibyte = length > 15 ? 128 : 0;\n const lastFour = length & 15;\n length = length >>> 4;\n let byte = (multibyte | type | lastFour).toString(16);\n write(byte, \"hex\");\n while (multibyte) {\n multibyte = length > 127 ? 128 : 0;\n byte = multibyte | length & 127;\n write(padHex(2, byte), \"hex\");\n length = length >>> 7;\n }\n write(Buffer.from(await deflate(object)));\n }\n write(\"PACK\");\n write(\"00000002\", \"hex\");\n write(padHex(8, oids.length), \"hex\");\n for (const oid of oids) {\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n await writeObject2({ write, object, stype: type });\n }\n const digest = hash.digest();\n outputStream.push(digest);\n return outputStream;\n}\nasync function _packObjects({ fs, cache, gitdir, oids, write }) {\n const buffers = await _pack({ fs, cache, gitdir, oids });\n const packfile = Buffer.from(await collect(buffers));\n const packfileSha = packfile.slice(-20).toString(\"hex\");\n const filename = `pack-${packfileSha}.pack`;\n if (write) {\n await fs.write(join2(gitdir, `objects/pack/${filename}`), packfile);\n return { filename };\n }\n return {\n filename,\n packfile: new Uint8Array(packfile)\n };\n}\nasync function packObjects({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oids,\n write = false,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oids\", oids);\n return await _packObjects({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oids,\n write\n });\n } catch (err) {\n err.caller = \"git.packObjects\";\n throw err;\n }\n}\nasync function pull({\n fs: _fs,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n url,\n remote,\n remoteRef,\n prune = false,\n pruneTags = false,\n fastForward: fastForward2 = true,\n fastForwardOnly = false,\n corsProxy,\n singleBranch,\n headers = {},\n author: _author,\n committer: _committer,\n signingKey,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n const fs = new FileSystem(_fs);\n const author = await normalizeAuthorObject({ fs, gitdir, author: _author });\n if (!author) throw new MissingNameError(\"author\");\n const committer = await normalizeCommitterObject({\n fs,\n gitdir,\n author,\n committer: _committer\n });\n if (!committer) throw new MissingNameError(\"committer\");\n return await _pull({\n fs,\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n dir,\n gitdir,\n ref,\n url,\n remote,\n remoteRef,\n fastForward: fastForward2,\n fastForwardOnly,\n corsProxy,\n singleBranch,\n headers,\n author,\n committer,\n signingKey,\n prune,\n pruneTags\n });\n } catch (err) {\n err.caller = \"git.pull\";\n throw err;\n }\n}\nasync function listCommitsAndTags({\n fs,\n cache,\n dir,\n gitdir = join2(dir, \".git\"),\n start,\n finish\n}) {\n const shallows = await GitShallowManager.read({ fs, gitdir });\n const startingSet = /* @__PURE__ */ new Set();\n const finishingSet = /* @__PURE__ */ new Set();\n for (const ref of start) {\n startingSet.add(await GitRefManager.resolve({ fs, gitdir, ref }));\n }\n for (const ref of finish) {\n try {\n const oid = await GitRefManager.resolve({ fs, gitdir, ref });\n finishingSet.add(oid);\n } catch (err) {\n }\n }\n const visited = /* @__PURE__ */ new Set();\n async function walk2(oid) {\n visited.add(oid);\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type === \"tag\") {\n const tag2 = GitAnnotatedTag.from(object);\n const commit2 = tag2.headers().object;\n return walk2(commit2);\n }\n if (type !== \"commit\") {\n throw new ObjectTypeError(oid, type, \"commit\");\n }\n if (!shallows.has(oid)) {\n const commit2 = GitCommit.from(object);\n const parents = commit2.headers().parent;\n for (oid of parents) {\n if (!finishingSet.has(oid) && !visited.has(oid)) {\n await walk2(oid);\n }\n }\n }\n }\n for (const oid of startingSet) {\n await walk2(oid);\n }\n return visited;\n}\nasync function listObjects({\n fs,\n cache,\n dir,\n gitdir = join2(dir, \".git\"),\n oids\n}) {\n const visited = /* @__PURE__ */ new Set();\n async function walk2(oid) {\n if (visited.has(oid)) return;\n visited.add(oid);\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type === \"tag\") {\n const tag2 = GitAnnotatedTag.from(object);\n const obj = tag2.headers().object;\n await walk2(obj);\n } else if (type === \"commit\") {\n const commit2 = GitCommit.from(object);\n const tree = commit2.headers().tree;\n await walk2(tree);\n } else if (type === \"tree\") {\n const tree = GitTree.from(object);\n for (const entry of tree) {\n if (entry.type === \"blob\") {\n visited.add(entry.oid);\n }\n if (entry.type === \"tree\") {\n await walk2(entry.oid);\n }\n }\n }\n }\n for (const oid of oids) {\n await walk2(oid);\n }\n return visited;\n}\nasync function parseReceivePackResponse(packfile) {\n const result = {};\n let response = \"\";\n const read = GitPktLine.streamReader(packfile);\n let line = await read();\n while (line !== true) {\n if (line !== null) response += line.toString(\"utf8\") + \"\\n\";\n line = await read();\n }\n const lines = response.toString(\"utf8\").split(\"\\n\");\n line = lines.shift();\n if (!line.startsWith(\"unpack \")) {\n throw new ParseError('unpack ok\" or \"unpack [error message]', line);\n }\n result.ok = line === \"unpack ok\";\n if (!result.ok) {\n result.error = line.slice(\"unpack \".length);\n }\n result.refs = {};\n for (const line2 of lines) {\n if (line2.trim() === \"\") continue;\n const status2 = line2.slice(0, 2);\n const refAndMessage = line2.slice(3);\n let space = refAndMessage.indexOf(\" \");\n if (space === -1) space = refAndMessage.length;\n const ref = refAndMessage.slice(0, space);\n const error = refAndMessage.slice(space + 1);\n result.refs[ref] = {\n ok: status2 === \"ok\",\n error\n };\n }\n return result;\n}\nasync function writeReceivePackRequest({\n capabilities = [],\n triplets = []\n}) {\n const packstream = [];\n let capsFirstLine = `\\0 ${capabilities.join(\" \")}`;\n for (const trip of triplets) {\n packstream.push(\n GitPktLine.encode(\n `${trip.oldoid} ${trip.oid} ${trip.fullRef}${capsFirstLine}\n`\n )\n );\n capsFirstLine = \"\";\n }\n packstream.push(GitPktLine.flush());\n return packstream;\n}\nasync function _push({\n fs,\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n onPrePush,\n gitdir,\n ref: _ref,\n remoteRef: _remoteRef,\n remote,\n url: _url,\n force = false,\n delete: _delete = false,\n corsProxy,\n headers = {}\n}) {\n const ref = _ref || await _currentBranch({ fs, gitdir });\n if (typeof ref === \"undefined\") {\n throw new MissingParameterError(\"ref\");\n }\n const config = await GitConfigManager.get({ fs, gitdir });\n remote = remote || await config.get(`branch.${ref}.pushRemote`) || await config.get(\"remote.pushDefault\") || await config.get(`branch.${ref}.remote`) || \"origin\";\n const url = _url || await config.get(`remote.${remote}.pushurl`) || await config.get(`remote.${remote}.url`);\n if (typeof url === \"undefined\") {\n throw new MissingParameterError(\"remote OR url\");\n }\n const remoteRef = _remoteRef || await config.get(`branch.${ref}.merge`);\n if (typeof url === \"undefined\") {\n throw new MissingParameterError(\"remoteRef\");\n }\n if (corsProxy === void 0) {\n corsProxy = await config.get(\"http.corsProxy\");\n }\n const fullRef = await GitRefManager.expand({ fs, gitdir, ref });\n const oid = _delete ? \"0000000000000000000000000000000000000000\" : await GitRefManager.resolve({ fs, gitdir, ref: fullRef });\n const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });\n const httpRemote = await GitRemoteHTTP2.discover({\n http,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n corsProxy,\n service: \"git-receive-pack\",\n url,\n headers,\n protocolVersion: 1\n });\n const auth = httpRemote.auth;\n let fullRemoteRef;\n if (!remoteRef) {\n fullRemoteRef = fullRef;\n } else {\n try {\n fullRemoteRef = await GitRefManager.expandAgainstMap({\n ref: remoteRef,\n map: httpRemote.refs\n });\n } catch (err) {\n if (err instanceof NotFoundError) {\n fullRemoteRef = remoteRef.startsWith(\"refs/\") ? remoteRef : `refs/heads/${remoteRef}`;\n } else {\n throw err;\n }\n }\n }\n const oldoid = httpRemote.refs.get(fullRemoteRef) || \"0000000000000000000000000000000000000000\";\n if (onPrePush) {\n const hookCancel = await onPrePush({\n remote,\n url,\n localRef: { ref: _delete ? \"(delete)\" : fullRef, oid },\n remoteRef: { ref: fullRemoteRef, oid: oldoid }\n });\n if (!hookCancel) throw new UserCanceledError();\n }\n const thinPack = !httpRemote.capabilities.has(\"no-thin\");\n let objects = /* @__PURE__ */ new Set();\n if (!_delete) {\n const finish = [...httpRemote.refs.values()];\n let skipObjects = /* @__PURE__ */ new Set();\n if (oldoid !== \"0000000000000000000000000000000000000000\") {\n const mergebase = await _findMergeBase({\n fs,\n cache,\n gitdir,\n oids: [oid, oldoid]\n });\n for (const oid2 of mergebase) finish.push(oid2);\n if (thinPack) {\n skipObjects = await listObjects({ fs, cache, gitdir, oids: mergebase });\n }\n }\n if (!finish.includes(oid)) {\n const commits = await listCommitsAndTags({\n fs,\n cache,\n gitdir,\n start: [oid],\n finish\n });\n objects = await listObjects({ fs, cache, gitdir, oids: commits });\n }\n if (thinPack) {\n try {\n const ref2 = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: `refs/remotes/${remote}/HEAD`,\n depth: 2\n });\n const { oid: oid2 } = await GitRefManager.resolveAgainstMap({\n ref: ref2.replace(`refs/remotes/${remote}/`, \"\"),\n fullref: ref2,\n map: httpRemote.refs\n });\n const oids = [oid2];\n for (const oid3 of await listObjects({ fs, cache, gitdir, oids })) {\n skipObjects.add(oid3);\n }\n } catch (e) {\n }\n for (const oid2 of skipObjects) {\n objects.delete(oid2);\n }\n }\n if (oid === oldoid) force = true;\n if (!force) {\n if (fullRef.startsWith(\"refs/tags\") && oldoid !== \"0000000000000000000000000000000000000000\") {\n throw new PushRejectedError(\"tag-exists\");\n }\n if (oid !== \"0000000000000000000000000000000000000000\" && oldoid !== \"0000000000000000000000000000000000000000\" && !await _isDescendent({\n fs,\n cache,\n gitdir,\n oid,\n ancestor: oldoid,\n depth: -1\n })) {\n throw new PushRejectedError(\"not-fast-forward\");\n }\n }\n }\n const capabilities = filterCapabilities(\n [...httpRemote.capabilities],\n [\"report-status\", \"side-band-64k\", `agent=${pkg.agent}`]\n );\n const packstream1 = await writeReceivePackRequest({\n capabilities,\n triplets: [{ oldoid, oid, fullRef: fullRemoteRef }]\n });\n const packstream2 = _delete ? [] : await _pack({\n fs,\n cache,\n gitdir,\n oids: [...objects]\n });\n const res = await GitRemoteHTTP2.connect({\n http,\n onProgress,\n corsProxy,\n service: \"git-receive-pack\",\n url,\n auth,\n headers,\n body: [...packstream1, ...packstream2]\n });\n const { packfile, progress } = await GitSideBand.demux(res.body);\n if (onMessage) {\n const lines = splitLines(progress);\n forAwait(lines, async (line) => {\n await onMessage(line);\n });\n }\n const result = await parseReceivePackResponse(packfile);\n if (res.headers) {\n result.headers = res.headers;\n }\n if (remote && result.ok && result.refs[fullRemoteRef].ok && !fullRef.startsWith(\"refs/tags\")) {\n const ref2 = `refs/remotes/${remote}/${fullRemoteRef.replace(\n \"refs/heads\",\n \"\"\n )}`;\n if (_delete) {\n await GitRefManager.deleteRef({ fs, gitdir, ref: ref2 });\n } else {\n await GitRefManager.writeRef({ fs, gitdir, ref: ref2, value: oid });\n }\n }\n if (result.ok && Object.values(result.refs).every((result2) => result2.ok)) {\n return result;\n } else {\n const prettyDetails = Object.entries(result.refs).filter(([k, v]) => !v.ok).map(([k, v]) => `\n - ${k}: ${v.error}`).join(\"\");\n throw new GitPushError(prettyDetails, result);\n }\n}\nasync function push({\n fs,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n onPrePush,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n remoteRef,\n remote = \"origin\",\n url,\n force = false,\n delete: _delete = false,\n corsProxy,\n headers = {},\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"http\", http);\n assertParameter(\"gitdir\", gitdir);\n return await _push({\n fs: new FileSystem(fs),\n cache,\n http,\n onProgress,\n onMessage,\n onAuth,\n onAuthSuccess,\n onAuthFailure,\n onPrePush,\n gitdir,\n ref,\n remoteRef,\n remote,\n url,\n force,\n delete: _delete,\n corsProxy,\n headers\n });\n } catch (err) {\n err.caller = \"git.push\";\n throw err;\n }\n}\nasync function resolveBlob({ fs, cache, gitdir, oid }) {\n const { type, object } = await _readObject({ fs, cache, gitdir, oid });\n if (type === \"tag\") {\n oid = GitAnnotatedTag.from(object).parse().object;\n return resolveBlob({ fs, cache, gitdir, oid });\n }\n if (type !== \"blob\") {\n throw new ObjectTypeError(oid, type, \"blob\");\n }\n return { oid, blob: new Uint8Array(object) };\n}\nasync function _readBlob({\n fs,\n cache,\n gitdir,\n oid,\n filepath = void 0\n}) {\n if (filepath !== void 0) {\n oid = await resolveFilepath({ fs, cache, gitdir, oid, filepath });\n }\n const blob = await resolveBlob({\n fs,\n cache,\n gitdir,\n oid\n });\n return blob;\n}\nasync function readBlob({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oid,\n filepath,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n return await _readBlob({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oid,\n filepath\n });\n } catch (err) {\n err.caller = \"git.readBlob\";\n throw err;\n }\n}\nasync function readCommit({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oid,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n return await _readCommit({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oid\n });\n } catch (err) {\n err.caller = \"git.readCommit\";\n throw err;\n }\n}\nasync function _readNote({\n fs,\n cache,\n gitdir,\n ref = \"refs/notes/commits\",\n oid\n}) {\n const parent = await GitRefManager.resolve({ gitdir, fs, ref });\n const { blob } = await _readBlob({\n fs,\n cache,\n gitdir,\n oid: parent,\n filepath: oid\n });\n return blob;\n}\nasync function readNote({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref = \"refs/notes/commits\",\n oid,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n assertParameter(\"oid\", oid);\n return await _readNote({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n ref,\n oid\n });\n } catch (err) {\n err.caller = \"git.readNote\";\n throw err;\n }\n}\nasync function readObject({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oid,\n format = \"parsed\",\n filepath = void 0,\n encoding = void 0,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n const fs = new FileSystem(_fs);\n if (filepath !== void 0) {\n oid = await resolveFilepath({\n fs,\n cache,\n gitdir,\n oid,\n filepath\n });\n }\n const _format = format === \"parsed\" ? \"content\" : format;\n const result = await _readObject({\n fs,\n cache,\n gitdir,\n oid,\n format: _format\n });\n result.oid = oid;\n if (format === \"parsed\") {\n result.format = \"parsed\";\n switch (result.type) {\n case \"commit\":\n result.object = GitCommit.from(result.object).parse();\n break;\n case \"tree\":\n result.object = GitTree.from(result.object).entries();\n break;\n case \"blob\":\n if (encoding) {\n result.object = result.object.toString(encoding);\n } else {\n result.object = new Uint8Array(result.object);\n result.format = \"content\";\n }\n break;\n case \"tag\":\n result.object = GitAnnotatedTag.from(result.object).parse();\n break;\n default:\n throw new ObjectTypeError(\n result.oid,\n result.type,\n \"blob|commit|tag|tree\"\n );\n }\n } else if (result.format === \"deflated\" || result.format === \"wrapped\") {\n result.type = result.format;\n }\n return result;\n } catch (err) {\n err.caller = \"git.readObject\";\n throw err;\n }\n}\nasync function _readTag({ fs, cache, gitdir, oid }) {\n const { type, object } = await _readObject({\n fs,\n cache,\n gitdir,\n oid,\n format: \"content\"\n });\n if (type !== \"tag\") {\n throw new ObjectTypeError(oid, type, \"tag\");\n }\n const tag2 = GitAnnotatedTag.from(object);\n const result = {\n oid,\n tag: tag2.parse(),\n payload: tag2.payload()\n };\n return result;\n}\nasync function readTag({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oid,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n return await _readTag({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oid\n });\n } catch (err) {\n err.caller = \"git.readTag\";\n throw err;\n }\n}\nasync function readTree({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n oid,\n filepath = void 0,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n return await _readTree({\n fs: new FileSystem(fs),\n cache,\n gitdir,\n oid,\n filepath\n });\n } catch (err) {\n err.caller = \"git.readTree\";\n throw err;\n }\n}\nasync function remove({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"filepath\", filepath);\n await GitIndexManager.acquire(\n { fs: new FileSystem(_fs), gitdir, cache },\n async function(index3) {\n index3.delete({ filepath });\n }\n );\n } catch (err) {\n err.caller = \"git.remove\";\n throw err;\n }\n}\nasync function _removeNote({\n fs,\n cache,\n onSign,\n gitdir,\n ref = \"refs/notes/commits\",\n oid,\n author,\n committer,\n signingKey\n}) {\n let parent;\n try {\n parent = await GitRefManager.resolve({ gitdir, fs, ref });\n } catch (err) {\n if (!(err instanceof NotFoundError)) {\n throw err;\n }\n }\n const result = await _readTree({\n fs,\n gitdir,\n oid: parent || \"4b825dc642cb6eb9a060e54bf8d69288fbee4904\"\n });\n let tree = result.tree;\n tree = tree.filter((entry) => entry.path !== oid);\n const treeOid = await _writeTree({\n fs,\n gitdir,\n tree\n });\n const commitOid = await _commit({\n fs,\n cache,\n onSign,\n gitdir,\n ref,\n tree: treeOid,\n parent: parent && [parent],\n message: `Note removed by 'isomorphic-git removeNote'\n`,\n author,\n committer,\n signingKey\n });\n return commitOid;\n}\nasync function removeNote({\n fs: _fs,\n onSign,\n dir,\n gitdir = join2(dir, \".git\"),\n ref = \"refs/notes/commits\",\n oid,\n author: _author,\n committer: _committer,\n signingKey,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"oid\", oid);\n const fs = new FileSystem(_fs);\n const author = await normalizeAuthorObject({ fs, gitdir, author: _author });\n if (!author) throw new MissingNameError(\"author\");\n const committer = await normalizeCommitterObject({\n fs,\n gitdir,\n author,\n committer: _committer\n });\n if (!committer) throw new MissingNameError(\"committer\");\n return await _removeNote({\n fs,\n cache,\n onSign,\n gitdir,\n ref,\n oid,\n author,\n committer,\n signingKey\n });\n } catch (err) {\n err.caller = \"git.removeNote\";\n throw err;\n }\n}\nasync function _renameBranch({\n fs,\n gitdir,\n oldref,\n ref,\n checkout: checkout2 = false\n}) {\n if (!(0, import_is_git_ref_name_valid.default)(ref, true)) {\n throw new InvalidRefNameError(ref, import_clean_git_ref.default.clean(ref));\n }\n if (!(0, import_is_git_ref_name_valid.default)(oldref, true)) {\n throw new InvalidRefNameError(oldref, import_clean_git_ref.default.clean(oldref));\n }\n const fulloldref = `refs/heads/${oldref}`;\n const fullnewref = `refs/heads/${ref}`;\n const newexist = await GitRefManager.exists({ fs, gitdir, ref: fullnewref });\n if (newexist) {\n throw new AlreadyExistsError(\"branch\", ref, false);\n }\n const value = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: fulloldref,\n depth: 1\n });\n await GitRefManager.writeRef({ fs, gitdir, ref: fullnewref, value });\n await GitRefManager.deleteRef({ fs, gitdir, ref: fulloldref });\n const fullCurrentBranchRef = await _currentBranch({\n fs,\n gitdir,\n fullname: true\n });\n const isCurrentBranch = fullCurrentBranchRef === fulloldref;\n if (checkout2 || isCurrentBranch) {\n await GitRefManager.writeSymbolicRef({\n fs,\n gitdir,\n ref: \"HEAD\",\n value: fullnewref\n });\n }\n}\nasync function renameBranch({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n oldref,\n checkout: checkout2 = false\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n assertParameter(\"oldref\", oldref);\n return await _renameBranch({\n fs: new FileSystem(fs),\n gitdir,\n ref,\n oldref,\n checkout: checkout2\n });\n } catch (err) {\n err.caller = \"git.renameBranch\";\n throw err;\n }\n}\nasync function hashObject$1({ gitdir, type, object }) {\n return shasum(GitObject.wrap({ type, object }));\n}\nasync function resetIndex({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath,\n ref,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"filepath\", filepath);\n const fs = new FileSystem(_fs);\n let oid;\n let workdirOid;\n try {\n oid = await GitRefManager.resolve({ fs, gitdir, ref: ref || \"HEAD\" });\n } catch (e) {\n if (ref) {\n throw e;\n }\n }\n if (oid) {\n try {\n oid = await resolveFilepath({\n fs,\n cache,\n gitdir,\n oid,\n filepath\n });\n } catch (e) {\n oid = null;\n }\n }\n let stats = {\n ctime: /* @__PURE__ */ new Date(0),\n mtime: /* @__PURE__ */ new Date(0),\n dev: 0,\n ino: 0,\n mode: 0,\n uid: 0,\n gid: 0,\n size: 0\n };\n const object = dir && await fs.read(join2(dir, filepath));\n if (object) {\n workdirOid = await hashObject$1({\n gitdir,\n type: \"blob\",\n object\n });\n if (oid === workdirOid) {\n stats = await fs.lstat(join2(dir, filepath));\n }\n }\n await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n index3.delete({ filepath });\n if (oid) {\n index3.insert({ filepath, stats, oid });\n }\n });\n } catch (err) {\n err.caller = \"git.reset\";\n throw err;\n }\n}\nasync function resolveRef({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n depth\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n const oid = await GitRefManager.resolve({\n fs: new FileSystem(fs),\n gitdir,\n ref,\n depth\n });\n return oid;\n } catch (err) {\n err.caller = \"git.resolveRef\";\n throw err;\n }\n}\nasync function setConfig({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n path,\n value,\n append = false\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"path\", path);\n const fs = new FileSystem(_fs);\n const config = await GitConfigManager.get({ fs, gitdir });\n if (append) {\n await config.append(path, value);\n } else {\n await config.set(path, value);\n }\n await GitConfigManager.save({ fs, gitdir, config });\n } catch (err) {\n err.caller = \"git.setConfig\";\n throw err;\n }\n}\nasync function _writeCommit({ fs, gitdir, commit: commit2 }) {\n const object = GitCommit.from(commit2).toObject();\n const oid = await _writeObject({\n fs,\n gitdir,\n type: \"commit\",\n object,\n format: \"content\"\n });\n return oid;\n}\nvar GitRefStash = class _GitRefStash {\n // constructor removed\n static get timezoneOffsetForRefLogEntry() {\n const offsetMinutes = (/* @__PURE__ */ new Date()).getTimezoneOffset();\n const offsetHours = Math.abs(Math.floor(offsetMinutes / 60));\n const offsetMinutesFormatted = Math.abs(offsetMinutes % 60).toString().padStart(2, \"0\");\n const sign = offsetMinutes > 0 ? \"-\" : \"+\";\n return `${sign}${offsetHours.toString().padStart(2, \"0\")}${offsetMinutesFormatted}`;\n }\n static createStashReflogEntry(author, stashCommit, message) {\n const nameNoSpace = author.name.replace(/\\s/g, \"\");\n const z40 = \"0000000000000000000000000000000000000000\";\n const timestamp = Math.floor(Date.now() / 1e3);\n const timezoneOffset = _GitRefStash.timezoneOffsetForRefLogEntry;\n return `${z40} ${stashCommit} ${nameNoSpace} ${author.email} ${timestamp} ${timezoneOffset}\t${message}\n`;\n }\n static getStashReflogEntry(reflogString, parsed = false) {\n const reflogLines = reflogString.split(\"\\n\");\n const entries = reflogLines.filter((l) => l).reverse().map(\n (line, idx) => parsed ? `stash@{${idx}}: ${line.split(\"\t\")[1]}` : line\n );\n return entries;\n }\n};\nvar _TreeMap = {\n stage: STAGE,\n workdir: WORKDIR\n};\nvar lock$3;\nasync function acquireLock$1(ref, callback) {\n if (lock$3 === void 0) lock$3 = new AsyncLock();\n return lock$3.run(ref, callback);\n}\nasync function checkAndWriteBlob(fs, gitdir, dir, filepath, oid = null) {\n const currentFilepath = join2(dir, filepath);\n const stats = await fs.lstat(currentFilepath);\n if (!stats) throw new NotFoundError(currentFilepath);\n if (stats.isDirectory())\n throw new InternalError(\n `${currentFilepath}: file expected, but found directory`\n );\n const objContent = oid ? await readObjectLoose({ fs, gitdir, oid }) : void 0;\n let retOid = objContent ? oid : void 0;\n if (!objContent) {\n await acquireLock$1({ fs, gitdir, currentFilepath }, async () => {\n const object = stats.isSymbolicLink() ? await fs.readlink(currentFilepath).then(posixifyPathBuffer) : await fs.read(currentFilepath);\n if (object === null) throw new NotFoundError(currentFilepath);\n retOid = await _writeObject({ fs, gitdir, type: \"blob\", object });\n });\n }\n return retOid;\n}\nasync function processTreeEntries({ fs, dir, gitdir, entries }) {\n async function processTreeEntry(entry) {\n if (entry.type === \"tree\") {\n if (!entry.oid) {\n const children = await Promise.all(entry.children.map(processTreeEntry));\n entry.oid = await _writeTree({\n fs,\n gitdir,\n tree: children\n });\n entry.mode = 16384;\n }\n } else if (entry.type === \"blob\") {\n entry.oid = await checkAndWriteBlob(\n fs,\n gitdir,\n dir,\n entry.path,\n entry.oid\n );\n entry.mode = 33188;\n }\n entry.path = entry.path.split(\"/\").pop();\n return entry;\n }\n return Promise.all(entries.map(processTreeEntry));\n}\nasync function writeTreeChanges({\n fs,\n dir,\n gitdir,\n treePair\n // [TREE({ ref: 'HEAD' }), 'STAGE'] would be the equivalent of `git write-tree`\n}) {\n const isStage = treePair[1] === \"stage\";\n const trees = treePair.map((t) => typeof t === \"string\" ? _TreeMap[t]() : t);\n const changedEntries = [];\n const map = async (filepath, [head, stage]) => {\n if (filepath === \".\" || await GitIgnoreManager.isIgnored({ fs, dir, gitdir, filepath })) {\n return;\n }\n if (stage) {\n if (!head || await head.oid() !== await stage.oid() && await stage.oid() !== void 0) {\n changedEntries.push([head, stage]);\n }\n return {\n mode: await stage.mode(),\n path: filepath,\n oid: await stage.oid(),\n type: await stage.type()\n };\n }\n };\n const reduce = async (parent, children) => {\n children = children.filter(Boolean);\n if (!parent) {\n return children.length > 0 ? children : void 0;\n } else {\n parent.children = children;\n return parent;\n }\n };\n const iterate = async (walk2, children) => {\n const filtered = [];\n for (const child of children) {\n const [head, stage] = child;\n if (isStage) {\n if (stage) {\n if (await fs.exists(`${dir}/${stage.toString()}`)) {\n filtered.push(child);\n } else {\n changedEntries.push([null, stage]);\n }\n }\n } else if (head) {\n if (!stage) {\n changedEntries.push([head, null]);\n } else {\n filtered.push(child);\n }\n }\n }\n return filtered.length ? Promise.all(filtered.map(walk2)) : [];\n };\n const entries = await _walk({\n fs,\n cache: {},\n dir,\n gitdir,\n trees,\n map,\n reduce,\n iterate\n });\n if (changedEntries.length === 0 || entries.length === 0) {\n return null;\n }\n const processedEntries = await processTreeEntries({\n fs,\n dir,\n gitdir,\n entries\n });\n const treeEntries = processedEntries.filter(Boolean).map((entry) => ({\n mode: entry.mode,\n path: entry.path,\n oid: entry.oid,\n type: entry.type\n }));\n return _writeTree({ fs, gitdir, tree: treeEntries });\n}\nasync function applyTreeChanges({\n fs,\n dir,\n gitdir,\n stashCommit,\n parentCommit,\n wasStaged\n}) {\n const dirRemoved = [];\n const stageUpdated = [];\n const ops = await _walk({\n fs,\n cache: {},\n dir,\n gitdir,\n trees: [TREE({ ref: parentCommit }), TREE({ ref: stashCommit })],\n map: async (filepath, [parent, stash2]) => {\n if (filepath === \".\" || await GitIgnoreManager.isIgnored({ fs, dir, gitdir, filepath })) {\n return;\n }\n const type = stash2 ? await stash2.type() : await parent.type();\n if (type !== \"tree\" && type !== \"blob\") {\n return;\n }\n if (!stash2 && parent) {\n const method = type === \"tree\" ? \"rmdir\" : \"rm\";\n if (type === \"tree\") dirRemoved.push(filepath);\n if (type === \"blob\" && wasStaged)\n stageUpdated.push({ filepath, oid: await parent.oid() });\n return { method, filepath };\n }\n const oid = await stash2.oid();\n if (!parent || await parent.oid() !== oid) {\n if (type === \"tree\") {\n return { method: \"mkdir\", filepath };\n } else {\n if (wasStaged)\n stageUpdated.push({\n filepath,\n oid,\n stats: await fs.lstat(join2(dir, filepath))\n });\n return {\n method: \"write\",\n filepath,\n oid\n };\n }\n }\n }\n });\n await acquireLock$1({ fs, gitdir, dirRemoved, ops }, async () => {\n for (const op of ops) {\n const currentFilepath = join2(dir, op.filepath);\n switch (op.method) {\n case \"rmdir\":\n await fs.rmdir(currentFilepath);\n break;\n case \"mkdir\":\n await fs.mkdir(currentFilepath);\n break;\n case \"rm\":\n await fs.rm(currentFilepath);\n break;\n case \"write\":\n if (!dirRemoved.some(\n (removedDir) => currentFilepath.startsWith(removedDir)\n )) {\n const { object } = await _readObject({\n fs,\n cache: {},\n gitdir,\n oid: op.oid\n });\n if (await fs.exists(currentFilepath)) {\n await fs.rm(currentFilepath);\n }\n await fs.write(currentFilepath, object);\n }\n break;\n }\n }\n });\n await GitIndexManager.acquire({ fs, gitdir, cache: {} }, async (index3) => {\n stageUpdated.forEach(({ filepath, stats, oid }) => {\n index3.insert({ filepath, stats, oid });\n });\n });\n}\nvar GitStashManager = class _GitStashManager {\n /**\n * Creates an instance of GitStashManager.\n *\n * @param {Object} args\n * @param {FSClient} args.fs - A file system implementation.\n * @param {string} args.dir - The working directory.\n * @param {string}[args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path\n */\n constructor({ fs, dir, gitdir = join2(dir, \".git\") }) {\n Object.assign(this, {\n fs,\n dir,\n gitdir,\n _author: null\n });\n }\n /**\n * Gets the reference name for the stash.\n *\n * @returns {string} - The stash reference name.\n */\n static get refStash() {\n return \"refs/stash\";\n }\n /**\n * Gets the reference name for the stash reflogs.\n *\n * @returns {string} - The stash reflogs reference name.\n */\n static get refLogsStash() {\n return \"logs/refs/stash\";\n }\n /**\n * Gets the file path for the stash reference.\n *\n * @returns {string} - The file path for the stash reference.\n */\n get refStashPath() {\n return join2(this.gitdir, _GitStashManager.refStash);\n }\n /**\n * Gets the file path for the stash reflogs.\n *\n * @returns {string} - The file path for the stash reflogs.\n */\n get refLogsStashPath() {\n return join2(this.gitdir, _GitStashManager.refLogsStash);\n }\n /**\n * Retrieves the author information for the stash.\n *\n * @returns {Promise<Object>} - The author object.\n * @throws {MissingNameError} - If the author name is missing.\n */\n async getAuthor() {\n if (!this._author) {\n this._author = await normalizeAuthorObject({\n fs: this.fs,\n gitdir: this.gitdir,\n author: {}\n });\n if (!this._author) throw new MissingNameError(\"author\");\n }\n return this._author;\n }\n /**\n * Gets the SHA of a stash entry by its index.\n *\n * @param {number} refIdx - The index of the stash entry.\n * @param {string[]} [stashEntries] - Optional preloaded stash entries.\n * @returns {Promise<string|null>} - The SHA of the stash entry or `null` if not found.\n */\n async getStashSHA(refIdx, stashEntries) {\n if (!await this.fs.exists(this.refStashPath)) {\n return null;\n }\n const entries = stashEntries || await this.readStashReflogs({ parsed: false });\n return entries[refIdx].split(\" \")[1];\n }\n /**\n * Writes a stash commit to the repository.\n *\n * @param {Object} args\n * @param {string} args.message - The commit message.\n * @param {string} args.tree - The tree object ID.\n * @param {string[]} args.parent - The parent commit object IDs.\n * @returns {Promise<string>} - The object ID of the written commit.\n */\n async writeStashCommit({ message, tree, parent }) {\n return _writeCommit({\n fs: this.fs,\n gitdir: this.gitdir,\n commit: {\n message,\n tree,\n parent,\n author: await this.getAuthor(),\n committer: await this.getAuthor()\n }\n });\n }\n /**\n * Reads a stash commit by its index.\n *\n * @param {number} refIdx - The index of the stash entry.\n * @returns {Promise<Object>} - The stash commit object.\n * @throws {InvalidRefNameError} - If the index is invalid.\n */\n async readStashCommit(refIdx) {\n const stashEntries = await this.readStashReflogs({ parsed: false });\n if (refIdx !== 0) {\n if (refIdx < 0 || refIdx > stashEntries.length - 1) {\n throw new InvalidRefNameError(\n `stash@${refIdx}`,\n \"number that is in range of [0, num of stash pushed]\"\n );\n }\n }\n const stashSHA = await this.getStashSHA(refIdx, stashEntries);\n if (!stashSHA) {\n return {};\n }\n return _readCommit({\n fs: this.fs,\n cache: {},\n gitdir: this.gitdir,\n oid: stashSHA\n });\n }\n /**\n * Writes a stash reference to the repository.\n *\n * @param {string} stashCommit - The object ID of the stash commit.\n * @returns {Promise<void>}\n */\n async writeStashRef(stashCommit) {\n return GitRefManager.writeRef({\n fs: this.fs,\n gitdir: this.gitdir,\n ref: _GitStashManager.refStash,\n value: stashCommit\n });\n }\n /**\n * Writes a reflog entry for a stash commit.\n *\n * @param {Object} args\n * @param {string} args.stashCommit - The object ID of the stash commit.\n * @param {string} args.message - The reflog message.\n * @returns {Promise<void>}\n */\n async writeStashReflogEntry({ stashCommit, message }) {\n const author = await this.getAuthor();\n const entry = GitRefStash.createStashReflogEntry(\n author,\n stashCommit,\n message\n );\n const filepath = this.refLogsStashPath;\n await acquireLock$1({ filepath, entry }, async () => {\n const appendTo = await this.fs.exists(filepath) ? await this.fs.read(filepath, \"utf8\") : \"\";\n await this.fs.write(filepath, appendTo + entry, \"utf8\");\n });\n }\n /**\n * Reads the stash reflogs.\n *\n * @param {Object} args\n * @param {boolean} [args.parsed=false] - Whether to parse the reflog entries.\n * @returns {Promise<string[]|Object[]>} - The reflog entries as strings or parsed objects.\n */\n async readStashReflogs({ parsed = false }) {\n if (!await this.fs.exists(this.refLogsStashPath)) {\n return [];\n }\n const reflogString = await this.fs.read(this.refLogsStashPath, \"utf8\");\n return GitRefStash.getStashReflogEntry(reflogString, parsed);\n }\n};\nasync function _createStashCommit({ fs, dir, gitdir, message = \"\" }) {\n const stashMgr = new GitStashManager({ fs, dir, gitdir });\n await stashMgr.getAuthor();\n const branch2 = await _currentBranch({\n fs,\n gitdir,\n fullname: false\n });\n const headCommit = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: \"HEAD\"\n });\n const headCommitObj = await readCommit({ fs, dir, gitdir, oid: headCommit });\n const headMsg = headCommitObj.commit.message;\n const stashCommitParents = [headCommit];\n let stashCommitTree = null;\n let workDirCompareBase = TREE({ ref: \"HEAD\" });\n const indexTree = await writeTreeChanges({\n fs,\n dir,\n gitdir,\n treePair: [TREE({ ref: \"HEAD\" }), \"stage\"]\n });\n if (indexTree) {\n const stashCommitOne = await stashMgr.writeStashCommit({\n message: `stash-Index: WIP on ${branch2} - ${(/* @__PURE__ */ new Date()).toISOString()}`,\n tree: indexTree,\n parent: stashCommitParents\n });\n stashCommitParents.push(stashCommitOne);\n stashCommitTree = indexTree;\n workDirCompareBase = STAGE();\n }\n const workingTree = await writeTreeChanges({\n fs,\n dir,\n gitdir,\n treePair: [workDirCompareBase, \"workdir\"]\n });\n if (workingTree) {\n const workingHeadCommit = await stashMgr.writeStashCommit({\n message: `stash-WorkDir: WIP on ${branch2} - ${(/* @__PURE__ */ new Date()).toISOString()}`,\n tree: workingTree,\n parent: [stashCommitParents[stashCommitParents.length - 1]]\n });\n stashCommitParents.push(workingHeadCommit);\n stashCommitTree = workingTree;\n }\n if (!stashCommitTree || !indexTree && !workingTree) {\n throw new NotFoundError(\"changes, nothing to stash\");\n }\n const stashMsg = (message.trim() || `WIP on ${branch2}`) + `: ${headCommit.substring(0, 7)} ${headMsg}`;\n const stashCommit = await stashMgr.writeStashCommit({\n message: stashMsg,\n tree: stashCommitTree,\n parent: stashCommitParents\n });\n return { stashCommit, stashMsg, branch: branch2, stashMgr };\n}\nasync function _stashPush({ fs, dir, gitdir, message = \"\" }) {\n const { stashCommit, stashMsg, branch: branch2, stashMgr } = await _createStashCommit({\n fs,\n dir,\n gitdir,\n message\n });\n await stashMgr.writeStashRef(stashCommit);\n await stashMgr.writeStashReflogEntry({\n stashCommit,\n message: stashMsg\n });\n await checkout({\n fs,\n dir,\n gitdir,\n ref: branch2,\n track: false,\n force: true\n // force checkout to discard changes\n });\n return stashCommit;\n}\nasync function _stashCreate({ fs, dir, gitdir, message = \"\" }) {\n const { stashCommit } = await _createStashCommit({\n fs,\n dir,\n gitdir,\n message\n });\n return stashCommit;\n}\nasync function _stashApply({ fs, dir, gitdir, refIdx = 0 }) {\n const stashMgr = new GitStashManager({ fs, dir, gitdir });\n const stashCommit = await stashMgr.readStashCommit(refIdx);\n const { parent: stashParents = null } = stashCommit.commit ? stashCommit.commit : {};\n if (!stashParents || !Array.isArray(stashParents)) {\n return;\n }\n for (let i = 0; i < stashParents.length - 1; i++) {\n const applyingCommit = await _readCommit({\n fs,\n cache: {},\n gitdir,\n oid: stashParents[i + 1]\n });\n const wasStaged = applyingCommit.commit.message.startsWith(\"stash-Index\");\n await applyTreeChanges({\n fs,\n dir,\n gitdir,\n stashCommit: stashParents[i + 1],\n parentCommit: stashParents[i],\n wasStaged\n });\n }\n}\nasync function _stashDrop({ fs, dir, gitdir, refIdx = 0 }) {\n const stashMgr = new GitStashManager({ fs, dir, gitdir });\n const stashCommit = await stashMgr.readStashCommit(refIdx);\n if (!stashCommit.commit) {\n return;\n }\n const stashRefPath = stashMgr.refStashPath;\n await acquireLock$1(stashRefPath, async () => {\n if (await fs.exists(stashRefPath)) {\n await fs.rm(stashRefPath);\n }\n });\n const reflogEntries = await stashMgr.readStashReflogs({ parsed: false });\n if (!reflogEntries.length) {\n return;\n }\n reflogEntries.splice(refIdx, 1);\n const stashReflogPath = stashMgr.refLogsStashPath;\n await acquireLock$1({ reflogEntries, stashReflogPath, stashMgr }, async () => {\n if (reflogEntries.length) {\n await fs.write(\n stashReflogPath,\n reflogEntries.reverse().join(\"\\n\") + \"\\n\",\n \"utf8\"\n );\n const lastStashCommit = reflogEntries[reflogEntries.length - 1].split(\n \" \"\n )[1];\n await stashMgr.writeStashRef(lastStashCommit);\n } else {\n await fs.rm(stashReflogPath);\n }\n });\n}\nasync function _stashList({ fs, dir, gitdir }) {\n const stashMgr = new GitStashManager({ fs, dir, gitdir });\n return stashMgr.readStashReflogs({ parsed: true });\n}\nasync function _stashClear({ fs, dir, gitdir }) {\n const stashMgr = new GitStashManager({ fs, dir, gitdir });\n const stashRefPath = [stashMgr.refStashPath, stashMgr.refLogsStashPath];\n await acquireLock$1(stashRefPath, async () => {\n await Promise.all(\n stashRefPath.map(async (path) => {\n if (await fs.exists(path)) {\n return fs.rm(path);\n }\n })\n );\n });\n}\nasync function _stashPop({ fs, dir, gitdir, refIdx = 0 }) {\n await _stashApply({ fs, dir, gitdir, refIdx });\n await _stashDrop({ fs, dir, gitdir, refIdx });\n}\nasync function stash({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n op = \"push\",\n message = \"\",\n refIdx = 0\n}) {\n assertParameter(\"fs\", fs);\n assertParameter(\"dir\", dir);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"op\", op);\n const stashMap = {\n push: _stashPush,\n apply: _stashApply,\n drop: _stashDrop,\n list: _stashList,\n clear: _stashClear,\n pop: _stashPop,\n create: _stashCreate\n };\n const opsNeedRefIdx = [\"apply\", \"drop\", \"pop\"];\n try {\n const _fs = new FileSystem(fs);\n const folders = [\"refs\", \"logs\", \"logs/refs\"];\n folders.map((f) => join2(gitdir, f)).forEach(async (folder) => {\n if (!await _fs.exists(folder)) {\n await _fs.mkdir(folder);\n }\n });\n const opFunc = stashMap[op];\n if (opFunc) {\n if (opsNeedRefIdx.includes(op) && refIdx < 0) {\n throw new InvalidRefNameError(\n `stash@${refIdx}`,\n \"number that is in range of [0, num of stash pushed]\"\n );\n }\n return await opFunc({ fs: _fs, dir, gitdir, message, refIdx });\n }\n throw new Error(`To be implemented: ${op}`);\n } catch (err) {\n err.caller = \"git.stash\";\n throw err;\n }\n}\nasync function status({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n filepath,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"filepath\", filepath);\n const fs = new FileSystem(_fs);\n const ignored = await GitIgnoreManager.isIgnored({\n fs,\n gitdir,\n dir,\n filepath\n });\n if (ignored) {\n return \"ignored\";\n }\n const headTree = await getHeadTree({ fs, cache, gitdir });\n const treeOid = await getOidAtPath({\n fs,\n cache,\n gitdir,\n tree: headTree,\n path: filepath\n });\n const indexEntry = await GitIndexManager.acquire(\n { fs, gitdir, cache },\n async function(index3) {\n for (const entry of index3) {\n if (entry.path === filepath) return entry;\n }\n return null;\n }\n );\n const stats = await fs.lstat(join2(dir, filepath));\n const H = treeOid !== null;\n const I = indexEntry !== null;\n const W = stats !== null;\n const getWorkdirOid = async () => {\n if (I && !compareStats(indexEntry, stats)) {\n return indexEntry.oid;\n } else {\n const object = await fs.read(join2(dir, filepath));\n const workdirOid = await hashObject$1({\n gitdir,\n type: \"blob\",\n object\n });\n if (I && indexEntry.oid === workdirOid) {\n if (stats.size !== -1) {\n GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n index3.insert({ filepath, stats, oid: workdirOid });\n });\n }\n }\n return workdirOid;\n }\n };\n if (!H && !W && !I) return \"absent\";\n if (!H && !W && I) return \"*absent\";\n if (!H && W && !I) return \"*added\";\n if (!H && W && I) {\n const workdirOid = await getWorkdirOid();\n return workdirOid === indexEntry.oid ? \"added\" : \"*added\";\n }\n if (H && !W && !I) return \"deleted\";\n if (H && !W && I) {\n return treeOid === indexEntry.oid ? \"*deleted\" : \"*deleted\";\n }\n if (H && W && !I) {\n const workdirOid = await getWorkdirOid();\n return workdirOid === treeOid ? \"*undeleted\" : \"*undeletemodified\";\n }\n if (H && W && I) {\n const workdirOid = await getWorkdirOid();\n if (workdirOid === treeOid) {\n return workdirOid === indexEntry.oid ? \"unmodified\" : \"*unmodified\";\n } else {\n return workdirOid === indexEntry.oid ? \"modified\" : \"*modified\";\n }\n }\n } catch (err) {\n err.caller = \"git.status\";\n throw err;\n }\n}\nasync function getOidAtPath({ fs, cache, gitdir, tree, path }) {\n if (typeof path === \"string\") path = path.split(\"/\");\n const dirname2 = path.shift();\n for (const entry of tree) {\n if (entry.path === dirname2) {\n if (path.length === 0) {\n return entry.oid;\n }\n const { type, object } = await _readObject({\n fs,\n cache,\n gitdir,\n oid: entry.oid\n });\n if (type === \"tree\") {\n const tree2 = GitTree.from(object);\n return getOidAtPath({ fs, cache, gitdir, tree: tree2, path });\n }\n if (type === \"blob\") {\n throw new ObjectTypeError(entry.oid, type, \"blob\", path.join(\"/\"));\n }\n }\n }\n return null;\n}\nasync function getHeadTree({ fs, cache, gitdir }) {\n let oid;\n try {\n oid = await GitRefManager.resolve({ fs, gitdir, ref: \"HEAD\" });\n } catch (e) {\n if (e instanceof NotFoundError) {\n return [];\n }\n }\n const { tree } = await _readTree({ fs, cache, gitdir, oid });\n return tree;\n}\nasync function statusMatrix({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref = \"HEAD\",\n filepaths = [\".\"],\n filter,\n cache = {},\n ignored: shouldIgnore = false\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n const fs = new FileSystem(_fs);\n return await _walk({\n fs,\n cache,\n dir,\n gitdir,\n trees: [TREE({ ref }), WORKDIR(), STAGE()],\n map: async function(filepath, [head, workdir, stage]) {\n if (!head && !stage && workdir) {\n if (!shouldIgnore) {\n const isIgnored2 = await GitIgnoreManager.isIgnored({\n fs,\n dir,\n filepath\n });\n if (isIgnored2) {\n return null;\n }\n }\n }\n if (!filepaths.some((base) => worthWalking(filepath, base))) {\n return null;\n }\n if (filter) {\n if (!filter(filepath)) return;\n }\n const [headType, workdirType, stageType] = await Promise.all([\n head && head.type(),\n workdir && workdir.type(),\n stage && stage.type()\n ]);\n const isBlob = [headType, workdirType, stageType].includes(\"blob\");\n if ((headType === \"tree\" || headType === \"special\") && !isBlob) return;\n if (headType === \"commit\") return null;\n if ((workdirType === \"tree\" || workdirType === \"special\") && !isBlob)\n return;\n if (stageType === \"commit\") return null;\n if ((stageType === \"tree\" || stageType === \"special\") && !isBlob) return;\n const headOid = headType === \"blob\" ? await head.oid() : void 0;\n const stageOid = stageType === \"blob\" ? await stage.oid() : void 0;\n let workdirOid;\n if (headType !== \"blob\" && workdirType === \"blob\" && stageType !== \"blob\") {\n workdirOid = \"42\";\n } else if (workdirType === \"blob\") {\n workdirOid = await workdir.oid();\n }\n const entry = [void 0, headOid, workdirOid, stageOid];\n const result = entry.map((value) => entry.indexOf(value));\n result.shift();\n return [filepath, ...result];\n }\n });\n } catch (err) {\n err.caller = \"git.statusMatrix\";\n throw err;\n }\n}\nasync function tag({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n object,\n force = false\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n const fs = new FileSystem(_fs);\n if (ref === void 0) {\n throw new MissingParameterError(\"ref\");\n }\n ref = ref.startsWith(\"refs/tags/\") ? ref : `refs/tags/${ref}`;\n const value = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: object || \"HEAD\"\n });\n if (!force && await GitRefManager.exists({ fs, gitdir, ref })) {\n throw new AlreadyExistsError(\"tag\", ref);\n }\n await GitRefManager.writeRef({ fs, gitdir, ref, value });\n } catch (err) {\n err.caller = \"git.tag\";\n throw err;\n }\n}\nasync function updateIndex$1({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n cache = {},\n filepath,\n oid,\n mode,\n add: add2,\n remove: remove2,\n force\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"filepath\", filepath);\n const fs = new FileSystem(_fs);\n if (remove2) {\n return await GitIndexManager.acquire(\n { fs, gitdir, cache },\n async function(index3) {\n if (!force) {\n const fileStats2 = await fs.lstat(join2(dir, filepath));\n if (fileStats2) {\n if (fileStats2.isDirectory()) {\n throw new InvalidFilepathError(\"directory\");\n }\n return;\n }\n }\n if (index3.has({ filepath })) {\n index3.delete({\n filepath\n });\n }\n }\n );\n }\n let fileStats;\n if (!oid) {\n fileStats = await fs.lstat(join2(dir, filepath));\n if (!fileStats) {\n throw new NotFoundError(\n `file at \"${filepath}\" on disk and \"remove\" not set`\n );\n }\n if (fileStats.isDirectory()) {\n throw new InvalidFilepathError(\"directory\");\n }\n }\n return await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index3) {\n if (!add2 && !index3.has({ filepath })) {\n throw new NotFoundError(\n `file at \"${filepath}\" in index and \"add\" not set`\n );\n }\n let stats;\n if (!oid) {\n stats = fileStats;\n const object = stats.isSymbolicLink() ? await fs.readlink(join2(dir, filepath)) : await fs.read(join2(dir, filepath));\n oid = await _writeObject({\n fs,\n gitdir,\n type: \"blob\",\n format: \"content\",\n object\n });\n } else {\n stats = {\n ctime: /* @__PURE__ */ new Date(0),\n mtime: /* @__PURE__ */ new Date(0),\n dev: 0,\n ino: 0,\n mode,\n uid: 0,\n gid: 0,\n size: 0\n };\n }\n index3.insert({\n filepath,\n oid,\n stats\n });\n return oid;\n });\n } catch (err) {\n err.caller = \"git.updateIndex\";\n throw err;\n }\n}\nfunction version() {\n try {\n return pkg.version;\n } catch (err) {\n err.caller = \"git.version\";\n throw err;\n }\n}\nasync function walk({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n trees,\n map,\n reduce,\n iterate,\n cache = {}\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"trees\", trees);\n return await _walk({\n fs: new FileSystem(fs),\n cache,\n dir,\n gitdir,\n trees,\n map,\n reduce,\n iterate\n });\n } catch (err) {\n err.caller = \"git.walk\";\n throw err;\n }\n}\nasync function writeBlob({ fs, dir, gitdir = join2(dir, \".git\"), blob }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"blob\", blob);\n return await _writeObject({\n fs: new FileSystem(fs),\n gitdir,\n type: \"blob\",\n object: blob,\n format: \"content\"\n });\n } catch (err) {\n err.caller = \"git.writeBlob\";\n throw err;\n }\n}\nasync function writeCommit({\n fs,\n dir,\n gitdir = join2(dir, \".git\"),\n commit: commit2\n}) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"commit\", commit2);\n return await _writeCommit({\n fs: new FileSystem(fs),\n gitdir,\n commit: commit2\n });\n } catch (err) {\n err.caller = \"git.writeCommit\";\n throw err;\n }\n}\nasync function writeObject({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n type,\n object,\n format = \"parsed\",\n oid,\n encoding = void 0\n}) {\n try {\n const fs = new FileSystem(_fs);\n if (format === \"parsed\") {\n switch (type) {\n case \"commit\":\n object = GitCommit.from(object).toObject();\n break;\n case \"tree\":\n object = GitTree.from(object).toObject();\n break;\n case \"blob\":\n object = Buffer.from(object, encoding);\n break;\n case \"tag\":\n object = GitAnnotatedTag.from(object).toObject();\n break;\n default:\n throw new ObjectTypeError(oid || \"\", type, \"blob|commit|tag|tree\");\n }\n format = \"content\";\n }\n oid = await _writeObject({\n fs,\n gitdir,\n type,\n object,\n oid,\n format\n });\n return oid;\n } catch (err) {\n err.caller = \"git.writeObject\";\n throw err;\n }\n}\nasync function writeRef({\n fs: _fs,\n dir,\n gitdir = join2(dir, \".git\"),\n ref,\n value,\n force = false,\n symbolic = false\n}) {\n try {\n assertParameter(\"fs\", _fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"ref\", ref);\n assertParameter(\"value\", value);\n const fs = new FileSystem(_fs);\n if (!(0, import_is_git_ref_name_valid.default)(ref, true)) {\n throw new InvalidRefNameError(ref, import_clean_git_ref.default.clean(ref));\n }\n if (!force && await GitRefManager.exists({ fs, gitdir, ref })) {\n throw new AlreadyExistsError(\"ref\", ref);\n }\n if (symbolic) {\n await GitRefManager.writeSymbolicRef({\n fs,\n gitdir,\n ref,\n value\n });\n } else {\n value = await GitRefManager.resolve({\n fs,\n gitdir,\n ref: value\n });\n await GitRefManager.writeRef({\n fs,\n gitdir,\n ref,\n value\n });\n }\n } catch (err) {\n err.caller = \"git.writeRef\";\n throw err;\n }\n}\nasync function _writeTag({ fs, gitdir, tag: tag2 }) {\n const object = GitAnnotatedTag.from(tag2).toObject();\n const oid = await _writeObject({\n fs,\n gitdir,\n type: \"tag\",\n object,\n format: \"content\"\n });\n return oid;\n}\nasync function writeTag({ fs, dir, gitdir = join2(dir, \".git\"), tag: tag2 }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"tag\", tag2);\n return await _writeTag({\n fs: new FileSystem(fs),\n gitdir,\n tag: tag2\n });\n } catch (err) {\n err.caller = \"git.writeTag\";\n throw err;\n }\n}\nasync function writeTree({ fs, dir, gitdir = join2(dir, \".git\"), tree }) {\n try {\n assertParameter(\"fs\", fs);\n assertParameter(\"gitdir\", gitdir);\n assertParameter(\"tree\", tree);\n return await _writeTree({\n fs: new FileSystem(fs),\n gitdir,\n tree\n });\n } catch (err) {\n err.caller = \"git.writeTree\";\n throw err;\n }\n}\nvar index = {\n Errors,\n STAGE,\n TREE,\n WORKDIR,\n add,\n abortMerge,\n addNote,\n addRemote,\n annotatedTag,\n branch,\n checkout,\n clone,\n commit,\n getConfig,\n getConfigAll,\n setConfig,\n currentBranch,\n deleteBranch,\n deleteRef,\n deleteRemote,\n deleteTag,\n expandOid,\n expandRef,\n fastForward,\n fetch: fetch2,\n findMergeBase,\n findRoot,\n getRemoteInfo,\n getRemoteInfo2,\n hashBlob,\n indexPack,\n init,\n isDescendent,\n isIgnored,\n listBranches,\n listFiles,\n listNotes,\n listRefs,\n listRemotes,\n listServerRefs,\n listTags,\n log,\n merge,\n packObjects,\n pull,\n push,\n readBlob,\n readCommit,\n readNote,\n readObject,\n readTag,\n readTree,\n remove,\n removeNote,\n renameBranch,\n resetIndex,\n updateIndex: updateIndex$1,\n resolveRef,\n status,\n statusMatrix,\n tag,\n version,\n walk,\n writeBlob,\n writeCommit,\n writeObject,\n writeRef,\n writeTag,\n writeTree,\n stash\n};\nvar cf_git_default = index;\n\n// ../../node_modules/.bun/@ashishkumar472+cf-git@1.0.5/node_modules/@ashishkumar472/cf-git/http/web/index.js\nvar web_exports = {};\n__export(web_exports, {\n default: () => web_default,\n request: () => request\n});\nfunction fromValue2(value) {\n let queue = [value];\n return {\n next() {\n return Promise.resolve({ done: queue.length === 0, value: queue.pop() });\n },\n return() {\n queue = [];\n return {};\n },\n [Symbol.asyncIterator]() {\n return this;\n }\n };\n}\nfunction getIterator2(iterable) {\n if (iterable[Symbol.asyncIterator]) {\n return iterable[Symbol.asyncIterator]();\n }\n if (iterable[Symbol.iterator]) {\n return iterable[Symbol.iterator]();\n }\n if (iterable.next) {\n return iterable;\n }\n return fromValue2(iterable);\n}\nasync function forAwait2(iterable, cb) {\n const iter = getIterator2(iterable);\n while (true) {\n const { value, done } = await iter.next();\n if (value) await cb(value);\n if (done) break;\n }\n if (iter.return) iter.return();\n}\nasync function collect2(iterable) {\n let size = 0;\n const buffers = [];\n await forAwait2(iterable, (value) => {\n buffers.push(value);\n size += value.byteLength;\n });\n const result = new Uint8Array(size);\n let nextIndex = 0;\n for (const buffer of buffers) {\n result.set(buffer, nextIndex);\n nextIndex += buffer.byteLength;\n }\n return result;\n}\nfunction fromStream(stream) {\n if (stream[Symbol.asyncIterator]) return stream;\n const reader = stream.getReader();\n return {\n next() {\n return reader.read();\n },\n return() {\n reader.releaseLock();\n return {};\n },\n [Symbol.asyncIterator]() {\n return this;\n }\n };\n}\nasync function request({\n onProgress,\n url,\n method = \"GET\",\n headers = {},\n body\n}) {\n if (body) {\n body = await collect2(body);\n }\n const res = await fetch(url, { method, headers, body });\n const iter = res.body && res.body.getReader ? fromStream(res.body) : [new Uint8Array(await res.arrayBuffer())];\n headers = {};\n for (const [key, value] of res.headers.entries()) {\n headers[key] = value;\n }\n return {\n url: res.url,\n method: res.method,\n statusCode: res.status,\n statusMessage: res.statusText,\n body: iter,\n headers\n };\n}\nvar index2 = { request };\nvar web_default = index2;\nexport {\n cf_git_exports as git,\n web_exports as gitHttp\n};\n/*! Bundled license information:\n\ncrc-32/crc32.js:\n (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *)\n*/\n";
14
- export const GIT_BUNDLE_SIZE = 493906;
8
+ export const GIT_BUNDLE_ENTRY = "/_assets/runtime/git-de3e60c9f3ff006a.js";
9
+ export const GIT_BUNDLE_BUILD_ID = "de3e60c9f3ff006a";
10
+ export const GIT_BUNDLE_SHA256 = "de3e60c9f3ff006a0befd7d8e2cbe29dc5628d033ae5081499d26cccd253732f";