@dev.fast/whiteboard 0.0.0-stage → 0.2.1-preview.20261005.98

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 (247) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -2
  3. package/THIRD_PARTY_NOTICES.md +93 -0
  4. package/dist/account-alias-DOHN1RSH.js +973 -0
  5. package/dist/agent-cli-ChOq0ZuO.js +117 -0
  6. package/dist/agent-cli-DzWfZr6G.js +2 -0
  7. package/dist/agent-client-CPQo7iTI.js +305 -0
  8. package/dist/authoring-tools-Cr6Kpjsx.js +234 -0
  9. package/dist/build-info.json +1 -0
  10. package/dist/cli-hVgHcdsv.js +47 -0
  11. package/dist/cli-runner-D8y2_luU.js +5095 -0
  12. package/dist/cli.d.ts +1 -0
  13. package/dist/cli.js +128 -0
  14. package/dist/client-DFoh50W3.js +950 -0
  15. package/dist/desktop-discovery-DBO-PM2V.js +164 -0
  16. package/dist/error-message-OtiDonty.js +6 -0
  17. package/dist/fs-utils-BMPLt0cr.js +22 -0
  18. package/dist/fuzzy-match-BoAmcyak.js +30 -0
  19. package/dist/headless-host-BJxf4dUU.js +94 -0
  20. package/dist/input-error-OLgB_h31.js +11 -0
  21. package/dist/local-data-CxLk75rx.js +4491 -0
  22. package/dist/mcp-QeF8vkdf.js +140 -0
  23. package/dist/package-paths-B6-zxvIO.js +47 -0
  24. package/dist/process-error-telemetry-v9e5h6D7.js +3952 -0
  25. package/dist/profile-4ry2f3AM.js +76 -0
  26. package/dist/profile-Bh5FIrmf.js +2 -0
  27. package/dist/request-origin-D_4QIdoN.js +811 -0
  28. package/dist/review-agent-traces-DNJFYzc8.js +3866 -0
  29. package/dist/review-home-paths-6zZH-1c9.js +2560 -0
  30. package/dist/review-telemetry-DEFnQsQ2.js +1195 -0
  31. package/dist/runtime-CKiWhGrf.js +52 -0
  32. package/dist/runtime.d.ts +9 -0
  33. package/dist/runtime.js +2 -0
  34. package/dist/s3-SzLpeCG6.js +345 -0
  35. package/dist/s3-config-BgxkSoOy.js +2 -0
  36. package/dist/s3-config-CAxhO9u_.js +676 -0
  37. package/dist/server/desktop-host.d.ts +4 -0
  38. package/dist/server/desktop-host.js +1702 -0
  39. package/dist/server-discovery-Dbzn3w6Z.js +66 -0
  40. package/dist/sharing/index.d.ts +1977 -0
  41. package/dist/sharing/index.js +2 -0
  42. package/dist/src-CGP5ytbV.js +283 -0
  43. package/dist/src-CmdiBL20.js +3676 -0
  44. package/dist/src-DnwdaQ2r.js +865 -0
  45. package/dist/src-X9phtB2j.js +68 -0
  46. package/dist/stored-document-migration-DHeMpLMb.js +2671 -0
  47. package/dist/tool-failure-C8zB73HV.js +98 -0
  48. package/dist/tutorial-trace-DrBvkaeL.js +43 -0
  49. package/instructions/authoring.md +36 -0
  50. package/instructions/file-lenses.md +13 -0
  51. package/instructions/scratchpad.md +23 -0
  52. package/instructions/trace-archaeology.md +113 -0
  53. package/onboarding.md +8 -0
  54. package/package.json +106 -3
  55. package/src/agent-selection.ts +100 -0
  56. package/src/agent-session-ref.ts +80 -0
  57. package/src/ask/agents.ts +351 -0
  58. package/src/ask/checkout-files.ts +47 -0
  59. package/src/ask/file-refs.ts +111 -0
  60. package/src/ask/pi-mcp.ts +154 -0
  61. package/src/ask/protocol.ts +244 -0
  62. package/src/ask/thread-state.ts +350 -0
  63. package/src/ask/thread.ts +1400 -0
  64. package/src/ask/threads.ts +219 -0
  65. package/src/ask/watch.ts +79 -0
  66. package/src/cli-install.ts +1041 -0
  67. package/src/cli-runner.ts +1461 -0
  68. package/src/cli-runtime-info.ts +35 -0
  69. package/src/cli.ts +222 -0
  70. package/src/connect-prompts.ts +248 -0
  71. package/src/cursor-deeplink.ts +11 -0
  72. package/src/desktop-discovery.ts +355 -0
  73. package/src/diff-selection-migration.ts +63 -0
  74. package/src/embedded-posthog-key.ts +6 -0
  75. package/src/error-telemetry.ts +247 -0
  76. package/src/evidence.ts +14 -0
  77. package/src/exception-telemetry.ts +126 -0
  78. package/src/fixtures/blocks/call_stack_diff.json +27 -0
  79. package/src/fixtures/blocks/callout.json +11 -0
  80. package/src/fixtures/blocks/code.json +9 -0
  81. package/src/fixtures/blocks/code_peek.json +8 -0
  82. package/src/fixtures/blocks/database_lens.json +51 -0
  83. package/src/fixtures/blocks/divider.json +1 -0
  84. package/src/fixtures/blocks/fixtures.ts +33 -0
  85. package/src/fixtures/blocks/flow_diagram.json +36 -0
  86. package/src/fixtures/blocks/ids.ts +8 -0
  87. package/src/fixtures/blocks/image.json +9 -0
  88. package/src/fixtures/blocks/markdown.json +7 -0
  89. package/src/fixtures/blocks/section.json +11 -0
  90. package/src/fixtures/blocks/sequence.json +31 -0
  91. package/src/fixtures/blocks/software_map.json +7 -0
  92. package/src/fixtures/blocks/trace_quote.json +9 -0
  93. package/src/fixtures/blocks/tutorial.json +51 -0
  94. package/src/fs-utils.ts +32 -0
  95. package/src/fuzzy-match.ts +94 -0
  96. package/src/install.ts +29 -0
  97. package/src/legacy-skills.ts +133 -0
  98. package/src/lens-selection.ts +230 -0
  99. package/src/markdown-latex-math.ts +230 -0
  100. package/src/markdown.ts +81 -0
  101. package/src/package-paths.ts +53 -0
  102. package/src/posthog-capture-client.ts +610 -0
  103. package/src/review-api/README.md +295 -0
  104. package/src/review-api/activity.ts +340 -0
  105. package/src/review-api/agent-cli.ts +219 -0
  106. package/src/review-api/agent-client.ts +188 -0
  107. package/src/review-api/anchor-quotes.ts +88 -0
  108. package/src/review-api/ask-history.ts +242 -0
  109. package/src/review-api/authoring-tools.ts +211 -0
  110. package/src/review-api/blocks/call_stack_diff.ts +75 -0
  111. package/src/review-api/blocks/callout.ts +24 -0
  112. package/src/review-api/blocks/code.ts +9 -0
  113. package/src/review-api/blocks/code_peek.ts +13 -0
  114. package/src/review-api/blocks/database_lens.ts +150 -0
  115. package/src/review-api/blocks/definition.ts +40 -0
  116. package/src/review-api/blocks/divider.ts +6 -0
  117. package/src/review-api/blocks/flow_diagram.ts +111 -0
  118. package/src/review-api/blocks/image.ts +10 -0
  119. package/src/review-api/blocks/index.ts +90 -0
  120. package/src/review-api/blocks/markdown.ts +17 -0
  121. package/src/review-api/blocks/section.ts +24 -0
  122. package/src/review-api/blocks/sequence.ts +56 -0
  123. package/src/review-api/blocks/software_map.ts +9 -0
  124. package/src/review-api/blocks/trace_quote.ts +10 -0
  125. package/src/review-api/blocks/tutorial.ts +39 -0
  126. package/src/review-api/checkout-fs.ts +14 -0
  127. package/src/review-api/client.ts +1 -0
  128. package/src/review-api/comparison-coverage.ts +304 -0
  129. package/src/review-api/component-reference.ts +30 -0
  130. package/src/review-api/diff-lenses.ts +175 -0
  131. package/src/review-api/document-headings.ts +51 -0
  132. package/src/review-api/document-text.ts +200 -0
  133. package/src/review-api/document.ts +906 -0
  134. package/src/review-api/file-lenses.ts +100 -0
  135. package/src/review-api/http.ts +1877 -0
  136. package/src/review-api/image-decode.ts +29 -0
  137. package/src/review-api/input-error.ts +9 -0
  138. package/src/review-api/instructions.ts +89 -0
  139. package/src/review-api/lens-alignment.ts +52 -0
  140. package/src/review-api/local-data.ts +1837 -0
  141. package/src/review-api/map-input.ts +154 -0
  142. package/src/review-api/mcp-client-agent.ts +32 -0
  143. package/src/review-api/mcp.ts +240 -0
  144. package/src/review-api/origin.ts +43 -0
  145. package/src/review-api/profile.ts +146 -0
  146. package/src/review-api/public-tools.ts +102 -0
  147. package/src/review-api/pull-request.ts +389 -0
  148. package/src/review-api/read-schemas.ts +85 -0
  149. package/src/review-api/recovery.ts +2 -0
  150. package/src/review-api/request-origin.ts +33 -0
  151. package/src/review-api/review-progress.ts +382 -0
  152. package/src/review-api/status-tool.ts +10 -0
  153. package/src/review-api/store-schema.ts +22 -0
  154. package/src/review-api/store.ts +1647 -0
  155. package/src/review-api/tool-failure.ts +64 -0
  156. package/src/review-api/trace-schema.ts +13 -0
  157. package/src/review-api/traces.ts +119 -0
  158. package/src/review-api/unsupported-files.integration.ts +91 -0
  159. package/src/review-api/workspaces.ts +692 -0
  160. package/src/review-api/worktree-source.ts +170 -0
  161. package/src/review-api/worktree-structural.integration.ts +320 -0
  162. package/src/review-app-launcher.ts +432 -0
  163. package/src/review-app-picker.ts +168 -0
  164. package/src/review-app.ts +134 -0
  165. package/src/review-bundled-tools.ts +249 -0
  166. package/src/review-checkout-paths.ts +37 -0
  167. package/src/review-diff-files.ts +89 -0
  168. package/src/review-head-checkout.ts +300 -0
  169. package/src/review-home-paths.ts +73 -0
  170. package/src/review-info.ts +59 -0
  171. package/src/review-instances.ts +113 -0
  172. package/src/review-logger.ts +183 -0
  173. package/src/review-preferences.ts +88 -0
  174. package/src/review-prepare.ts +291 -0
  175. package/src/review-stack.ts +112 -0
  176. package/src/review-telemetry.ts +1066 -0
  177. package/src/runtime.ts +74 -0
  178. package/src/server/account-alias.ts +30 -0
  179. package/src/server/bounded-stream.ts +34 -0
  180. package/src/server/bug-report.ts +301 -0
  181. package/src/server/client-error-budget.ts +45 -0
  182. package/src/server/crash-report.ts +273 -0
  183. package/src/server/desktop-host-shutdown.ts +64 -0
  184. package/src/server/desktop-host.ts +190 -0
  185. package/src/server/desktop-server.ts +703 -0
  186. package/src/server/diffr-config.ts +509 -0
  187. package/src/server/diffr-languages.ts +97 -0
  188. package/src/server/global-verb-relay.ts +190 -0
  189. package/src/server/headless-host.ts +149 -0
  190. package/src/server/hono-http.ts +162 -0
  191. package/src/server/http-json.ts +24 -0
  192. package/src/server/json-review-reporting.ts +174 -0
  193. package/src/server/process-error-telemetry.ts +174 -0
  194. package/src/server/review-api-parsers.ts +90 -0
  195. package/src/server/review-lifecycle-telemetry.ts +73 -0
  196. package/src/server/review-open-watchdog.ts +46 -0
  197. package/src/server/review-server-core.ts +290 -0
  198. package/src/server/structural-comparisons.ts +153 -0
  199. package/src/server/structural-diff.ts +186 -0
  200. package/src/server/tutorial-service.ts +241 -0
  201. package/src/server/ui-telemetry.ts +198 -0
  202. package/src/server-discovery.ts +95 -0
  203. package/src/session-markers.ts +132 -0
  204. package/src/sharing/auth.ts +41 -0
  205. package/src/sharing/cli.ts +83 -0
  206. package/src/sharing/client.ts +334 -0
  207. package/src/sharing/export.ts +195 -0
  208. package/src/sharing/host.ts +316 -0
  209. package/src/sharing/import.ts +787 -0
  210. package/src/sharing/index.ts +16 -0
  211. package/src/sharing/repository.ts +145 -0
  212. package/src/sharing/routes.ts +34 -0
  213. package/src/slug.ts +23 -0
  214. package/src/software-map-diff-counts.ts +517 -0
  215. package/src/software-map-model.ts +1147 -0
  216. package/src/software-map-topology-diff.ts +260 -0
  217. package/src/source.ts +92 -0
  218. package/src/startup-trace.ts +232 -0
  219. package/src/stored-document-migration.ts +151 -0
  220. package/src/telemetry-clean-text.ts +257 -0
  221. package/src/telemetry-config.ts +298 -0
  222. package/src/telemetry-debug-sink.ts +38 -0
  223. package/src/telemetry.ts +13 -0
  224. package/src/trace-cli.ts +156 -0
  225. package/src/trace-storage-cli.ts +509 -0
  226. package/src/tutorial-conversation.ts +18 -0
  227. package/src/ui-telemetry-events.ts +765 -0
  228. package/src/unified-diff.ts +71 -0
  229. package/src/viewed-coverage.ts +259 -0
  230. package/src/windows-cli.ts +125 -0
  231. package/tutorial/document.json +275 -0
  232. package/tutorial/runtime-manifest.json +12 -0
  233. package/tutorial/sample-service/package.json +9 -0
  234. package/tutorial/sample-service/src/api/checkout-api.ts +17 -0
  235. package/tutorial/sample-service/src/app.ts +26 -0
  236. package/tutorial/sample-service/src/database/schema.ts +10 -0
  237. package/tutorial/sample-service/src/fulfillment/fulfillment-queue.ts +15 -0
  238. package/tutorial/sample-service/src/fulfillment/fulfillment-worker.ts +24 -0
  239. package/tutorial/sample-service/src/inventory/inventory-service.ts +11 -0
  240. package/tutorial/sample-service/src/orders/order-service.ts +34 -0
  241. package/tutorial/sample-service/src/orders/order.ts +21 -0
  242. package/tutorial/sample-service/src/orders/orders-repository.ts +24 -0
  243. package/tutorial/sample-service/src/payments/payment-gateway.ts +12 -0
  244. package/tutorial/sample-service/src/shipping/shipping-gateway.ts +15 -0
  245. package/tutorial/sample-service/tsconfig.json +12 -0
  246. package/tutorial/software-map.json +139 -0
  247. package/tutorial/trace.json +20 -0
@@ -0,0 +1,3676 @@
1
+ import { createRequire } from "node:module";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { execFile, execFileSync, spawn } from "node:child_process";
6
+ import { promisify } from "node:util";
7
+ import "node:timers/promises";
8
+ //#region \0rolldown/runtime.js
9
+ var __create = Object.create;
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __getProtoOf = Object.getPrototypeOf;
14
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
18
+ key = keys[i];
19
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
20
+ get: ((k) => from[k]).bind(null, key),
21
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
22
+ });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
27
+ value: mod,
28
+ enumerable: true
29
+ }) : target, mod));
30
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
31
+ //#endregion
32
+ //#region ../../node_modules/protocols/lib/index.js
33
+ var require_lib$4 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
34
+ /**
35
+ * protocols
36
+ * Returns the protocols of an input url.
37
+ *
38
+ * @name protocols
39
+ * @function
40
+ * @param {String|URL} input The input url (string or `URL` instance)
41
+ * @param {Boolean|Number} first If `true`, the first protocol will be returned. If number, it will represent the zero-based index of the protocols array.
42
+ * @return {Array|String} The array of protocols or the specified protocol.
43
+ */
44
+ module.exports = function protocols(input, first) {
45
+ if (first === true) first = 0;
46
+ var prots = "";
47
+ if (typeof input === "string") try {
48
+ prots = new URL(input).protocol;
49
+ } catch (e) {}
50
+ else if (input && input.constructor === URL) prots = input.protocol;
51
+ var splits = prots.split(/\:|\+/).filter(Boolean);
52
+ if (typeof first === "number") return splits[first];
53
+ return splits;
54
+ };
55
+ }));
56
+ //#endregion
57
+ //#region ../../node_modules/parse-path/lib/index.js
58
+ var require_lib$3 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
59
+ var protocols = require_lib$4();
60
+ /**
61
+ * parsePath
62
+ * Parses the input url.
63
+ *
64
+ * @name parsePath
65
+ * @function
66
+ * @param {String} url The input url.
67
+ * @return {Object} An object containing the following fields:
68
+ *
69
+ * - `protocols` (Array): An array with the url protocols (usually it has one element).
70
+ * - `protocol` (String): The first protocol or `"file"`.
71
+ * - `port` (String): The domain port (default: `""`).
72
+ * - `resource` (String): The url domain/hostname.
73
+ * - `host` (String): The url domain (including subdomain and port).
74
+ * - `user` (String): The authentication user (default: `""`).
75
+ * - `password` (String): The authentication password (default: `""`).
76
+ * - `pathname` (String): The url pathname.
77
+ * - `hash` (String): The url hash.
78
+ * - `search` (String): The url querystring value (excluding `?`).
79
+ * - `href` (String): The normalized input url.
80
+ * - `query` (Object): The url querystring, parsed as object.
81
+ * - `parse_failed` (Boolean): Whether the parsing failed or not.
82
+ */
83
+ function parsePath(url) {
84
+ var output = {
85
+ protocols: [],
86
+ protocol: null,
87
+ port: null,
88
+ resource: "",
89
+ host: "",
90
+ user: "",
91
+ password: "",
92
+ pathname: "",
93
+ hash: "",
94
+ search: "",
95
+ href: url,
96
+ query: {},
97
+ parse_failed: false
98
+ };
99
+ try {
100
+ var parsed = new URL(url);
101
+ output.protocols = protocols(parsed);
102
+ output.protocol = output.protocols[0];
103
+ output.port = parsed.port;
104
+ output.resource = parsed.hostname;
105
+ output.host = parsed.host;
106
+ output.user = parsed.username || "";
107
+ output.password = parsed.password || "";
108
+ output.pathname = parsed.pathname;
109
+ output.hash = parsed.hash.slice(1);
110
+ output.search = parsed.search.slice(1);
111
+ output.href = parsed.href;
112
+ output.query = Object.fromEntries(parsed.searchParams);
113
+ } catch (e) {
114
+ output.protocols = ["file"];
115
+ output.protocol = output.protocols[0];
116
+ output.port = "";
117
+ output.resource = "";
118
+ output.user = "";
119
+ output.pathname = "";
120
+ output.hash = "";
121
+ output.search = "";
122
+ output.href = url;
123
+ output.query = {};
124
+ output.parse_failed = true;
125
+ }
126
+ return output;
127
+ }
128
+ module.exports = parsePath;
129
+ }));
130
+ //#endregion
131
+ //#region ../../node_modules/parse-url/dist/index.js
132
+ var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
133
+ var require$$1 = require_lib$3();
134
+ function _interopDefaultLegacy(e) {
135
+ return e && typeof e === "object" && "default" in e ? e : { "default": e };
136
+ }
137
+ var require$$1__default = /*#__PURE__*/ _interopDefaultLegacy(require$$1);
138
+ function getAugmentedNamespace(n) {
139
+ if (n.__esModule) return n;
140
+ var f = n.default;
141
+ if (typeof f == "function") {
142
+ var a = function a() {
143
+ if (this instanceof a) {
144
+ var args = [null];
145
+ args.push.apply(args, arguments);
146
+ return new (Function.bind.apply(f, args))();
147
+ }
148
+ return f.apply(this, arguments);
149
+ };
150
+ a.prototype = f.prototype;
151
+ } else a = {};
152
+ Object.defineProperty(a, "__esModule", { value: true });
153
+ Object.keys(n).forEach(function(k) {
154
+ var d = Object.getOwnPropertyDescriptor(n, k);
155
+ Object.defineProperty(a, k, d.get ? d : {
156
+ enumerable: true,
157
+ get: function() {
158
+ return n[k];
159
+ }
160
+ });
161
+ });
162
+ return a;
163
+ }
164
+ var src = {};
165
+ const DATA_URL_DEFAULT_MIME_TYPE = "text/plain";
166
+ const DATA_URL_DEFAULT_CHARSET = "us-ascii";
167
+ const testParameter = (name, filters) => filters.some((filter) => filter instanceof RegExp ? filter.test(name) : filter === name);
168
+ const normalizeDataURL = (urlString, { stripHash }) => {
169
+ const match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);
170
+ if (!match) throw new Error(`Invalid URL: ${urlString}`);
171
+ let { type, data, hash } = match.groups;
172
+ const mediaType = type.split(";");
173
+ hash = stripHash ? "" : hash;
174
+ let isBase64 = false;
175
+ if (mediaType[mediaType.length - 1] === "base64") {
176
+ mediaType.pop();
177
+ isBase64 = true;
178
+ }
179
+ const mimeType = (mediaType.shift() || "").toLowerCase();
180
+ const normalizedMediaType = [...mediaType.map((attribute) => {
181
+ let [key, value = ""] = attribute.split("=").map((string) => string.trim());
182
+ if (key === "charset") {
183
+ value = value.toLowerCase();
184
+ if (value === DATA_URL_DEFAULT_CHARSET) return "";
185
+ }
186
+ return `${key}${value ? `=${value}` : ""}`;
187
+ }).filter(Boolean)];
188
+ if (isBase64) normalizedMediaType.push("base64");
189
+ if (normalizedMediaType.length > 0 || mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE) normalizedMediaType.unshift(mimeType);
190
+ return `data:${normalizedMediaType.join(";")},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ""}`;
191
+ };
192
+ function normalizeUrl(urlString, options) {
193
+ options = {
194
+ defaultProtocol: "http:",
195
+ normalizeProtocol: true,
196
+ forceHttp: false,
197
+ forceHttps: false,
198
+ stripAuthentication: true,
199
+ stripHash: false,
200
+ stripTextFragment: true,
201
+ stripWWW: true,
202
+ removeQueryParameters: [/^utm_\w+/i],
203
+ removeTrailingSlash: true,
204
+ removeSingleSlash: true,
205
+ removeDirectoryIndex: false,
206
+ sortQueryParameters: true,
207
+ ...options
208
+ };
209
+ urlString = urlString.trim();
210
+ if (/^data:/i.test(urlString)) return normalizeDataURL(urlString, options);
211
+ if (/^view-source:/i.test(urlString)) throw new Error("`view-source:` is not supported as it is a non-standard protocol");
212
+ const hasRelativeProtocol = urlString.startsWith("//");
213
+ if (!(!hasRelativeProtocol && /^\.*\//.test(urlString))) urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol);
214
+ const urlObject = new URL(urlString);
215
+ if (options.forceHttp && options.forceHttps) throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");
216
+ if (options.forceHttp && urlObject.protocol === "https:") urlObject.protocol = "http:";
217
+ if (options.forceHttps && urlObject.protocol === "http:") urlObject.protocol = "https:";
218
+ if (options.stripAuthentication) {
219
+ urlObject.username = "";
220
+ urlObject.password = "";
221
+ }
222
+ if (options.stripHash) urlObject.hash = "";
223
+ else if (options.stripTextFragment) urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, "");
224
+ if (urlObject.pathname) {
225
+ const protocolRegex = /\b[a-z][a-z\d+\-.]{1,50}:\/\//g;
226
+ let lastIndex = 0;
227
+ let result = "";
228
+ for (;;) {
229
+ const match = protocolRegex.exec(urlObject.pathname);
230
+ if (!match) break;
231
+ const protocol = match[0];
232
+ const protocolAtIndex = match.index;
233
+ const intermediate = urlObject.pathname.slice(lastIndex, protocolAtIndex);
234
+ result += intermediate.replace(/\/{2,}/g, "/");
235
+ result += protocol;
236
+ lastIndex = protocolAtIndex + protocol.length;
237
+ }
238
+ const remnant = urlObject.pathname.slice(lastIndex, urlObject.pathname.length);
239
+ result += remnant.replace(/\/{2,}/g, "/");
240
+ urlObject.pathname = result;
241
+ }
242
+ if (urlObject.pathname) try {
243
+ urlObject.pathname = decodeURI(urlObject.pathname);
244
+ } catch {}
245
+ if (options.removeDirectoryIndex === true) options.removeDirectoryIndex = [/^index\.[a-z]+$/];
246
+ if (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {
247
+ let pathComponents = urlObject.pathname.split("/");
248
+ const lastComponent = pathComponents[pathComponents.length - 1];
249
+ if (testParameter(lastComponent, options.removeDirectoryIndex)) {
250
+ pathComponents = pathComponents.slice(0, -1);
251
+ urlObject.pathname = pathComponents.slice(1).join("/") + "/";
252
+ }
253
+ }
254
+ if (urlObject.hostname) {
255
+ urlObject.hostname = urlObject.hostname.replace(/\.$/, "");
256
+ if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) urlObject.hostname = urlObject.hostname.replace(/^www\./, "");
257
+ }
258
+ if (Array.isArray(options.removeQueryParameters)) {
259
+ for (const key of [...urlObject.searchParams.keys()]) if (testParameter(key, options.removeQueryParameters)) urlObject.searchParams.delete(key);
260
+ }
261
+ if (options.removeQueryParameters === true) urlObject.search = "";
262
+ if (options.sortQueryParameters) {
263
+ urlObject.searchParams.sort();
264
+ try {
265
+ urlObject.search = decodeURIComponent(urlObject.search);
266
+ } catch {}
267
+ }
268
+ if (options.removeTrailingSlash) urlObject.pathname = urlObject.pathname.replace(/\/$/, "");
269
+ const oldUrlString = urlString;
270
+ urlString = urlObject.toString();
271
+ if (!options.removeSingleSlash && urlObject.pathname === "/" && !oldUrlString.endsWith("/") && urlObject.hash === "") urlString = urlString.replace(/\/$/, "");
272
+ if ((options.removeTrailingSlash || urlObject.pathname === "/") && urlObject.hash === "" && options.removeSingleSlash) urlString = urlString.replace(/\/$/, "");
273
+ if (hasRelativeProtocol && !options.normalizeProtocol) urlString = urlString.replace(/^http:\/\//, "//");
274
+ if (options.stripProtocol) urlString = urlString.replace(/^(?:https?:)?\/\//, "");
275
+ return urlString;
276
+ }
277
+ var require$$0 = /*@__PURE__*/ getAugmentedNamespace(/* @__PURE__ */ Object.freeze({
278
+ __proto__: null,
279
+ "default": normalizeUrl
280
+ }));
281
+ Object.defineProperty(src, "__esModule", { value: true });
282
+ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
283
+ return typeof obj;
284
+ } : function(obj) {
285
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
286
+ };
287
+ var _normalizeUrl2 = _interopRequireDefault(require$$0);
288
+ var _parsePath = require$$1__default["default"];
289
+ var _parsePath2 = _interopRequireDefault(_parsePath);
290
+ function _interopRequireDefault(obj) {
291
+ return obj && obj.__esModule ? obj : { default: obj };
292
+ }
293
+ /**
294
+ * parseUrl
295
+ * Parses the input url.
296
+ *
297
+ * **Note**: This *throws* if invalid urls are provided.
298
+ *
299
+ * @name parseUrl
300
+ * @function
301
+ * @param {String} url The input url.
302
+ * @param {Boolean|Object} normalize Whether to normalize the url or not.
303
+ * Default is `false`. If `true`, the url will
304
+ * be normalized. If an object, it will be the
305
+ * options object sent to [`normalize-url`](https://github.com/sindresorhus/normalize-url).
306
+ *
307
+ * For SSH urls, normalize won't work.
308
+ *
309
+ * @return {Object} An object containing the following fields:
310
+ *
311
+ * - `protocols` (Array): An array with the url protocols (usually it has one element).
312
+ * - `protocol` (String): The first protocol, `"ssh"` (if the url is a ssh url) or `"file"`.
313
+ * - `port` (null|Number): The domain port.
314
+ * - `resource` (String): The url domain (including subdomains).
315
+ * - `host` (String): The fully qualified domain name of a network host, or its IP address.
316
+ * - `user` (String): The authentication user (usually for ssh urls).
317
+ * - `pathname` (String): The url pathname.
318
+ * - `hash` (String): The url hash.
319
+ * - `search` (String): The url querystring value.
320
+ * - `href` (String): The input url.
321
+ * - `query` (Object): The url querystring, parsed as object.
322
+ * - `parse_failed` (Boolean): Whether the parsing failed or not.
323
+ */
324
+ var parseUrl = function parseUrl(url) {
325
+ var normalize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
326
+ /**
327
+ * ([a-zA-Z_][a-zA-Z0-9_-]{0,31}) Try to match the user
328
+ * ([\w\.\-@]+) Match the host/resource
329
+ * (([\~,\.\w,\-,\_,\/,\s]|%[0-9A-Fa-f]{2})+?(?:\.git|\/)?) Match the path, allowing spaces/white
330
+ */
331
+ var GIT_RE = /^(?:([a-zA-Z_][a-zA-Z0-9_-]{0,31})@|https?:\/\/)([\w\.\-@]+)[\/:](([\~,\.\w,\-,\_,\/,\s]|%[0-9A-Fa-f]{2})+?(?:\.git|\/)?)$/;
332
+ var throwErr = function throwErr(msg) {
333
+ var err = new Error(msg);
334
+ err.subject_url = url;
335
+ throw err;
336
+ };
337
+ if (typeof url !== "string" || !url.trim()) throwErr("Invalid url.");
338
+ if (url.length > parseUrl.MAX_INPUT_LENGTH) throwErr("Input exceeds maximum length. If needed, change the value of parseUrl.MAX_INPUT_LENGTH.");
339
+ if (normalize) {
340
+ if ((typeof normalize === "undefined" ? "undefined" : _typeof(normalize)) !== "object") normalize = { stripHash: false };
341
+ url = (0, _normalizeUrl2.default)(url, normalize);
342
+ }
343
+ var parsed = (0, _parsePath2.default)(url);
344
+ if (parsed.parse_failed) {
345
+ var matched = parsed.href.match(GIT_RE);
346
+ if (matched) {
347
+ parsed.protocols = ["ssh"];
348
+ parsed.protocol = "ssh";
349
+ parsed.resource = matched[2];
350
+ parsed.host = matched[2];
351
+ parsed.user = matched[1];
352
+ parsed.pathname = "/" + matched[3];
353
+ parsed.parse_failed = false;
354
+ } else throwErr("URL parsing failed.");
355
+ }
356
+ return parsed;
357
+ };
358
+ parseUrl.MAX_INPUT_LENGTH = 2048;
359
+ module.exports = src.default = parseUrl;
360
+ }));
361
+ //#endregion
362
+ //#region ../../node_modules/is-ssh/lib/index.js
363
+ var require_lib$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
364
+ var protocols = require_lib$4();
365
+ /**
366
+ * isSsh
367
+ * Checks if an input value is a ssh url or not.
368
+ *
369
+ * @name isSsh
370
+ * @function
371
+ * @param {String|Array} input The input url or an array of protocols.
372
+ * @return {Boolean} `true` if the input is a ssh url, `false` otherwise.
373
+ */
374
+ function isSsh(input) {
375
+ if (Array.isArray(input)) return input.indexOf("ssh") !== -1 || input.indexOf("rsync") !== -1;
376
+ if (typeof input !== "string") return false;
377
+ var prots = protocols(input);
378
+ input = input.substring(input.indexOf("://") + 3);
379
+ if (isSsh(prots)) return true;
380
+ var urlPortPattern = /* @__PURE__ */ new RegExp(".([a-zA-Z\\d]+):(\\d+)/");
381
+ return !input.match(urlPortPattern) && input.indexOf("@") < input.indexOf(":");
382
+ }
383
+ module.exports = isSsh;
384
+ }));
385
+ //#endregion
386
+ //#region ../../node_modules/git-up/lib/index.js
387
+ var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
388
+ const parseUrl = require_dist();
389
+ const isSsh = require_lib$2();
390
+ /**
391
+ * gitUp
392
+ * Parses the input url.
393
+ *
394
+ * @name gitUp
395
+ * @function
396
+ * @param {String} input The input url.
397
+ * @return {Object} An object containing the following fields:
398
+ *
399
+ * - `protocols` (Array): An array with the url protocols (usually it has one element).
400
+ * - `port` (String): The domain port.
401
+ * - `resource` (String): The url domain (including subdomains).
402
+ * - `user` (String): The authentication user (usually for ssh urls).
403
+ * - `pathname` (String): The url pathname.
404
+ * - `hash` (String): The url hash.
405
+ * - `search` (String): The url querystring value.
406
+ * - `href` (String): The input url.
407
+ * - `protocol` (String): The git url protocol.
408
+ * - `token` (String): The oauth token (could appear in the https urls).
409
+ */
410
+ function gitUp(input) {
411
+ let output = parseUrl(input);
412
+ output.token = "";
413
+ if (output.password === "x-oauth-basic") output.token = output.user;
414
+ else if (output.user === "x-token-auth") output.token = output.password;
415
+ if (isSsh(output.protocols) || output.protocols.length === 0 && isSsh(input)) output.protocol = "ssh";
416
+ else if (output.protocols.length) output.protocol = output.protocols[0];
417
+ else {
418
+ output.protocol = "file";
419
+ output.protocols = ["file"];
420
+ }
421
+ output.href = output.href.replace(/\/$/, "");
422
+ return output;
423
+ }
424
+ module.exports = gitUp;
425
+ }));
426
+ /*!
427
+ * buildToken
428
+ * Builds OAuth token prefix (helper function)
429
+ *
430
+ * @name buildToken
431
+ * @function
432
+ * @param {GitUrl} obj The parsed Git url object.
433
+ * @return {String} token prefix
434
+ */
435
+ //#endregion
436
+ //#region ../local-vcs/src/exec.ts
437
+ var import_lib = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
438
+ var gitUp = require_lib$1();
439
+ /**
440
+ * gitUrlParse
441
+ * Parses a Git url.
442
+ *
443
+ * @name gitUrlParse
444
+ * @function
445
+ * @param {String} url The Git url to parse.
446
+ * @param {Array} refs An array of strings representing the refs. This is
447
+ * helpful in the context of the URLs that contain branches with slashes.
448
+ * If user wants to identify the branch, he should pass all branch names
449
+ * of the project as part of refs parameter
450
+ * @return {GitUrl} The `GitUrl` object containing:
451
+ *
452
+ * - `protocols` (Array): An array with the url protocols (usually it has one element).
453
+ * - `port` (String): The domain port.
454
+ * - `resource` (String): The url domain (including subdomains).
455
+ * - `user` (String): The authentication user (usually for ssh urls).
456
+ * - `pathname` (String): The url pathname.
457
+ * - `hash` (String): The url hash.
458
+ * - `search` (String): The url querystring value.
459
+ * - `href` (String): The input url.
460
+ * - `protocol` (String): The git url protocol.
461
+ * - `token` (String): The oauth token (could appear in the https urls).
462
+ * - `source` (String): The Git provider (e.g. `"github.com"`).
463
+ * - `owner` (String): The repository owner.
464
+ * - `name` (String): The repository name.
465
+ * - `ref` (String): The repository ref (e.g., "master" or "dev").
466
+ * - `filepath` (String): A filepath relative to the repository root.
467
+ * - `filepathtype` (String): The type of filepath in the url ("blob" or "tree").
468
+ * - `full_name` (String): The owner and name values in the `owner/name` format.
469
+ * - `toString` (Function): A function to stringify the parsed url into another url type.
470
+ * - `organization` (String): The organization the owner belongs to. This is CloudForge specific.
471
+ * - `git_suffix` (Boolean): Whether to add the `.git` suffix or not.
472
+ *
473
+ */
474
+ function gitUrlParse(url, refs) {
475
+ refs = refs || [];
476
+ if (typeof url !== "string") throw new Error("The url must be a string.");
477
+ if (!refs.every(function(item) {
478
+ return typeof item === "string";
479
+ })) throw new Error("The refs should contain only strings");
480
+ if (/^([a-z\d-]{1,39})\/([-\.\w]{1,100})$/i.test(url)) url = "https://github.com/" + url;
481
+ var urlInfo = gitUp(url), sourceParts = urlInfo.resource.split("."), splits = null;
482
+ urlInfo.toString = function(type) {
483
+ return gitUrlParse.stringify(this, type);
484
+ };
485
+ urlInfo.source = sourceParts.length > 2 ? sourceParts.slice(1 - sourceParts.length).join(".") : urlInfo.source = urlInfo.resource;
486
+ urlInfo.git_suffix = /\.git$/.test(urlInfo.pathname);
487
+ urlInfo.name = decodeURIComponent((urlInfo.pathname || urlInfo.href).replace(/(^\/)|(\/$)/g, "").replace(/\.git$/, ""));
488
+ urlInfo.owner = decodeURIComponent(urlInfo.user);
489
+ switch (urlInfo.source) {
490
+ case "git.cloudforge.com":
491
+ urlInfo.owner = urlInfo.user;
492
+ urlInfo.organization = sourceParts[0];
493
+ urlInfo.source = "cloudforge.com";
494
+ break;
495
+ case "visualstudio.com": if (urlInfo.resource === "vs-ssh.visualstudio.com") {
496
+ splits = urlInfo.name.split("/");
497
+ if (splits.length === 4) {
498
+ urlInfo.organization = splits[1];
499
+ urlInfo.owner = splits[2];
500
+ urlInfo.name = splits[3];
501
+ urlInfo.full_name = splits[2] + "/" + splits[3];
502
+ }
503
+ break;
504
+ } else {
505
+ splits = urlInfo.name.split("/");
506
+ if (splits.length === 2) {
507
+ urlInfo.owner = splits[1];
508
+ urlInfo.name = splits[1];
509
+ urlInfo.full_name = "_git/" + urlInfo.name;
510
+ } else if (splits.length === 3) {
511
+ urlInfo.name = splits[2];
512
+ if (splits[0] === "DefaultCollection") {
513
+ urlInfo.owner = splits[2];
514
+ urlInfo.organization = splits[0];
515
+ urlInfo.full_name = urlInfo.organization + "/_git/" + urlInfo.name;
516
+ } else {
517
+ urlInfo.owner = splits[0];
518
+ urlInfo.full_name = urlInfo.owner + "/_git/" + urlInfo.name;
519
+ }
520
+ } else if (splits.length === 4) {
521
+ urlInfo.organization = splits[0];
522
+ urlInfo.owner = splits[1];
523
+ urlInfo.name = splits[3];
524
+ urlInfo.full_name = urlInfo.organization + "/" + urlInfo.owner + "/_git/" + urlInfo.name;
525
+ }
526
+ break;
527
+ }
528
+ case "dev.azure.com":
529
+ case "azure.com": if (urlInfo.resource === "ssh.dev.azure.com") {
530
+ splits = urlInfo.name.split("/");
531
+ if (splits.length === 4) {
532
+ urlInfo.organization = splits[1];
533
+ urlInfo.owner = splits[2];
534
+ urlInfo.name = splits[3];
535
+ }
536
+ break;
537
+ } else {
538
+ splits = urlInfo.name.split("/");
539
+ if (splits.length === 5) {
540
+ urlInfo.organization = splits[0];
541
+ urlInfo.owner = splits[1];
542
+ urlInfo.name = splits[4];
543
+ urlInfo.full_name = "_git/" + urlInfo.name;
544
+ } else if (splits.length === 3) {
545
+ urlInfo.name = splits[2];
546
+ if (splits[0] === "DefaultCollection") {
547
+ urlInfo.owner = splits[2];
548
+ urlInfo.organization = splits[0];
549
+ urlInfo.full_name = urlInfo.organization + "/_git/" + urlInfo.name;
550
+ } else {
551
+ urlInfo.owner = splits[0];
552
+ urlInfo.full_name = urlInfo.owner + "/_git/" + urlInfo.name;
553
+ }
554
+ } else if (splits.length === 4) {
555
+ urlInfo.organization = splits[0];
556
+ urlInfo.owner = splits[1];
557
+ urlInfo.name = splits[3];
558
+ urlInfo.full_name = urlInfo.organization + "/" + urlInfo.owner + "/_git/" + urlInfo.name;
559
+ }
560
+ if (urlInfo.query && urlInfo.query["path"]) urlInfo.filepath = urlInfo.query["path"].replace(/^\/+/g, "");
561
+ if (urlInfo.query && urlInfo.query["version"]) urlInfo.ref = urlInfo.query["version"].replace(/^GB/, "");
562
+ break;
563
+ }
564
+ default:
565
+ splits = urlInfo.name.split("/");
566
+ var nameIndex = splits.length - 1;
567
+ if (splits.length >= 2) {
568
+ var dashIndex = splits.indexOf("-", 2);
569
+ var blobIndex = splits.indexOf("blob", 2);
570
+ var treeIndex = splits.indexOf("tree", 2);
571
+ var commitIndex = splits.indexOf("commit", 2);
572
+ var issuesIndex = splits.indexOf("issues", 2);
573
+ var srcIndex = splits.indexOf("src", 2);
574
+ var rawIndex = splits.indexOf("raw", 2);
575
+ var editIndex = splits.indexOf("edit", 2);
576
+ nameIndex = dashIndex > 0 ? dashIndex - 1 : blobIndex > 0 && treeIndex > 0 ? Math.min(blobIndex - 1, treeIndex - 1) : blobIndex > 0 ? blobIndex - 1 : issuesIndex > 0 ? issuesIndex - 1 : treeIndex > 0 ? treeIndex - 1 : commitIndex > 0 ? commitIndex - 1 : srcIndex > 0 ? srcIndex - 1 : rawIndex > 0 ? rawIndex - 1 : editIndex > 0 ? editIndex - 1 : nameIndex;
577
+ urlInfo.owner = splits.slice(0, nameIndex).join("/");
578
+ urlInfo.name = splits[nameIndex];
579
+ if (commitIndex && issuesIndex < 0) urlInfo.commit = splits[nameIndex + 2];
580
+ }
581
+ urlInfo.ref = "";
582
+ urlInfo.filepathtype = "";
583
+ urlInfo.filepath = "";
584
+ var offsetNameIndex = splits.length > nameIndex && splits[nameIndex + 1] === "-" ? nameIndex + 1 : nameIndex;
585
+ if (splits.length > offsetNameIndex + 2 && [
586
+ "raw",
587
+ "src",
588
+ "blob",
589
+ "tree",
590
+ "edit"
591
+ ].indexOf(splits[offsetNameIndex + 1]) >= 0) {
592
+ urlInfo.filepathtype = splits[offsetNameIndex + 1];
593
+ urlInfo.ref = splits[offsetNameIndex + 2];
594
+ if (splits.length > offsetNameIndex + 3) urlInfo.filepath = splits.slice(offsetNameIndex + 3).join("/");
595
+ }
596
+ urlInfo.organization = urlInfo.owner;
597
+ }
598
+ if (!urlInfo.full_name) {
599
+ urlInfo.full_name = urlInfo.owner;
600
+ if (urlInfo.name) {
601
+ urlInfo.full_name && (urlInfo.full_name += "/");
602
+ urlInfo.full_name += urlInfo.name;
603
+ }
604
+ }
605
+ if (urlInfo.owner.startsWith("scm/")) {
606
+ urlInfo.source = "bitbucket-server";
607
+ urlInfo.owner = urlInfo.owner.replace("scm/", "");
608
+ urlInfo.organization = urlInfo.owner;
609
+ urlInfo.full_name = urlInfo.owner + "/" + urlInfo.name;
610
+ }
611
+ var matches = /(projects|users)\/(.*?)\/repos\/(.*?)((\/.*$)|$)/.exec(urlInfo.pathname);
612
+ if (matches != null) {
613
+ urlInfo.source = "bitbucket-server";
614
+ if (matches[1] === "users") urlInfo.owner = "~" + matches[2];
615
+ else urlInfo.owner = matches[2];
616
+ urlInfo.organization = urlInfo.owner;
617
+ urlInfo.name = matches[3];
618
+ splits = matches[4].split("/");
619
+ if (splits.length > 1) {
620
+ if (["raw", "browse"].indexOf(splits[1]) >= 0) {
621
+ urlInfo.filepathtype = splits[1];
622
+ if (splits.length > 2) urlInfo.filepath = splits.slice(2).join("/");
623
+ } else if (splits[1] === "commits" && splits.length > 2) urlInfo.commit = splits[2];
624
+ }
625
+ urlInfo.full_name = urlInfo.owner + "/" + urlInfo.name;
626
+ if (urlInfo.query.at) urlInfo.ref = urlInfo.query.at;
627
+ else urlInfo.ref = "";
628
+ }
629
+ if (refs.length !== 0 && urlInfo.ref) {
630
+ urlInfo.ref = findLongestMatchingSubstring(urlInfo.href, refs) || urlInfo.ref;
631
+ urlInfo.filepath = urlInfo.href.split(urlInfo.ref + "/")[1];
632
+ }
633
+ return urlInfo;
634
+ }
635
+ /**
636
+ * stringify
637
+ * Stringifies a `GitUrl` object.
638
+ *
639
+ * @name stringify
640
+ * @function
641
+ * @param {GitUrl} obj The parsed Git url object.
642
+ * @param {String} type The type of the stringified url (default `obj.protocol`).
643
+ * @return {String} The stringified url.
644
+ */
645
+ gitUrlParse.stringify = function(obj, type) {
646
+ type = type || (obj.protocols && obj.protocols.length ? obj.protocols.join("+") : obj.protocol);
647
+ var port = obj.port ? ":" + obj.port : "";
648
+ var user = obj.user || "git";
649
+ var maybeGitSuffix = obj.git_suffix ? ".git" : "";
650
+ switch (type) {
651
+ case "ssh": if (port) return "ssh://" + user + "@" + obj.resource + port + "/" + obj.full_name + maybeGitSuffix;
652
+ else return user + "@" + obj.resource + ":" + obj.full_name + maybeGitSuffix;
653
+ case "git+ssh":
654
+ case "ssh+git":
655
+ case "ftp":
656
+ case "ftps": return type + "://" + user + "@" + obj.resource + port + "/" + obj.full_name + maybeGitSuffix;
657
+ case "http":
658
+ case "https":
659
+ var auth = obj.token ? buildToken(obj) : obj.user && (obj.protocols.includes("http") || obj.protocols.includes("https")) ? obj.user + "@" : "";
660
+ return type + "://" + auth + obj.resource + port + "/" + buildPath(obj) + maybeGitSuffix;
661
+ default: return obj.href;
662
+ }
663
+ };
664
+ function buildToken(obj) {
665
+ switch (obj.source) {
666
+ case "bitbucket.org": return "x-token-auth:" + obj.token + "@";
667
+ default: return obj.token + "@";
668
+ }
669
+ }
670
+ function buildPath(obj) {
671
+ switch (obj.source) {
672
+ case "bitbucket-server": return "scm/" + obj.full_name;
673
+ default: return obj.full_name.split("/").map(function(x) {
674
+ return encodeURIComponent(x);
675
+ }).join("/");
676
+ }
677
+ }
678
+ function findLongestMatchingSubstring(string, array) {
679
+ var longestMatch = "";
680
+ array.forEach(function(item) {
681
+ if (string.includes(item) && item.length > longestMatch.length) longestMatch = item;
682
+ });
683
+ return longestMatch;
684
+ }
685
+ module.exports = gitUrlParse;
686
+ })))(), 1);
687
+ let observer = null;
688
+ function setLocalVcsCommandObserver(next) {
689
+ observer = next;
690
+ }
691
+ const execFilePromise = promisify(execFile);
692
+ async function execFileAsync(file, args, options = {}) {
693
+ const finish = observer?.start({
694
+ file,
695
+ args,
696
+ cwd: options.cwd === void 0 ? void 0 : String(options.cwd)
697
+ });
698
+ try {
699
+ const result = await execFilePromise(file, args, {
700
+ ...options,
701
+ encoding: options.encoding ?? "utf8"
702
+ });
703
+ finish?.({ ok: true });
704
+ return {
705
+ stdout: String(result.stdout),
706
+ stderr: String(result.stderr)
707
+ };
708
+ } catch (error) {
709
+ finish?.({ ok: false });
710
+ throw error;
711
+ }
712
+ }
713
+ function execFileSyncObserved(file, args, options) {
714
+ const finish = observer?.start({
715
+ file,
716
+ args,
717
+ cwd: options.cwd === void 0 ? void 0 : String(options.cwd)
718
+ });
719
+ try {
720
+ const output = execFileSync(file, args, options);
721
+ finish?.({ ok: true });
722
+ return String(output);
723
+ } catch (error) {
724
+ finish?.({ ok: false });
725
+ throw error;
726
+ }
727
+ }
728
+ /** Long-lived child; the observer sees one spawn, completed once the process is up. */
729
+ function spawnObserved(file, args, options) {
730
+ const finish = observer?.start({
731
+ file,
732
+ args,
733
+ cwd: options.cwd === void 0 ? void 0 : String(options.cwd)
734
+ });
735
+ try {
736
+ const child = spawn(file, args, options);
737
+ let finished = false;
738
+ const complete = (ok) => {
739
+ if (finished) return;
740
+ finished = true;
741
+ finish?.({ ok });
742
+ };
743
+ child.once("spawn", () => complete(true));
744
+ child.once("error", () => complete(false));
745
+ return child;
746
+ } catch (error) {
747
+ finish?.({ ok: false });
748
+ throw error;
749
+ }
750
+ }
751
+ //#endregion
752
+ //#region ../local-vcs/src/blob-batch-reader.ts
753
+ const DEFAULT_IDLE_TIMEOUT_MS = 3e4;
754
+ const DEFAULT_MAX_BLOB_BYTES = 10485760;
755
+ const headerPattern = /^[0-9a-f]+ ([a-z]+) (\d+)$/;
756
+ const KILL_TIMEOUT_MS = 2e3;
757
+ const newline = 10;
758
+ const NOTHING = { found: "nothing" };
759
+ /** Not a cache: every read reaches git. Starts on first read, retires when idle, respawns after a crash. */
760
+ var BlobBatchReader = class {
761
+ input;
762
+ session = null;
763
+ objectStoreArgs = null;
764
+ starting = null;
765
+ idleTimer = null;
766
+ closed = false;
767
+ constructor(input) {
768
+ this.input = input;
769
+ }
770
+ get pid() {
771
+ return this.session?.child.pid;
772
+ }
773
+ processExit() {
774
+ return this.session?.exit ?? Promise.resolve();
775
+ }
776
+ async read(commit, relativePath) {
777
+ const answer = await this.readObject(commit, relativePath);
778
+ return answer.found === "blob" ? answer.blob : null;
779
+ }
780
+ async readObject(commit, relativePath) {
781
+ const request = `${commit}:${relativePath}`;
782
+ if (this.closed || request.includes("\n")) return NOTHING;
783
+ const session = await this.start();
784
+ if (!session) return NOTHING;
785
+ const answer = new Promise((resolve, reject) => {
786
+ session.pending.push({
787
+ resolve,
788
+ reject
789
+ });
790
+ session.writes = session.writes.then(() => this.write(session, `${request}\n`));
791
+ });
792
+ session.tail = answer.catch(() => null);
793
+ this.holdEventLoop(session);
794
+ this.armIdleTimer(session);
795
+ return answer;
796
+ }
797
+ async close() {
798
+ this.closed = true;
799
+ this.clearIdleTimer();
800
+ await this.starting?.catch(() => null);
801
+ const session = this.session;
802
+ if (!session) return;
803
+ await session.writes.catch(() => null);
804
+ await session.tail;
805
+ this.setEventLoopHold(session, true);
806
+ this.retire(session);
807
+ await this.awaitExit(session);
808
+ }
809
+ async awaitExit(session) {
810
+ let timer;
811
+ const expired = new Promise((resolve) => {
812
+ timer = setTimeout(() => resolve("expired"), KILL_TIMEOUT_MS);
813
+ timer.unref();
814
+ });
815
+ const outcome = await Promise.race([session.exit.then(() => "exited"), expired]);
816
+ clearTimeout(timer);
817
+ if (outcome === "exited") return;
818
+ session.child.kill("SIGKILL");
819
+ await session.exit;
820
+ }
821
+ start() {
822
+ if (this.session) return Promise.resolve(this.session);
823
+ this.starting ??= this.spawn().finally(() => {
824
+ this.starting = null;
825
+ });
826
+ return this.starting;
827
+ }
828
+ async spawn() {
829
+ const args = this.objectStoreArgs ?? await this.input.objectStoreArgs().catch(() => null);
830
+ if (!args) return null;
831
+ this.objectStoreArgs = args;
832
+ const child = spawnObserved("git", [
833
+ ...args,
834
+ "cat-file",
835
+ "--batch"
836
+ ], {
837
+ stdio: [
838
+ "pipe",
839
+ "pipe",
840
+ "ignore"
841
+ ],
842
+ env: this.input.env
843
+ });
844
+ const session = {
845
+ child,
846
+ pending: [],
847
+ buffered: Buffer.alloc(0),
848
+ expected: null,
849
+ collected: null,
850
+ writes: Promise.resolve(),
851
+ tail: Promise.resolve(),
852
+ exit: new Promise((resolve) => {
853
+ child.once("close", () => resolve());
854
+ })
855
+ };
856
+ child.stdin.on("error", () => {});
857
+ child.stdout.on("data", (chunk) => this.consume(session, chunk));
858
+ child.once("error", (cause) => this.fail(session, "git cat-file --batch could not start.", cause));
859
+ child.once("exit", () => this.fail(session, "git cat-file --batch stopped before answering."));
860
+ this.session = session;
861
+ this.armIdleTimer(session);
862
+ return session;
863
+ }
864
+ consume(session, chunk) {
865
+ session.buffered = session.buffered.length > 0 ? Buffer.concat([session.buffered, chunk]) : chunk;
866
+ for (;;) {
867
+ if (session.expected === null) {
868
+ const end = session.buffered.indexOf(newline);
869
+ if (end < 0) break;
870
+ const header = session.buffered.subarray(0, end).toString("utf8");
871
+ session.buffered = session.buffered.subarray(end + 1);
872
+ const answer = headerPattern.exec(header);
873
+ if (!answer) {
874
+ this.settle(session, NOTHING);
875
+ continue;
876
+ }
877
+ const size = Number(answer[2]);
878
+ session.expected = size + 1;
879
+ session.collected = answer[1] === "blob" && size <= this.maxBlobBytes ? [] : null;
880
+ }
881
+ const take = Math.min(session.buffered.length, session.expected);
882
+ session.collected?.push(session.buffered.subarray(0, take));
883
+ session.buffered = session.buffered.subarray(take);
884
+ session.expected -= take;
885
+ if (session.expected > 0) break;
886
+ const collected = session.collected;
887
+ session.expected = null;
888
+ session.collected = null;
889
+ this.settle(session, collected ? {
890
+ found: "blob",
891
+ blob: Buffer.concat(collected).subarray(0, -1)
892
+ } : { found: "other" });
893
+ }
894
+ this.armIdleTimer(session);
895
+ }
896
+ settle(session, value) {
897
+ session.pending.shift()?.resolve(value);
898
+ this.holdEventLoop(session);
899
+ }
900
+ /** Hold the loop only while a read is pending or a close is in progress. */
901
+ holdEventLoop(session) {
902
+ this.setEventLoopHold(session, session.pending.length > 0 || this.closed);
903
+ }
904
+ setEventLoopHold(session, hold) {
905
+ for (const handle of [
906
+ session.child,
907
+ session.child.stdin,
908
+ session.child.stdout
909
+ ]) if (hold) handle.ref();
910
+ else handle.unref();
911
+ }
912
+ fail(session, message, cause) {
913
+ if (this.session === session) {
914
+ this.session = null;
915
+ this.clearIdleTimer();
916
+ }
917
+ for (const read of session.pending.splice(0)) read.reject(cause ? new Error(message, { cause }) : new Error(message));
918
+ this.holdEventLoop(session);
919
+ }
920
+ write(session, request) {
921
+ const stdin = session.child.stdin;
922
+ if (!stdin.writable) return Promise.resolve();
923
+ return new Promise((resolve) => {
924
+ if (stdin.write(request)) {
925
+ resolve();
926
+ return;
927
+ }
928
+ const proceed = () => {
929
+ stdin.off("drain", proceed);
930
+ resolve();
931
+ };
932
+ stdin.once("drain", proceed);
933
+ session.exit.then(proceed);
934
+ });
935
+ }
936
+ get maxBlobBytes() {
937
+ return this.input.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES;
938
+ }
939
+ armIdleTimer(session) {
940
+ if (this.session !== session) return;
941
+ this.clearIdleTimer();
942
+ this.idleTimer = setTimeout(() => {
943
+ this.idleTimer = null;
944
+ if (session.pending.length > 0) {
945
+ this.armIdleTimer(session);
946
+ return;
947
+ }
948
+ this.retire(session);
949
+ }, this.input.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS);
950
+ this.idleTimer.unref();
951
+ }
952
+ clearIdleTimer() {
953
+ if (!this.idleTimer) return;
954
+ clearTimeout(this.idleTimer);
955
+ this.idleTimer = null;
956
+ }
957
+ /** Null the session before killing so its exit rejects nothing. */
958
+ retire(session) {
959
+ if (this.session === session) {
960
+ this.session = null;
961
+ this.clearIdleTimer();
962
+ }
963
+ session.child.kill();
964
+ }
965
+ };
966
+ //#endregion
967
+ //#region ../local-vcs/src/windows-path.ts
968
+ /**
969
+ * A Windows process keeps the PATH it launched with, so Git installed while
970
+ * Whiteboard runs is only in the saved system and user PATH. Merge those (and
971
+ * Git for Windows' usual location) into this process. Returns whether PATH
972
+ * gained any entries.
973
+ */
974
+ function refreshWindowsPath() {
975
+ if (process.platform !== "win32") return false;
976
+ const current = (process.env.PATH ?? "").split(";").filter(Boolean);
977
+ const known = new Set(current.map(normalizeEntry));
978
+ const added = [];
979
+ const candidates = [
980
+ ...savedPath("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"),
981
+ ...savedPath("HKCU\\Environment"),
982
+ path.join(process.env.ProgramFiles ?? "C:\\Program Files", "Git", "cmd")
983
+ ];
984
+ for (const entry of candidates) {
985
+ const key = normalizeEntry(entry);
986
+ if (known.has(key) || !fs.existsSync(entry)) continue;
987
+ known.add(key);
988
+ added.push(entry);
989
+ }
990
+ if (added.length === 0) return false;
991
+ process.env.PATH = [...current, ...added].join(";");
992
+ return true;
993
+ }
994
+ function savedPath(key) {
995
+ let output;
996
+ try {
997
+ output = execFileSync("reg.exe", [
998
+ "query",
999
+ key,
1000
+ "/v",
1001
+ "Path"
1002
+ ], {
1003
+ encoding: "utf8",
1004
+ windowsHide: true
1005
+ });
1006
+ } catch {
1007
+ return [];
1008
+ }
1009
+ return (output.match(/^\s*Path\s+REG_\w+\s*(.*)$/im)?.[1] ?? "").split(";").map((entry) => entry.trim().replace(/%([^%]+)%/g, (whole, name) => process.env[name] ?? whole)).filter(Boolean);
1010
+ }
1011
+ function normalizeEntry(entry) {
1012
+ return path.win32.resolve(entry).toLowerCase();
1013
+ }
1014
+ //#endregion
1015
+ //#region ../local-vcs/src/vcs.ts
1016
+ const LOCAL_GIT_ENV_KEYS = [
1017
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
1018
+ "GIT_COMMON_DIR",
1019
+ "GIT_CONFIG",
1020
+ "GIT_CONFIG_COUNT",
1021
+ "GIT_CONFIG_PARAMETERS",
1022
+ "GIT_DIR",
1023
+ "GIT_GRAFT_FILE",
1024
+ "GIT_IMPLICIT_WORK_TREE",
1025
+ "GIT_INDEX_FILE",
1026
+ "GIT_INTERNAL_SUPER_PREFIX",
1027
+ "GIT_NO_REPLACE_OBJECTS",
1028
+ "GIT_OBJECT_DIRECTORY",
1029
+ "GIT_PREFIX",
1030
+ "GIT_QUARANTINE_PATH",
1031
+ "GIT_REPLACE_REF_BASE",
1032
+ "GIT_SHALLOW_FILE",
1033
+ "GIT_WORK_TREE"
1034
+ ];
1035
+ /** Neither git nor jj could be started, so no folder can be recognized as a repository. */
1036
+ var LocalVcsToolsMissingError = class extends Error {
1037
+ constructor() {
1038
+ super(process.platform === "win32" ? "Git isn't installed or isn't on PATH. Install Git for Windows, then try again." : "Git isn't installed or isn't on PATH. Install Git, then try again.");
1039
+ this.name = "LocalVcsToolsMissingError";
1040
+ }
1041
+ };
1042
+ async function detectLocalVcs(rootPath) {
1043
+ const detected = await detectLocalVcsOnce(rootPath);
1044
+ if (detected !== TOOLS_MISSING) return detected;
1045
+ if (refreshWindowsPath()) {
1046
+ const retried = await detectLocalVcsOnce(rootPath);
1047
+ if (retried !== TOOLS_MISSING) return retried;
1048
+ }
1049
+ throw new LocalVcsToolsMissingError();
1050
+ }
1051
+ const TOOLS_MISSING = Symbol("tools missing");
1052
+ async function detectLocalVcsOnce(rootPath) {
1053
+ const resolvedRootPath = canonicalPath(rootPath);
1054
+ let missing = 0;
1055
+ const notStarted = (error) => {
1056
+ if (error.code === "ENOENT") missing++;
1057
+ return null;
1058
+ };
1059
+ const jjRoot = await commandOutput("jj", [
1060
+ "-R",
1061
+ resolvedRootPath,
1062
+ "root",
1063
+ "--ignore-working-copy"
1064
+ ], { cwd: resolvedRootPath }).catch(notStarted);
1065
+ if (jjRoot && isInsideDirectory(resolvedRootPath, canonicalPath(jjRoot))) return createLocalVcs("jj", canonicalPath(jjRoot));
1066
+ const gitRoot = await commandOutput("git", [
1067
+ "-C",
1068
+ resolvedRootPath,
1069
+ "rev-parse",
1070
+ "--show-toplevel"
1071
+ ], { cwd: resolvedRootPath }).catch(notStarted);
1072
+ if (gitRoot) return createLocalVcs("git", canonicalPath(gitRoot));
1073
+ return missing === 2 && fs.existsSync(resolvedRootPath) ? TOOLS_MISSING : null;
1074
+ }
1075
+ /** Skip detection when the caller already holds a handle for this root. */
1076
+ async function knownOrDetectedVcs(rootPath, kind) {
1077
+ return kind ? createLocalVcs(kind, rootPath) : detectLocalVcs(rootPath);
1078
+ }
1079
+ /**
1080
+ * Resolve the repository's shared git directory ($GIT_COMMON_DIR) so all
1081
+ * worktrees agree on one object database and one refs namespace. Follows the
1082
+ * same jj-first preference as detectLocalVcs: a non-colocated jj workspace
1083
+ * nested inside another git repo must resolve to its jj backing store
1084
+ * (`jj git root`), not the OUTER repo's git dir via plain git. Colocated jj
1085
+ * repos have a real .git and resolve to it through either path.
1086
+ */
1087
+ async function gitCommonDir(rootPath) {
1088
+ const key = path.resolve(rootPath);
1089
+ return await commandOutput("jj", [
1090
+ "git",
1091
+ "root",
1092
+ "--ignore-working-copy"
1093
+ ], { cwd: key }).catch(() => null) || await commandOutput("git", [
1094
+ "-C",
1095
+ key,
1096
+ "rev-parse",
1097
+ "--path-format=absolute",
1098
+ "--git-common-dir"
1099
+ ], { cwd: key }).catch(() => null) || null;
1100
+ }
1101
+ function gitCommonDirSync(rootPath) {
1102
+ const key = path.resolve(rootPath);
1103
+ return commandOutputSync("jj", [
1104
+ "git",
1105
+ "root",
1106
+ "--ignore-working-copy"
1107
+ ], { cwd: key }) || commandOutputSync("git", [
1108
+ "-C",
1109
+ key,
1110
+ "rev-parse",
1111
+ "--path-format=absolute",
1112
+ "--git-common-dir"
1113
+ ], { cwd: key }) || null;
1114
+ }
1115
+ /**
1116
+ * Resolve the repository identity through its jj-first shared Git directory.
1117
+ * Remote lookup must never rely on Git's cwd walk: a non-colocated jj
1118
+ * workspace may be nested inside an unrelated Git repository.
1119
+ */
1120
+ async function resolveRepoContext(rootPath) {
1121
+ const commonDir = await gitCommonDir(path.resolve(rootPath));
1122
+ if (!commonDir) return null;
1123
+ const [originUrl, resolvedOriginUrl] = await Promise.all([commandOutput("git", [
1124
+ "--git-dir",
1125
+ commonDir,
1126
+ "config",
1127
+ "--get",
1128
+ "remote.origin.url"
1129
+ ]).catch(() => null), commandOutput("git", [
1130
+ "--git-dir",
1131
+ commonDir,
1132
+ "remote",
1133
+ "get-url",
1134
+ "origin"
1135
+ ]).catch(() => null)]);
1136
+ return {
1137
+ commonDir,
1138
+ originUrl: originUrl || null,
1139
+ githubSlug: (resolvedOriginUrl ? parseGitRemoteSlug(resolvedOriginUrl) : null) ?? (originUrl ? parseGitRemoteSlug(originUrl) : null)
1140
+ };
1141
+ }
1142
+ function resolveRepoContextSync(rootPath) {
1143
+ const commonDir = gitCommonDirSync(path.resolve(rootPath));
1144
+ if (!commonDir) return null;
1145
+ const originUrl = commandOutputSync("git", [
1146
+ "--git-dir",
1147
+ commonDir,
1148
+ "config",
1149
+ "--get",
1150
+ "remote.origin.url"
1151
+ ]) || null;
1152
+ const resolvedOriginUrl = commandOutputSync("git", [
1153
+ "--git-dir",
1154
+ commonDir,
1155
+ "remote",
1156
+ "get-url",
1157
+ "origin"
1158
+ ]) || null;
1159
+ return {
1160
+ commonDir,
1161
+ originUrl,
1162
+ githubSlug: (resolvedOriginUrl ? parseGitRemoteSlug(resolvedOriginUrl) : null) ?? (originUrl ? parseGitRemoteSlug(originUrl) : null)
1163
+ };
1164
+ }
1165
+ /** git argv for the object store: a jj workspace reads through its backing store. */
1166
+ async function objectStoreArgs(input) {
1167
+ if (input.kind === "git") return ["-C", input.rootPath];
1168
+ const gitDir = await gitCommonDir(input.rootPath);
1169
+ return gitDir ? ["--git-dir", gitDir] : ["-C", input.rootPath];
1170
+ }
1171
+ function createBlobBatchReader(input) {
1172
+ return new BlobBatchReader({
1173
+ objectStoreArgs: () => objectStoreArgs(input),
1174
+ env: localGitEnvironment(),
1175
+ idleTimeoutMs: input.idleTimeoutMs
1176
+ });
1177
+ }
1178
+ /** Git argv prefix that pins a command to the repo's shared git dir. */
1179
+ async function gitArgs(rootPath, args) {
1180
+ const gitDir = await gitCommonDir(rootPath);
1181
+ if (!gitDir) throw new Error(`No git repository found at ${rootPath}`);
1182
+ return [
1183
+ "--git-dir",
1184
+ gitDir,
1185
+ ...args
1186
+ ];
1187
+ }
1188
+ /** Run git against the repo's shared git dir, optionally tolerating failure. */
1189
+ async function git(rootPath, args, options = {}) {
1190
+ try {
1191
+ const { stdout, stderr } = await execFileAsync("git", await gitArgs(rootPath, args), {
1192
+ maxBuffer: 67108864,
1193
+ signal: options.signal
1194
+ });
1195
+ return {
1196
+ ok: true,
1197
+ stdout,
1198
+ stderr
1199
+ };
1200
+ } catch (error) {
1201
+ if (options.allowFailure) {
1202
+ const err = error;
1203
+ return {
1204
+ ok: false,
1205
+ stdout: err.stdout ?? "",
1206
+ stderr: err.stderr ?? String(error)
1207
+ };
1208
+ }
1209
+ throw error;
1210
+ }
1211
+ }
1212
+ /**
1213
+ * Run git from a working directory, as `git -C <cwd>` does. Unlike `git()`,
1214
+ * which pins the shared git dir, this resolves HEAD, the index, and local
1215
+ * config for the worktree that owns `cwd`.
1216
+ */
1217
+ async function gitAt(cwd, args, options = {}) {
1218
+ try {
1219
+ const { stdout, stderr } = await execFileAsync("git", [
1220
+ "-C",
1221
+ cwd,
1222
+ ...args
1223
+ ], {
1224
+ maxBuffer: 67108864,
1225
+ signal: options.signal,
1226
+ env: options.env,
1227
+ timeout: options.timeout
1228
+ });
1229
+ return {
1230
+ ok: true,
1231
+ stdout,
1232
+ stderr
1233
+ };
1234
+ } catch (error) {
1235
+ if (options.allowFailure) {
1236
+ const err = error;
1237
+ return {
1238
+ ok: false,
1239
+ stdout: err.stdout ?? "",
1240
+ stderr: err.stderr ?? String(error)
1241
+ };
1242
+ }
1243
+ throw error;
1244
+ }
1245
+ }
1246
+ function createLocalVcs(kind, rootPath) {
1247
+ return {
1248
+ kind,
1249
+ rootPath,
1250
+ currentHead: () => currentHeadForKind(rootPath, kind),
1251
+ resolveRevision: (revision) => resolveRevisionForKind(rootPath, revision, kind),
1252
+ defaultBranch: () => defaultBranchForKind(rootPath, kind),
1253
+ mergeBase: (baseRef, headRef) => mergeBaseForKind({
1254
+ rootPath,
1255
+ baseRef,
1256
+ headRef,
1257
+ kind
1258
+ }),
1259
+ listTrackedFiles: (revision) => Promise.resolve(listTrackedFilesForKind({
1260
+ rootPath,
1261
+ ref: revision,
1262
+ kind
1263
+ })),
1264
+ readFileAtRef: (ref, relativePath) => Promise.resolve(readFileAtRevisionForKind({
1265
+ rootPath,
1266
+ ref,
1267
+ relativePath,
1268
+ kind
1269
+ })?.source ?? null),
1270
+ diff: (input) => diffForKind({
1271
+ rootPath,
1272
+ baseRef: input.base,
1273
+ headRef: input.head,
1274
+ contextLines: input.contextLines,
1275
+ paths: input.paths,
1276
+ kind
1277
+ }),
1278
+ diffNameStatus: async (input) => toNameStatusEntries(await diffNameStatusForKind({
1279
+ rootPath,
1280
+ baseRef: input.base,
1281
+ headRef: input.head,
1282
+ mergeBase: input.mergeBase,
1283
+ kind
1284
+ })),
1285
+ diffFileSummaries: (input) => diffFileSummariesForKind({
1286
+ rootPath,
1287
+ baseRef: input.base,
1288
+ headRef: input.head,
1289
+ paths: input.paths,
1290
+ kind
1291
+ }),
1292
+ githubRemoteSlug: () => githubRemoteSlug(rootPath)
1293
+ };
1294
+ }
1295
+ /**
1296
+ * Whether a revision carries unresolved jj conflicts. jj materializes
1297
+ * conflict markers into the git export of such commits, so a downstream git
1298
+ * checkout would silently contain marker text instead of code. Returns null
1299
+ * when the repository is not jj (git commits cannot be conflicted) or when
1300
+ * jj cannot answer — callers must only act on a definite true.
1301
+ */
1302
+ async function jjRevisionIsConflicted(rootPath, revision) {
1303
+ if ((await detectLocalVcs(rootPath))?.kind !== "jj") return null;
1304
+ try {
1305
+ const { stdout } = await execFileAsync("jj", [
1306
+ "log",
1307
+ "-r",
1308
+ revision,
1309
+ "--no-graph",
1310
+ "-T",
1311
+ "if(conflict, \"true\", \"false\")",
1312
+ "--ignore-working-copy"
1313
+ ], { cwd: rootPath });
1314
+ const value = stdout.trim();
1315
+ return value === "true" ? true : value === "false" ? false : null;
1316
+ } catch {
1317
+ return null;
1318
+ }
1319
+ }
1320
+ async function resolveRevision(rootPath, revision) {
1321
+ const vcs = await detectLocalVcs(rootPath);
1322
+ if (!vcs) return null;
1323
+ return vcs.resolveRevision(revision);
1324
+ }
1325
+ async function currentHeadForKind(rootPath, kind) {
1326
+ return resolveRevisionForKind(rootPath, kind === "jj" ? "@" : "HEAD", kind);
1327
+ }
1328
+ async function resolveRevisionForKind(rootPath, revision, kind) {
1329
+ const commit = await resolveRevisionCommitByPreference(rootPath, revision, kind);
1330
+ return commit ? { commit } : null;
1331
+ }
1332
+ /**
1333
+ * The default branch as a re-resolvable NAME (e.g. "origin/main" or "main"),
1334
+ * or null when no candidate resolves. Callers that must store a base ref a
1335
+ * later update can re-derive from should prefer this over the resolved
1336
+ * commit, which freezes the fork point forever.
1337
+ */
1338
+ async function defaultBranchForKind(rootPath, kind) {
1339
+ const candidates = await defaultBranchCandidates(rootPath);
1340
+ for (const candidate of candidates) {
1341
+ const commit = await resolveRevisionCommitByPreference(rootPath, candidate, kind);
1342
+ if (commit) return {
1343
+ ref: candidate,
1344
+ commit
1345
+ };
1346
+ }
1347
+ return null;
1348
+ }
1349
+ async function mergeBaseForKind(input) {
1350
+ const commit = await mergeBaseByPreference(input.rootPath, input.baseRef, input.headRef, input.kind);
1351
+ return commit ? { commit } : null;
1352
+ }
1353
+ async function listTrackedFilesAtCommit(input) {
1354
+ if (input.kind === "jj") {
1355
+ const output = await commandOutput("jj", [
1356
+ "-R",
1357
+ input.rootPath,
1358
+ "file",
1359
+ "list",
1360
+ "--ignore-working-copy",
1361
+ "-r",
1362
+ input.commit
1363
+ ], { cwd: input.rootPath }).catch(() => null);
1364
+ if (output !== null) return splitLines(output);
1365
+ if (!await canUseGitFallback(input.rootPath, input.kind)) return [];
1366
+ }
1367
+ const output = await commandOutput("git", [
1368
+ "-C",
1369
+ input.rootPath,
1370
+ "ls-tree",
1371
+ "-r",
1372
+ "-z",
1373
+ "--name-only",
1374
+ input.commit
1375
+ ], { cwd: input.rootPath }).catch(() => null);
1376
+ return output === null ? [] : output.split("\0").filter(Boolean);
1377
+ }
1378
+ function listTrackedFilesForKind(input) {
1379
+ if (input.kind === "jj") {
1380
+ const args = [
1381
+ "-R",
1382
+ input.rootPath,
1383
+ "file",
1384
+ "list",
1385
+ "--ignore-working-copy"
1386
+ ];
1387
+ if (input.ref) args.push("-r", input.ref);
1388
+ const output = commandOutputSync("jj", args, { cwd: input.rootPath });
1389
+ if (output !== null) return splitLines(output);
1390
+ if (!canUseGitFallbackSync(input.rootPath, input.kind)) return [];
1391
+ }
1392
+ const output = input.ref ? commandOutputSync("git", [
1393
+ "-C",
1394
+ input.rootPath,
1395
+ "ls-tree",
1396
+ "-r",
1397
+ "-z",
1398
+ "--name-only",
1399
+ input.ref
1400
+ ], { cwd: input.rootPath }) : commandOutputSync("git", [
1401
+ "-C",
1402
+ input.rootPath,
1403
+ "ls-files",
1404
+ "-z"
1405
+ ], { cwd: input.rootPath });
1406
+ if (output === null) return [];
1407
+ return output.split("\0").filter(Boolean);
1408
+ }
1409
+ /**
1410
+ * Read a blob at a resolved commit through the caller's batch reader.
1411
+ * jj conflicted revisions go through `jj file show`: the git tree holds one side only.
1412
+ * Null for a missing commit or path, or a non-blob (a directory).
1413
+ */
1414
+ async function readFileAtCommit(input) {
1415
+ if (input.reader) return readFileWithReader(input, input.reader);
1416
+ const reader = createBlobBatchReader({
1417
+ rootPath: input.rootPath,
1418
+ kind: input.kind
1419
+ });
1420
+ try {
1421
+ return await readFileWithReader(input, reader);
1422
+ } finally {
1423
+ await reader.close();
1424
+ }
1425
+ }
1426
+ async function readFileWithReader(input, reader) {
1427
+ if (input.kind === "jj" && await jjCommitIsConflicted(reader, input.commit)) return readJjFileAtCommit(input);
1428
+ const answer = await reader.readObject(input.commit, input.relativePath).catch(() => ({ found: "nothing" }));
1429
+ if (answer.found === "blob") return answer.blob.toString("utf8");
1430
+ if (answer.found === "other" || input.kind !== "jj") return null;
1431
+ return readJjFileAtCommit(input);
1432
+ }
1433
+ async function readJjFileAtCommit(input) {
1434
+ return commandOutput("jj", [
1435
+ "-R",
1436
+ input.rootPath,
1437
+ "file",
1438
+ "show",
1439
+ "-r",
1440
+ input.commit,
1441
+ "--ignore-working-copy",
1442
+ "--",
1443
+ toJjRootFilePattern(input.relativePath)
1444
+ ], {
1445
+ cwd: input.rootPath,
1446
+ maxBuffer: 10485760,
1447
+ trim: false
1448
+ }).catch(() => null);
1449
+ }
1450
+ /** jj writes this README into a conflicted commit; remembered per (immutable) commit. */
1451
+ const JJ_CONFLICT_MARKER = "JJ-CONFLICT-README";
1452
+ const jjConflictedCommits = /* @__PURE__ */ new WeakMap();
1453
+ async function jjCommitIsConflicted(reader, commit) {
1454
+ let known = jjConflictedCommits.get(reader);
1455
+ if (!known) {
1456
+ known = /* @__PURE__ */ new Map();
1457
+ jjConflictedCommits.set(reader, known);
1458
+ }
1459
+ const answered = known.get(commit);
1460
+ if (answered) return answered;
1461
+ const probe = reader.read(commit, JJ_CONFLICT_MARKER).then((marker) => marker !== null, () => false);
1462
+ known.set(commit, probe);
1463
+ return probe;
1464
+ }
1465
+ function readFileAtRevisionForKind(input) {
1466
+ return input.kind === "jj" ? readJjFileAtRevisionSync(input) ?? (canUseGitFallbackSync(input.rootPath, input.kind) ? readGitFileAtRevisionSync(input) : null) : readGitFileAtRevisionSync(input) ?? readJjFileAtRevisionSync(input);
1467
+ }
1468
+ async function diff(input) {
1469
+ const vcs = await knownOrDetectedVcs(input.rootPath, input.kind);
1470
+ if (!vcs) throw new Error(`No Git or jj repository found for ${input.rootPath}.`);
1471
+ return diffForKind({
1472
+ ...input,
1473
+ rootPath: vcs.rootPath,
1474
+ kind: vcs.kind
1475
+ });
1476
+ }
1477
+ /** Use the same summary parser for working files and committed trees. */
1478
+ function diffFileSummariesWorkingTree(input) {
1479
+ return withWorkingTreeIndex(input, readGitDiffFileSummaries);
1480
+ }
1481
+ /** Read one Git patch for the entire checkout, or for the named changed files. */
1482
+ function diffWorkingTree(input) {
1483
+ return withWorkingTreeIndex(input, async (options) => {
1484
+ const read = {
1485
+ ...options,
1486
+ contextLines: input.contextLines
1487
+ };
1488
+ if (input.paths === void 0) return readGitDiff(read);
1489
+ const requested = new Set(input.paths);
1490
+ const previous = (await readGitDiffFileSummaries(options)).flatMap((change) => change.previousPath && requested.has(change.path) ? [change.previousPath] : []);
1491
+ return readGitDiff({
1492
+ ...read,
1493
+ literalPaths: true,
1494
+ paths: [.../* @__PURE__ */ new Set([...previous, ...input.paths])]
1495
+ });
1496
+ });
1497
+ }
1498
+ /** A private index and object store compare the working tree without staging user files. */
1499
+ async function withWorkingTreeIndex(input, read) {
1500
+ const scratch = await fs.promises.mkdtemp(path.join(tmpdir(), "review-git-diff-"));
1501
+ try {
1502
+ const common = await gitCommonDir(input.rootPath);
1503
+ if (!common) throw new Error("Working source requires a Git-backed repository.");
1504
+ const env = {
1505
+ ...localGitEnvironment(),
1506
+ GIT_INDEX_FILE: path.join(scratch, "index"),
1507
+ GIT_OBJECT_DIRECTORY: path.join(scratch, "objects"),
1508
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: JSON.stringify(path.join(common, "objects")),
1509
+ GIT_OPTIONAL_LOCKS: "0"
1510
+ };
1511
+ if (input.kind === "jj") {
1512
+ env.GIT_DIR = common;
1513
+ env.GIT_WORK_TREE = input.rootPath;
1514
+ }
1515
+ await fs.promises.mkdir(path.join(scratch, "objects"));
1516
+ const git = (args) => execFileAsync("git", [
1517
+ "-c",
1518
+ "core.splitIndex=false",
1519
+ "-C",
1520
+ input.rootPath,
1521
+ ...args
1522
+ ], {
1523
+ env,
1524
+ cwd: input.rootPath,
1525
+ maxBuffer: 33554432
1526
+ });
1527
+ if (input.kind === "git") {
1528
+ const index = (await execFileAsync("git", [
1529
+ "-C",
1530
+ input.rootPath,
1531
+ "rev-parse",
1532
+ "--path-format=absolute",
1533
+ "--git-path",
1534
+ "index"
1535
+ ], { env: localGitEnvironment() })).stdout.trim();
1536
+ try {
1537
+ const copy = path.join(scratch, "index");
1538
+ await fs.promises.copyFile(index, copy);
1539
+ const { atime, mtime } = await fs.promises.stat(index);
1540
+ await fs.promises.utimes(copy, atime, mtime);
1541
+ } catch (error) {
1542
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
1543
+ }
1544
+ } else if (input.headRef) await git(["read-tree", input.headRef]);
1545
+ if (input.kind === "jj") await git([
1546
+ "add",
1547
+ "--intent-to-add",
1548
+ "--all",
1549
+ "--",
1550
+ ".",
1551
+ ":(exclude).jj"
1552
+ ]);
1553
+ await fs.promises.writeFile(path.join(scratch, "empty"), "");
1554
+ const baseRef = input.baseRef ?? (await git([
1555
+ "hash-object",
1556
+ "-w",
1557
+ "-t",
1558
+ "tree",
1559
+ path.join(scratch, "empty")
1560
+ ])).stdout.trim();
1561
+ return await read({
1562
+ rootPath: input.rootPath,
1563
+ baseRef,
1564
+ env
1565
+ });
1566
+ } finally {
1567
+ await fs.promises.rm(scratch, {
1568
+ recursive: true,
1569
+ force: true
1570
+ });
1571
+ }
1572
+ }
1573
+ /** Compare two exact Git trees without merge-base semantics. */
1574
+ async function diffTrees(input) {
1575
+ const vcs = await knownOrDetectedVcs(input.rootPath, input.kind);
1576
+ if (!vcs) throw new Error(`No Git or jj repository found for ${input.rootPath}.`);
1577
+ return diffForKind({
1578
+ ...input,
1579
+ rootPath: vcs.rootPath,
1580
+ kind: vcs.kind,
1581
+ mergeBase: false
1582
+ });
1583
+ }
1584
+ async function diffFileSummaries(input) {
1585
+ const vcs = await detectLocalVcs(input.rootPath);
1586
+ if (!vcs) throw new Error(`No Git or jj repository found for ${input.rootPath}.`);
1587
+ return diffFileSummariesForKind({
1588
+ ...input,
1589
+ rootPath: vcs.rootPath,
1590
+ kind: vcs.kind
1591
+ });
1592
+ }
1593
+ /** List commits in base..head order, newest first, with first-parent stats. */
1594
+ async function listCommitRange(input) {
1595
+ const vcs = await knownOrDetectedVcs(input.rootPath, input.kind);
1596
+ if (!vcs) throw new Error(`No Git or jj repository found for ${input.rootPath}.`);
1597
+ try {
1598
+ const { stdout } = await execFileAsync("git", [
1599
+ "-C",
1600
+ vcs.rootPath,
1601
+ "log",
1602
+ "--topo-order",
1603
+ "--format=%H%x00%P%x00%an%x00%aI%x00%s%x00",
1604
+ "--numstat",
1605
+ "-z",
1606
+ `${input.baseRef}..${input.headRef}`
1607
+ ], {
1608
+ cwd: vcs.rootPath,
1609
+ maxBuffer: 26214400
1610
+ });
1611
+ return parseGitCommitRange(stdout);
1612
+ } catch (error) {
1613
+ if (vcs.kind !== "jj") throw error;
1614
+ return readJjCommitRange(vcs.rootPath, input.baseRef, input.headRef);
1615
+ }
1616
+ }
1617
+ function parseGitCommitRange(output) {
1618
+ const fields = output.split("\0");
1619
+ const commits = [];
1620
+ let index = 0;
1621
+ while (index < fields.length) {
1622
+ const commit = fields[index++]?.replace(/^\n+/u, "") ?? "";
1623
+ if (!/^[0-9a-f]{40}$/iu.test(commit)) continue;
1624
+ const parentCommit = (fields[index++] ?? "").split(" ")[0] ?? "";
1625
+ const author = fields[index++] ?? "";
1626
+ const authoredAt = fields[index++] ?? "";
1627
+ const subject = fields[index++] ?? "";
1628
+ if (fields[index] === "") index += 1;
1629
+ let fileCount = 0;
1630
+ let additions = 0;
1631
+ let deletions = 0;
1632
+ while (index < fields.length) {
1633
+ const field = fields[index]?.replace(/^\n+/u, "") ?? "";
1634
+ if (/^[0-9a-f]{40}$/iu.test(field)) break;
1635
+ index += 1;
1636
+ if (!field) continue;
1637
+ const [rawAdditions, rawDeletions, filePath] = field.split(" ");
1638
+ if (rawDeletions === void 0) continue;
1639
+ fileCount += 1;
1640
+ additions += parseGitNumStatCount(rawAdditions);
1641
+ deletions += parseGitNumStatCount(rawDeletions);
1642
+ if (!filePath) index += 2;
1643
+ }
1644
+ if (!parentCommit || !authoredAt) continue;
1645
+ commits.push({
1646
+ commit,
1647
+ parentCommit,
1648
+ subject,
1649
+ author,
1650
+ authoredAt,
1651
+ fileCount,
1652
+ additions,
1653
+ deletions
1654
+ });
1655
+ }
1656
+ return commits;
1657
+ }
1658
+ async function readJjCommitRange(rootPath, baseRef, headRef) {
1659
+ const fields = (await commandOutput("jj", [
1660
+ "-R",
1661
+ rootPath,
1662
+ "--no-pager",
1663
+ "log",
1664
+ "--no-graph",
1665
+ "-r",
1666
+ `::${headRef} ~ ::${baseRef}`,
1667
+ "-T",
1668
+ "commit_id ++ \"\\0\" ++ parents.map(|p| p.commit_id()).join(\" \") ++ \"\\0\" ++ author.name() ++ \"\\0\" ++ author.timestamp().format(\"%+\") ++ \"\\0\" ++ description.first_line() ++ \"\\0\"",
1669
+ "--ignore-working-copy"
1670
+ ], {
1671
+ cwd: rootPath,
1672
+ maxBuffer: 26214400,
1673
+ trim: false
1674
+ })).split("\0");
1675
+ const metadata = [];
1676
+ for (let index = 0; index + 4 < fields.length; index += 5) {
1677
+ const commit = fields[index]?.trim() ?? "";
1678
+ const parentCommit = (fields[index + 1] ?? "").split(" ")[0] ?? "";
1679
+ if (!commit || !parentCommit) continue;
1680
+ metadata.push({
1681
+ commit,
1682
+ parentCommit,
1683
+ author: fields[index + 2] ?? "",
1684
+ authoredAt: fields[index + 3] ?? "",
1685
+ subject: fields[index + 4] ?? ""
1686
+ });
1687
+ }
1688
+ return Promise.all(metadata.map(async (entry) => {
1689
+ const files = await diffFileSummariesForKind({
1690
+ rootPath,
1691
+ baseRef: entry.parentCommit,
1692
+ headRef: entry.commit,
1693
+ mergeBase: false,
1694
+ kind: "jj"
1695
+ });
1696
+ return {
1697
+ ...entry,
1698
+ fileCount: files.length,
1699
+ additions: files.reduce((total, file) => total + file.additions, 0),
1700
+ deletions: files.reduce((total, file) => total + file.deletions, 0)
1701
+ };
1702
+ }));
1703
+ }
1704
+ /** Summarize changes between two exact Git trees. */
1705
+ async function diffFileSummariesTrees(input) {
1706
+ const vcs = await knownOrDetectedVcs(input.rootPath, input.kind);
1707
+ if (!vcs) throw new Error(`No Git or jj repository found for ${input.rootPath}.`);
1708
+ return diffFileSummariesForKind({
1709
+ ...input,
1710
+ rootPath: vcs.rootPath,
1711
+ kind: vcs.kind,
1712
+ mergeBase: false
1713
+ });
1714
+ }
1715
+ async function diffForKind(input) {
1716
+ if (input.kind === "jj") return readJjDiff(input).catch((cause) => {
1717
+ if (!canUseGitFallbackSync(input.rootPath, input.kind)) throw cause;
1718
+ return readGitDiff(input);
1719
+ });
1720
+ return readGitDiff(input).catch(() => readJjDiff(input));
1721
+ }
1722
+ async function diffFileSummariesForKind(input) {
1723
+ const requestedPaths = normalizeDiffPaths(input.paths);
1724
+ const unfilteredInput = {
1725
+ ...input,
1726
+ paths: void 0
1727
+ };
1728
+ let summaries;
1729
+ if (input.kind === "jj") {
1730
+ if (canUseGitFallbackSync(input.rootPath, input.kind)) try {
1731
+ summaries = await readGitDiffFileSummaries(unfilteredInput);
1732
+ return filterDiffFileSummaries(summaries, requestedPaths);
1733
+ } catch {}
1734
+ summaries = parseGitPatchFileSummaries(await readJjDiff(unfilteredInput));
1735
+ return filterDiffFileSummaries(summaries, requestedPaths);
1736
+ }
1737
+ summaries = await readGitDiffFileSummaries(unfilteredInput).catch(async () => parseGitPatchFileSummaries(await readJjDiff(unfilteredInput)));
1738
+ return filterDiffFileSummaries(summaries, requestedPaths);
1739
+ }
1740
+ async function diffNameStatusForKind(input) {
1741
+ if (input.kind === "jj") return readJjDiffNameStatus(input).catch((cause) => {
1742
+ if (!canUseGitFallbackSync(input.rootPath, input.kind)) throw cause;
1743
+ return readGitDiffNameStatus(input);
1744
+ });
1745
+ return readGitDiffNameStatus(input).catch(() => readJjDiffNameStatus(input));
1746
+ }
1747
+ async function githubRemoteSlug(rootPath) {
1748
+ return (await resolveRepoContext(rootPath))?.githubSlug ?? null;
1749
+ }
1750
+ function parseGitRemote(remote) {
1751
+ const value = remote.trim();
1752
+ if (!value) return null;
1753
+ try {
1754
+ const parsed = (0, import_lib.default)(value);
1755
+ const host = parsed.resource.trim().toLowerCase();
1756
+ const owner = parsed.owner.trim();
1757
+ const repo = parsed.name.trim().replace(/\.git$/u, "");
1758
+ const port = parsed.port ? Number(parsed.port) : null;
1759
+ if (!host || !owner || !repo || port !== null && !Number.isInteger(port)) return null;
1760
+ return {
1761
+ protocol: parsed.protocol,
1762
+ host,
1763
+ port,
1764
+ owner,
1765
+ repo,
1766
+ slug: `${owner}/${repo}`
1767
+ };
1768
+ } catch {
1769
+ return null;
1770
+ }
1771
+ }
1772
+ /**
1773
+ * Return an owner/repo slug only for a trusted GitHub host.
1774
+ *
1775
+ * `git remote get-url` expands Git `url.*.insteadOf` aliases before this
1776
+ * function sees the value. OpenSSH `Host` aliases are not expanded by Git, so
1777
+ * callers must explicitly list a trusted alias or GitHub Enterprise hostname
1778
+ * in `githubHosts`.
1779
+ */
1780
+ function parseGitRemoteSlug(remote, options = {}) {
1781
+ const parsed = parseGitRemote(remote);
1782
+ if (!parsed) return null;
1783
+ return new Set(["github.com", ...options.githubHosts ?? []].map((host) => host.toLowerCase())).has(parsed.host) ? parsed.slug : null;
1784
+ }
1785
+ function parseGitDiffNameStatus(output) {
1786
+ const changedFiles = /* @__PURE__ */ new Set();
1787
+ const deletedFiles = /* @__PURE__ */ new Set();
1788
+ for (const line of output.split(/\r?\n/)) {
1789
+ if (!line.trim()) continue;
1790
+ const [status, firstPath, secondPath] = line.split(" ");
1791
+ if (!status || !firstPath) continue;
1792
+ const kind = status[0];
1793
+ if (kind === "D") {
1794
+ deletedFiles.add(firstPath);
1795
+ continue;
1796
+ }
1797
+ if (kind === "R") {
1798
+ deletedFiles.add(firstPath);
1799
+ if (secondPath) changedFiles.add(secondPath);
1800
+ continue;
1801
+ }
1802
+ if (kind === "C") {
1803
+ changedFiles.add(secondPath ?? firstPath);
1804
+ continue;
1805
+ }
1806
+ changedFiles.add(firstPath);
1807
+ }
1808
+ return {
1809
+ changedFiles: [...changedFiles].sort(),
1810
+ deletedFiles: [...deletedFiles].sort()
1811
+ };
1812
+ }
1813
+ function parseJjDiffSummary(output) {
1814
+ const changedFiles = /* @__PURE__ */ new Set();
1815
+ const deletedFiles = /* @__PURE__ */ new Set();
1816
+ for (const line of output.split(/\r?\n/)) {
1817
+ if (!line.trim()) continue;
1818
+ const status = line[0];
1819
+ const file = line.slice(2).trim();
1820
+ if (!file) continue;
1821
+ if (status === "D") deletedFiles.add(file);
1822
+ else changedFiles.add(file);
1823
+ }
1824
+ return {
1825
+ changedFiles: [...changedFiles].sort(),
1826
+ deletedFiles: [...deletedFiles].sort()
1827
+ };
1828
+ }
1829
+ function toNameStatusEntries(summary) {
1830
+ return [...summary.changedFiles.map((path) => ({
1831
+ path,
1832
+ status: "modified"
1833
+ })), ...summary.deletedFiles.map((path) => ({
1834
+ path,
1835
+ status: "deleted"
1836
+ }))].sort((left, right) => left.path.localeCompare(right.path));
1837
+ }
1838
+ async function readGitDiffNameStatus(input) {
1839
+ const refRange = input.mergeBase === false ? [input.baseRef, input.headRef] : [`${input.baseRef}...${input.headRef}`];
1840
+ return parseGitDiffNameStatus(await commandOutput("git", [
1841
+ "-C",
1842
+ input.rootPath,
1843
+ "diff",
1844
+ "--name-status",
1845
+ "--diff-filter=ACDMRTUXB",
1846
+ ...refRange,
1847
+ "--"
1848
+ ], {
1849
+ cwd: input.rootPath,
1850
+ maxBuffer: 26214400
1851
+ }));
1852
+ }
1853
+ async function readJjDiffNameStatus(input) {
1854
+ return parseJjDiffSummary(await commandOutput("jj", [
1855
+ "-R",
1856
+ input.rootPath,
1857
+ "diff",
1858
+ "--summary",
1859
+ "--from",
1860
+ input.baseRef,
1861
+ "--to",
1862
+ input.headRef,
1863
+ "--ignore-working-copy"
1864
+ ], {
1865
+ cwd: input.rootPath,
1866
+ maxBuffer: 26214400
1867
+ }));
1868
+ }
1869
+ function toJjRootFilePattern(filePath) {
1870
+ return `root-file:${JSON.stringify(filePath).replace(/\\(.)/g, (escape, char) => char === "b" ? "\\u0008" : char === "f" ? "\\u000c" : escape)}`;
1871
+ }
1872
+ async function defaultBranchCandidates(rootPath) {
1873
+ return uniqueStrings([
1874
+ await commandOutput("git", [
1875
+ "-C",
1876
+ rootPath,
1877
+ "symbolic-ref",
1878
+ "--quiet",
1879
+ "--short",
1880
+ "refs/remotes/origin/HEAD"
1881
+ ], { cwd: rootPath }).catch(() => null),
1882
+ "origin/main",
1883
+ "origin/master",
1884
+ "main",
1885
+ "master"
1886
+ ]);
1887
+ }
1888
+ async function resolveRevisionCommitByPreference(rootPath, revision, preferred) {
1889
+ const primary = preferred === "jj" ? resolveJjRevisionCommit : resolveGitRevisionCommit;
1890
+ const secondary = preferred === "jj" ? resolveGitRevisionCommit : resolveJjRevisionCommit;
1891
+ return await primary(rootPath, revision).catch(() => null) ?? (canUseGitFallbackSync(rootPath, preferred) ? await secondary(rootPath, revision).catch(() => null) : null);
1892
+ }
1893
+ async function mergeBaseByPreference(rootPath, baseRef, headRef, preferred) {
1894
+ const primary = preferred === "jj" ? resolveJjMergeBase : resolveGitMergeBase;
1895
+ const secondary = preferred === "jj" ? resolveGitMergeBase : resolveJjMergeBase;
1896
+ return await primary(rootPath, baseRef, headRef).catch(() => null) ?? (canUseGitFallbackSync(rootPath, preferred) ? await secondary(rootPath, baseRef, headRef).catch(() => null) : null);
1897
+ }
1898
+ async function resolveGitRevisionCommit(rootPath, revision) {
1899
+ return commandOutput("git", [
1900
+ "-C",
1901
+ rootPath,
1902
+ "rev-parse",
1903
+ "--verify",
1904
+ `${revision}^{commit}`
1905
+ ]);
1906
+ }
1907
+ function resolveGitRevisionCommitSync(rootPath, revision) {
1908
+ return commandOutputSync("git", [
1909
+ "-C",
1910
+ rootPath,
1911
+ "rev-parse",
1912
+ "--verify",
1913
+ `${revision}^{commit}`
1914
+ ]);
1915
+ }
1916
+ async function resolveJjRevisionCommit(rootPath, revision) {
1917
+ return oneResolvedCommit(await commandOutput("jj", [
1918
+ "-R",
1919
+ rootPath,
1920
+ "log",
1921
+ "--no-graph",
1922
+ "-r",
1923
+ revision,
1924
+ "-T",
1925
+ "commit_id ++ \"\\n\"",
1926
+ "--ignore-working-copy"
1927
+ ], { cwd: rootPath }), revision);
1928
+ }
1929
+ function resolveJjRevisionCommitSync(rootPath, revision) {
1930
+ const output = commandOutputSync("jj", [
1931
+ "-R",
1932
+ rootPath,
1933
+ "log",
1934
+ "--no-graph",
1935
+ "-r",
1936
+ revision,
1937
+ "-T",
1938
+ "commit_id ++ \"\\n\"",
1939
+ "--ignore-working-copy"
1940
+ ], { cwd: rootPath });
1941
+ return output ? oneResolvedCommit(output, revision) : null;
1942
+ }
1943
+ function oneResolvedCommit(output, revision) {
1944
+ const commits = output.split("\n").filter(Boolean);
1945
+ if (commits.length !== 1 || !/^[0-9a-f]{40}$/.test(commits[0])) throw new Error(`Revision ${revision} does not resolve to one Git commit.`);
1946
+ return commits[0];
1947
+ }
1948
+ async function resolveGitMergeBase(rootPath, baseRef, headRef) {
1949
+ return commandOutput("git", [
1950
+ "-C",
1951
+ rootPath,
1952
+ "merge-base",
1953
+ baseRef,
1954
+ headRef
1955
+ ]);
1956
+ }
1957
+ async function resolveJjMergeBase(rootPath, baseRef, headRef) {
1958
+ return splitLines(await commandOutput("jj", [
1959
+ "-R",
1960
+ rootPath,
1961
+ "log",
1962
+ "--no-graph",
1963
+ "-r",
1964
+ `heads(::${baseRef} & ::${headRef})`,
1965
+ "-T",
1966
+ "commit_id ++ \"\n\"",
1967
+ "--ignore-working-copy"
1968
+ ], { cwd: rootPath }))[0] ?? null;
1969
+ }
1970
+ function readGitFileAtRevisionSync(input) {
1971
+ const commit = resolveGitRevisionCommitSync(input.rootPath, input.ref);
1972
+ if (!commit) return null;
1973
+ const source = commandOutputSync("git", [
1974
+ "-C",
1975
+ input.rootPath,
1976
+ "show",
1977
+ `${commit}:${input.relativePath}`
1978
+ ], {
1979
+ maxBuffer: 10485760,
1980
+ trim: false
1981
+ });
1982
+ return source === null ? null : {
1983
+ commit,
1984
+ source
1985
+ };
1986
+ }
1987
+ function readJjFileAtRevisionSync(input) {
1988
+ const commit = resolveJjRevisionCommitSync(input.rootPath, input.ref);
1989
+ if (!commit) return null;
1990
+ const source = commandOutputSync("jj", [
1991
+ "-R",
1992
+ input.rootPath,
1993
+ "file",
1994
+ "show",
1995
+ "-r",
1996
+ input.ref,
1997
+ "--ignore-working-copy",
1998
+ "--",
1999
+ toJjRootFilePattern(input.relativePath)
2000
+ ], {
2001
+ cwd: input.rootPath,
2002
+ maxBuffer: 10485760,
2003
+ trim: false
2004
+ });
2005
+ return source === null ? null : {
2006
+ commit,
2007
+ source
2008
+ };
2009
+ }
2010
+ async function readGitDiff(input) {
2011
+ const paths = input.literalPaths ? input.paths ?? [] : normalizeDiffPaths(input.paths);
2012
+ const diffRefs = input.headRef ? input.mergeBase === false ? [input.baseRef, input.headRef] : [`${input.baseRef}...${input.headRef}`] : [input.baseRef];
2013
+ const { stdout } = await execFileAsync("git", [
2014
+ ...input.literalPaths ? ["--literal-pathspecs"] : [],
2015
+ "-C",
2016
+ input.rootPath,
2017
+ "diff",
2018
+ "--no-ext-diff",
2019
+ "--no-textconv",
2020
+ "--no-color",
2021
+ "-M",
2022
+ ...input.contextLines !== void 0 ? [`--unified=${input.contextLines}`] : [],
2023
+ ...input.nameOnly ? ["--name-only"] : [],
2024
+ ...diffRefs,
2025
+ "--",
2026
+ ...paths
2027
+ ], {
2028
+ env: input.env,
2029
+ cwd: input.rootPath,
2030
+ maxBuffer: 26214400
2031
+ });
2032
+ return stdout;
2033
+ }
2034
+ async function readGitDiffFileSummaries(input) {
2035
+ const paths = normalizeDiffPaths(input.paths);
2036
+ const diffRefs = input.headRef ? input.mergeBase === false ? [input.baseRef, input.headRef] : [`${input.baseRef}...${input.headRef}`] : [input.baseRef];
2037
+ const { stdout } = await execFileAsync("git", [
2038
+ "-C",
2039
+ input.rootPath,
2040
+ "diff",
2041
+ "--no-ext-diff",
2042
+ "--no-textconv",
2043
+ "--no-color",
2044
+ "-M",
2045
+ "-z",
2046
+ "--raw",
2047
+ "--numstat",
2048
+ ...diffRefs,
2049
+ "--",
2050
+ ...paths
2051
+ ], {
2052
+ env: input.env,
2053
+ cwd: input.rootPath,
2054
+ maxBuffer: 26214400
2055
+ });
2056
+ return parseGitRawNumStatSummaries(stdout);
2057
+ }
2058
+ async function readJjDiff(input) {
2059
+ const paths = input.literalPaths ? input.paths ?? [] : normalizeDiffPaths(input.paths);
2060
+ const { stdout } = await execFileAsync("jj", [
2061
+ "-R",
2062
+ input.rootPath,
2063
+ "--color",
2064
+ "never",
2065
+ "--no-pager",
2066
+ "diff",
2067
+ ...input.nameOnly ? ["--name-only"] : ["--git"],
2068
+ ...input.contextLines !== void 0 ? [`--context=${input.contextLines}`] : [],
2069
+ "--from",
2070
+ input.baseRef,
2071
+ ...input.headRef ? ["--to", input.headRef] : [],
2072
+ "--ignore-working-copy",
2073
+ ...input.literalPaths ? paths.map(toJjRootFilePattern) : paths
2074
+ ], {
2075
+ cwd: input.rootPath,
2076
+ maxBuffer: 26214400
2077
+ });
2078
+ return stdout;
2079
+ }
2080
+ /** Parse `git diff -z --raw --numstat`: raw records (status + paths) first, then counts keyed by current path. */
2081
+ function parseGitRawNumStatSummaries(output) {
2082
+ const fields = output.split("\0");
2083
+ const files = [];
2084
+ const counts = /* @__PURE__ */ new Map();
2085
+ let index = 0;
2086
+ while (index < fields.length) {
2087
+ const record = fields[index];
2088
+ if (record === void 0 || !record.startsWith(":")) break;
2089
+ index += 1;
2090
+ const kind = record.slice(record.lastIndexOf(" ") + 1)[0];
2091
+ if (kind === "R" || kind === "C") {
2092
+ const source = fields[index++];
2093
+ const path = fields[index++];
2094
+ if (!source || !path) continue;
2095
+ files.push(kind === "R" ? {
2096
+ path,
2097
+ previousPath: source,
2098
+ status: "renamed"
2099
+ } : {
2100
+ path,
2101
+ status: "added"
2102
+ });
2103
+ continue;
2104
+ }
2105
+ const path = fields[index++];
2106
+ if (!path) continue;
2107
+ files.push({
2108
+ path,
2109
+ status: kind === "A" ? "added" : kind === "D" ? "deleted" : "modified"
2110
+ });
2111
+ }
2112
+ while (index < fields.length) {
2113
+ const record = fields[index++];
2114
+ if (!record) continue;
2115
+ const additionsEnd = record.indexOf(" ");
2116
+ const deletionsEnd = record.indexOf(" ", additionsEnd + 1);
2117
+ if (additionsEnd < 0 || deletionsEnd < 0) continue;
2118
+ const rawAdditions = record.slice(0, additionsEnd);
2119
+ const rawDeletions = record.slice(additionsEnd + 1, deletionsEnd);
2120
+ let path = record.slice(deletionsEnd + 1);
2121
+ if (!path) {
2122
+ index += 1;
2123
+ path = fields[index++] ?? "";
2124
+ }
2125
+ if (!path) continue;
2126
+ counts.set(path, rawAdditions === "-" && rawDeletions === "-" ? {
2127
+ additions: 0,
2128
+ deletions: 0,
2129
+ binary: true
2130
+ } : {
2131
+ additions: parseGitNumStatCount(rawAdditions),
2132
+ deletions: parseGitNumStatCount(rawDeletions)
2133
+ });
2134
+ }
2135
+ if (files.length === 0 && counts.size > 0) throw new Error("git diff returned its counts before its raw records.");
2136
+ return files.map((file) => ({
2137
+ ...file,
2138
+ ...counts.get(file.path) ?? {
2139
+ additions: 0,
2140
+ deletions: 0
2141
+ }
2142
+ }));
2143
+ }
2144
+ function parseGitNumStatCount(value) {
2145
+ const count = Number(value);
2146
+ return Number.isSafeInteger(count) && count >= 0 ? count : 0;
2147
+ }
2148
+ /** One entry per file section of a Git-format patch, in patch order. */
2149
+ function splitGitPatchFiles(patch) {
2150
+ return splitGitDiffSections(patch).flatMap((section) => {
2151
+ const file = parseGitDiffSectionSummary(section);
2152
+ return file ? [{
2153
+ file,
2154
+ patch: section
2155
+ }] : [];
2156
+ });
2157
+ }
2158
+ function parseGitPatchFileSummaries(output) {
2159
+ return splitGitPatchFiles(output).map((entry) => entry.file);
2160
+ }
2161
+ function filterDiffFileSummaries(summaries, paths) {
2162
+ if (paths.length === 0) return summaries;
2163
+ const requested = new Set(paths);
2164
+ return summaries.filter((file) => requested.has(file.path) || file.previousPath !== void 0 && requested.has(file.previousPath));
2165
+ }
2166
+ function splitGitDiffSections(diff) {
2167
+ const sections = [];
2168
+ let current = null;
2169
+ for (const line of diff.split(/\r?\n/)) if (line.startsWith("diff --git ")) {
2170
+ if (current) sections.push(current.join("\n"));
2171
+ current = [line];
2172
+ } else current?.push(line);
2173
+ if (current) sections.push(current.join("\n"));
2174
+ return sections.filter((section) => section.trim().length > 0);
2175
+ }
2176
+ function parseGitDiffSectionSummary(section) {
2177
+ const lines = section.split(/\r?\n/);
2178
+ const headerPaths = parseDiffGitHeaderPaths(lines[0] ?? "");
2179
+ let oldPath = headerPaths?.oldPath ?? null;
2180
+ let newPath = headerPaths?.newPath ?? null;
2181
+ let renameFrom;
2182
+ let renameTo;
2183
+ let additions = 0;
2184
+ let deletions = 0;
2185
+ let binary = false;
2186
+ let inHunk = false;
2187
+ for (const line of lines) {
2188
+ if (line.startsWith("@@")) {
2189
+ inHunk = true;
2190
+ continue;
2191
+ }
2192
+ if (inHunk) {
2193
+ if (line.startsWith("+")) additions += 1;
2194
+ else if (line.startsWith("-")) deletions += 1;
2195
+ continue;
2196
+ }
2197
+ if (line.startsWith("Binary files ") || line === "GIT binary patch") binary = true;
2198
+ const parsedOldPath = parseGitFileLine(line, "--- ");
2199
+ const parsedNewPath = parseGitFileLine(line, "+++ ");
2200
+ if (parsedOldPath !== void 0) oldPath = parsedOldPath;
2201
+ if (parsedNewPath !== void 0) newPath = parsedNewPath;
2202
+ if (line.startsWith("rename from ")) renameFrom = unquoteGitPath(line.slice(12).trim());
2203
+ if (line.startsWith("rename to ")) renameTo = unquoteGitPath(line.slice(10).trim());
2204
+ }
2205
+ const status = section.includes("\nnew file mode ") ? "added" : section.includes("\ndeleted file mode ") ? "deleted" : section.includes("\nrename from ") && section.includes("\nrename to ") ? "renamed" : "modified";
2206
+ const filePath = status === "deleted" ? oldPath : renameTo ? renameTo : newPath ?? oldPath;
2207
+ if (!filePath) return null;
2208
+ const summary = {
2209
+ path: filePath,
2210
+ previousPath: status === "renamed" ? renameFrom ?? oldPath ?? void 0 : void 0,
2211
+ status,
2212
+ additions,
2213
+ deletions
2214
+ };
2215
+ if (binary) summary.binary = true;
2216
+ return summary;
2217
+ }
2218
+ function parseDiffGitHeaderPaths(line) {
2219
+ if (!line.startsWith("diff --git ")) return null;
2220
+ const tokens = line.slice(11).match(/"([^"\\]|\\.)*"|\S+/g);
2221
+ if (!tokens || tokens.length < 2) return null;
2222
+ return {
2223
+ oldPath: stripDiffPathPrefix(unquoteGitPath(tokens[0])),
2224
+ newPath: stripDiffPathPrefix(unquoteGitPath(tokens[1]))
2225
+ };
2226
+ }
2227
+ function parseGitFileLine(line, prefix) {
2228
+ if (!line.startsWith(prefix)) return void 0;
2229
+ const raw = unquoteGitPath(line.slice(prefix.length).trim());
2230
+ if (raw === "/dev/null") return null;
2231
+ return stripDiffPathPrefix(raw);
2232
+ }
2233
+ function stripDiffPathPrefix(value) {
2234
+ if (value.startsWith("a/") || value.startsWith("b/")) return value.slice(2);
2235
+ return value;
2236
+ }
2237
+ function unquoteGitPath(value) {
2238
+ if (!value.startsWith(`"`)) return value;
2239
+ try {
2240
+ return JSON.parse(value);
2241
+ } catch {
2242
+ return value.slice(1, value.endsWith(`"`) ? -1 : void 0);
2243
+ }
2244
+ }
2245
+ function normalizeDiffPaths(paths) {
2246
+ return [...new Set((paths ?? []).map((path) => path.trim()).filter((path) => path.length > 0 && !path.startsWith("-")))].sort();
2247
+ }
2248
+ function splitLines(output) {
2249
+ return output.split(/\r?\n/).filter((line) => line.length > 0);
2250
+ }
2251
+ function uniqueStrings(values) {
2252
+ return [...new Set(values.filter((value) => Boolean(value)))];
2253
+ }
2254
+ async function canUseGitFallback(rootPath, preferred) {
2255
+ if (preferred !== "jj") return true;
2256
+ const gitRoot = await commandOutput("git", [
2257
+ "-C",
2258
+ rootPath,
2259
+ "rev-parse",
2260
+ "--show-toplevel"
2261
+ ], { cwd: rootPath }).catch(() => null);
2262
+ return gitRoot !== null && canonicalPath(gitRoot) === canonicalPath(rootPath);
2263
+ }
2264
+ function canUseGitFallbackSync(rootPath, preferred) {
2265
+ if (preferred !== "jj") return true;
2266
+ const gitRoot = commandOutputSync("git", [
2267
+ "-C",
2268
+ rootPath,
2269
+ "rev-parse",
2270
+ "--show-toplevel"
2271
+ ], { cwd: rootPath });
2272
+ return gitRoot !== null && canonicalPath(gitRoot) === canonicalPath(rootPath);
2273
+ }
2274
+ function isInsideDirectory(filePath, directoryPath) {
2275
+ const relative = path.relative(canonicalPath(directoryPath), canonicalPath(filePath));
2276
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
2277
+ }
2278
+ function canonicalPath(filePath) {
2279
+ try {
2280
+ return fs.realpathSync.native(filePath);
2281
+ } catch {
2282
+ return path.resolve(filePath);
2283
+ }
2284
+ }
2285
+ async function commandOutput(command, args, options = {}) {
2286
+ return runCommandOutput(command, args, options);
2287
+ }
2288
+ function commandOutputSync(command, args, options = {}) {
2289
+ return runCommandOutputSync(command, args, options);
2290
+ }
2291
+ function runCommandOutput(command, args, options) {
2292
+ return execFileAsync(command, args, {
2293
+ cwd: options.cwd,
2294
+ env: commandEnvironment(command, args),
2295
+ maxBuffer: options.maxBuffer
2296
+ }).then(({ stdout }) => options.trim === false ? stdout : stdout.trim());
2297
+ }
2298
+ function runCommandOutputSync(command, args, options) {
2299
+ try {
2300
+ const output = execFileSyncObserved(command, args, {
2301
+ cwd: options.cwd,
2302
+ encoding: "utf8",
2303
+ env: commandEnvironment(command, args),
2304
+ maxBuffer: options.maxBuffer,
2305
+ stdio: [
2306
+ "ignore",
2307
+ "pipe",
2308
+ "ignore"
2309
+ ]
2310
+ });
2311
+ return options.trim === false ? output : output.trim();
2312
+ } catch {
2313
+ return null;
2314
+ }
2315
+ }
2316
+ function commandEnvironment(command, args) {
2317
+ if (command !== "git" || args[0] !== "-C" && args[0] !== "--git-dir") return;
2318
+ return localGitEnvironment();
2319
+ }
2320
+ /** Drop per-repository git env vars that would redirect an explicit object store. */
2321
+ function localGitEnvironment() {
2322
+ const env = { ...process.env };
2323
+ for (const key of LOCAL_GIT_ENV_KEYS) delete env[key];
2324
+ return env;
2325
+ }
2326
+ //#endregion
2327
+ //#region ../../node_modules/graceful-fs/polyfills.js
2328
+ var require_polyfills = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2329
+ var constants$1 = __require("constants");
2330
+ var origCwd = process.cwd;
2331
+ var cwd = null;
2332
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
2333
+ process.cwd = function() {
2334
+ if (!cwd) cwd = origCwd.call(process);
2335
+ return cwd;
2336
+ };
2337
+ try {
2338
+ process.cwd();
2339
+ } catch (er) {}
2340
+ if (typeof process.chdir === "function") {
2341
+ var chdir = process.chdir;
2342
+ process.chdir = function(d) {
2343
+ cwd = null;
2344
+ chdir.call(process, d);
2345
+ };
2346
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
2347
+ }
2348
+ module.exports = patch;
2349
+ function patch(fs) {
2350
+ if (constants$1.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) patchLchmod(fs);
2351
+ if (!fs.lutimes) patchLutimes(fs);
2352
+ fs.chown = chownFix(fs.chown);
2353
+ fs.fchown = chownFix(fs.fchown);
2354
+ fs.lchown = chownFix(fs.lchown);
2355
+ fs.chmod = chmodFix(fs.chmod);
2356
+ fs.fchmod = chmodFix(fs.fchmod);
2357
+ fs.lchmod = chmodFix(fs.lchmod);
2358
+ fs.chownSync = chownFixSync(fs.chownSync);
2359
+ fs.fchownSync = chownFixSync(fs.fchownSync);
2360
+ fs.lchownSync = chownFixSync(fs.lchownSync);
2361
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
2362
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
2363
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
2364
+ fs.stat = statFix(fs.stat);
2365
+ fs.fstat = statFix(fs.fstat);
2366
+ fs.lstat = statFix(fs.lstat);
2367
+ fs.statSync = statFixSync(fs.statSync);
2368
+ fs.fstatSync = statFixSync(fs.fstatSync);
2369
+ fs.lstatSync = statFixSync(fs.lstatSync);
2370
+ if (fs.chmod && !fs.lchmod) {
2371
+ fs.lchmod = function(path, mode, cb) {
2372
+ if (cb) process.nextTick(cb);
2373
+ };
2374
+ fs.lchmodSync = function() {};
2375
+ }
2376
+ if (fs.chown && !fs.lchown) {
2377
+ fs.lchown = function(path, uid, gid, cb) {
2378
+ if (cb) process.nextTick(cb);
2379
+ };
2380
+ fs.lchownSync = function() {};
2381
+ }
2382
+ if (platform === "win32") fs.rename = typeof fs.rename !== "function" ? fs.rename : (function(fs$rename) {
2383
+ function rename(from, to, cb) {
2384
+ var start = Date.now();
2385
+ var backoff = 0;
2386
+ fs$rename(from, to, function CB(er) {
2387
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
2388
+ setTimeout(function() {
2389
+ fs.stat(to, function(stater, st) {
2390
+ if (stater && stater.code === "ENOENT") fs$rename(from, to, CB);
2391
+ else cb(er);
2392
+ });
2393
+ }, backoff);
2394
+ if (backoff < 100) backoff += 10;
2395
+ return;
2396
+ }
2397
+ if (cb) cb(er);
2398
+ });
2399
+ }
2400
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
2401
+ return rename;
2402
+ })(fs.rename);
2403
+ fs.read = typeof fs.read !== "function" ? fs.read : (function(fs$read) {
2404
+ function read(fd, buffer, offset, length, position, callback_) {
2405
+ var callback;
2406
+ if (callback_ && typeof callback_ === "function") {
2407
+ var eagCounter = 0;
2408
+ callback = function(er, _, __) {
2409
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
2410
+ eagCounter++;
2411
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
2412
+ }
2413
+ callback_.apply(this, arguments);
2414
+ };
2415
+ }
2416
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
2417
+ }
2418
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
2419
+ return read;
2420
+ })(fs.read);
2421
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : (function(fs$readSync) {
2422
+ return function(fd, buffer, offset, length, position) {
2423
+ var eagCounter = 0;
2424
+ while (true) try {
2425
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
2426
+ } catch (er) {
2427
+ if (er.code === "EAGAIN" && eagCounter < 10) {
2428
+ eagCounter++;
2429
+ continue;
2430
+ }
2431
+ throw er;
2432
+ }
2433
+ };
2434
+ })(fs.readSync);
2435
+ function patchLchmod(fs) {
2436
+ fs.lchmod = function(path, mode, callback) {
2437
+ fs.open(path, constants$1.O_WRONLY | constants$1.O_SYMLINK, mode, function(err, fd) {
2438
+ if (err) {
2439
+ if (callback) callback(err);
2440
+ return;
2441
+ }
2442
+ fs.fchmod(fd, mode, function(err) {
2443
+ fs.close(fd, function(err2) {
2444
+ if (callback) callback(err || err2);
2445
+ });
2446
+ });
2447
+ });
2448
+ };
2449
+ fs.lchmodSync = function(path, mode) {
2450
+ var fd = fs.openSync(path, constants$1.O_WRONLY | constants$1.O_SYMLINK, mode);
2451
+ var threw = true;
2452
+ var ret;
2453
+ try {
2454
+ ret = fs.fchmodSync(fd, mode);
2455
+ threw = false;
2456
+ } finally {
2457
+ if (threw) try {
2458
+ fs.closeSync(fd);
2459
+ } catch (er) {}
2460
+ else fs.closeSync(fd);
2461
+ }
2462
+ return ret;
2463
+ };
2464
+ }
2465
+ function patchLutimes(fs) {
2466
+ if (constants$1.hasOwnProperty("O_SYMLINK") && fs.futimes) {
2467
+ fs.lutimes = function(path, at, mt, cb) {
2468
+ fs.open(path, constants$1.O_SYMLINK, function(er, fd) {
2469
+ if (er) {
2470
+ if (cb) cb(er);
2471
+ return;
2472
+ }
2473
+ fs.futimes(fd, at, mt, function(er) {
2474
+ fs.close(fd, function(er2) {
2475
+ if (cb) cb(er || er2);
2476
+ });
2477
+ });
2478
+ });
2479
+ };
2480
+ fs.lutimesSync = function(path, at, mt) {
2481
+ var fd = fs.openSync(path, constants$1.O_SYMLINK);
2482
+ var ret;
2483
+ var threw = true;
2484
+ try {
2485
+ ret = fs.futimesSync(fd, at, mt);
2486
+ threw = false;
2487
+ } finally {
2488
+ if (threw) try {
2489
+ fs.closeSync(fd);
2490
+ } catch (er) {}
2491
+ else fs.closeSync(fd);
2492
+ }
2493
+ return ret;
2494
+ };
2495
+ } else if (fs.futimes) {
2496
+ fs.lutimes = function(_a, _b, _c, cb) {
2497
+ if (cb) process.nextTick(cb);
2498
+ };
2499
+ fs.lutimesSync = function() {};
2500
+ }
2501
+ }
2502
+ function chmodFix(orig) {
2503
+ if (!orig) return orig;
2504
+ return function(target, mode, cb) {
2505
+ return orig.call(fs, target, mode, function(er) {
2506
+ if (chownErOk(er)) er = null;
2507
+ if (cb) cb.apply(this, arguments);
2508
+ });
2509
+ };
2510
+ }
2511
+ function chmodFixSync(orig) {
2512
+ if (!orig) return orig;
2513
+ return function(target, mode) {
2514
+ try {
2515
+ return orig.call(fs, target, mode);
2516
+ } catch (er) {
2517
+ if (!chownErOk(er)) throw er;
2518
+ }
2519
+ };
2520
+ }
2521
+ function chownFix(orig) {
2522
+ if (!orig) return orig;
2523
+ return function(target, uid, gid, cb) {
2524
+ return orig.call(fs, target, uid, gid, function(er) {
2525
+ if (chownErOk(er)) er = null;
2526
+ if (cb) cb.apply(this, arguments);
2527
+ });
2528
+ };
2529
+ }
2530
+ function chownFixSync(orig) {
2531
+ if (!orig) return orig;
2532
+ return function(target, uid, gid) {
2533
+ try {
2534
+ return orig.call(fs, target, uid, gid);
2535
+ } catch (er) {
2536
+ if (!chownErOk(er)) throw er;
2537
+ }
2538
+ };
2539
+ }
2540
+ function statFix(orig) {
2541
+ if (!orig) return orig;
2542
+ return function(target, options, cb) {
2543
+ if (typeof options === "function") {
2544
+ cb = options;
2545
+ options = null;
2546
+ }
2547
+ function callback(er, stats) {
2548
+ if (stats) {
2549
+ if (stats.uid < 0) stats.uid += 4294967296;
2550
+ if (stats.gid < 0) stats.gid += 4294967296;
2551
+ }
2552
+ if (cb) cb.apply(this, arguments);
2553
+ }
2554
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
2555
+ };
2556
+ }
2557
+ function statFixSync(orig) {
2558
+ if (!orig) return orig;
2559
+ return function(target, options) {
2560
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
2561
+ if (stats) {
2562
+ if (stats.uid < 0) stats.uid += 4294967296;
2563
+ if (stats.gid < 0) stats.gid += 4294967296;
2564
+ }
2565
+ return stats;
2566
+ };
2567
+ }
2568
+ function chownErOk(er) {
2569
+ if (!er) return true;
2570
+ if (er.code === "ENOSYS") return true;
2571
+ if (!process.getuid || process.getuid() !== 0) {
2572
+ if (er.code === "EINVAL" || er.code === "EPERM") return true;
2573
+ }
2574
+ return false;
2575
+ }
2576
+ }
2577
+ }));
2578
+ //#endregion
2579
+ //#region ../../node_modules/graceful-fs/legacy-streams.js
2580
+ var require_legacy_streams = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2581
+ var Stream = __require("stream").Stream;
2582
+ module.exports = legacy;
2583
+ function legacy(fs) {
2584
+ return {
2585
+ ReadStream,
2586
+ WriteStream
2587
+ };
2588
+ function ReadStream(path, options) {
2589
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
2590
+ Stream.call(this);
2591
+ var self = this;
2592
+ this.path = path;
2593
+ this.fd = null;
2594
+ this.readable = true;
2595
+ this.paused = false;
2596
+ this.flags = "r";
2597
+ this.mode = 438;
2598
+ this.bufferSize = 65536;
2599
+ options = options || {};
2600
+ var keys = Object.keys(options);
2601
+ for (var index = 0, length = keys.length; index < length; index++) {
2602
+ var key = keys[index];
2603
+ this[key] = options[key];
2604
+ }
2605
+ if (this.encoding) this.setEncoding(this.encoding);
2606
+ if (this.start !== void 0) {
2607
+ if ("number" !== typeof this.start) throw TypeError("start must be a Number");
2608
+ if (this.end === void 0) this.end = Infinity;
2609
+ else if ("number" !== typeof this.end) throw TypeError("end must be a Number");
2610
+ if (this.start > this.end) throw new Error("start must be <= end");
2611
+ this.pos = this.start;
2612
+ }
2613
+ if (this.fd !== null) {
2614
+ process.nextTick(function() {
2615
+ self._read();
2616
+ });
2617
+ return;
2618
+ }
2619
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
2620
+ if (err) {
2621
+ self.emit("error", err);
2622
+ self.readable = false;
2623
+ return;
2624
+ }
2625
+ self.fd = fd;
2626
+ self.emit("open", fd);
2627
+ self._read();
2628
+ });
2629
+ }
2630
+ function WriteStream(path, options) {
2631
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
2632
+ Stream.call(this);
2633
+ this.path = path;
2634
+ this.fd = null;
2635
+ this.writable = true;
2636
+ this.flags = "w";
2637
+ this.encoding = "binary";
2638
+ this.mode = 438;
2639
+ this.bytesWritten = 0;
2640
+ options = options || {};
2641
+ var keys = Object.keys(options);
2642
+ for (var index = 0, length = keys.length; index < length; index++) {
2643
+ var key = keys[index];
2644
+ this[key] = options[key];
2645
+ }
2646
+ if (this.start !== void 0) {
2647
+ if ("number" !== typeof this.start) throw TypeError("start must be a Number");
2648
+ if (this.start < 0) throw new Error("start must be >= zero");
2649
+ this.pos = this.start;
2650
+ }
2651
+ this.busy = false;
2652
+ this._queue = [];
2653
+ if (this.fd === null) {
2654
+ this._open = fs.open;
2655
+ this._queue.push([
2656
+ this._open,
2657
+ this.path,
2658
+ this.flags,
2659
+ this.mode,
2660
+ void 0
2661
+ ]);
2662
+ this.flush();
2663
+ }
2664
+ }
2665
+ }
2666
+ }));
2667
+ //#endregion
2668
+ //#region ../../node_modules/graceful-fs/clone.js
2669
+ var require_clone = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2670
+ module.exports = clone;
2671
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
2672
+ return obj.__proto__;
2673
+ };
2674
+ function clone(obj) {
2675
+ if (obj === null || typeof obj !== "object") return obj;
2676
+ if (obj instanceof Object) var copy = { __proto__: getPrototypeOf(obj) };
2677
+ else var copy = Object.create(null);
2678
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
2679
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
2680
+ });
2681
+ return copy;
2682
+ }
2683
+ }));
2684
+ //#endregion
2685
+ //#region ../../node_modules/graceful-fs/graceful-fs.js
2686
+ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2687
+ var fs$1 = __require("fs");
2688
+ var polyfills = require_polyfills();
2689
+ var legacy = require_legacy_streams();
2690
+ var clone = require_clone();
2691
+ var util = __require("util");
2692
+ /* istanbul ignore next - node 0.x polyfill */
2693
+ var gracefulQueue;
2694
+ var previousSymbol;
2695
+ /* istanbul ignore else - node 0.x polyfill */
2696
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
2697
+ gracefulQueue = Symbol.for("graceful-fs.queue");
2698
+ previousSymbol = Symbol.for("graceful-fs.previous");
2699
+ } else {
2700
+ gracefulQueue = "___graceful-fs.queue";
2701
+ previousSymbol = "___graceful-fs.previous";
2702
+ }
2703
+ function noop() {}
2704
+ function publishQueue(context, queue) {
2705
+ Object.defineProperty(context, gracefulQueue, { get: function() {
2706
+ return queue;
2707
+ } });
2708
+ }
2709
+ var debug = noop;
2710
+ if (util.debuglog) debug = util.debuglog("gfs4");
2711
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) debug = function() {
2712
+ var m = util.format.apply(util, arguments);
2713
+ m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
2714
+ console.error(m);
2715
+ };
2716
+ if (!fs$1[gracefulQueue]) {
2717
+ publishQueue(fs$1, global[gracefulQueue] || []);
2718
+ fs$1.close = (function(fs$close) {
2719
+ function close(fd, cb) {
2720
+ return fs$close.call(fs$1, fd, function(err) {
2721
+ if (!err) resetQueue();
2722
+ if (typeof cb === "function") cb.apply(this, arguments);
2723
+ });
2724
+ }
2725
+ Object.defineProperty(close, previousSymbol, { value: fs$close });
2726
+ return close;
2727
+ })(fs$1.close);
2728
+ fs$1.closeSync = (function(fs$closeSync) {
2729
+ function closeSync(fd) {
2730
+ fs$closeSync.apply(fs$1, arguments);
2731
+ resetQueue();
2732
+ }
2733
+ Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync });
2734
+ return closeSync;
2735
+ })(fs$1.closeSync);
2736
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) process.on("exit", function() {
2737
+ debug(fs$1[gracefulQueue]);
2738
+ __require("assert").equal(fs$1[gracefulQueue].length, 0);
2739
+ });
2740
+ }
2741
+ if (!global[gracefulQueue]) publishQueue(global, fs$1[gracefulQueue]);
2742
+ module.exports = patch(clone(fs$1));
2743
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$1.__patched) {
2744
+ module.exports = patch(fs$1);
2745
+ fs$1.__patched = true;
2746
+ }
2747
+ function patch(fs) {
2748
+ polyfills(fs);
2749
+ fs.gracefulify = patch;
2750
+ fs.createReadStream = createReadStream;
2751
+ fs.createWriteStream = createWriteStream;
2752
+ var fs$readFile = fs.readFile;
2753
+ fs.readFile = readFile;
2754
+ function readFile(path, options, cb) {
2755
+ if (typeof options === "function") cb = options, options = null;
2756
+ return go$readFile(path, options, cb);
2757
+ function go$readFile(path, options, cb, startTime) {
2758
+ return fs$readFile(path, options, function(err) {
2759
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([
2760
+ go$readFile,
2761
+ [
2762
+ path,
2763
+ options,
2764
+ cb
2765
+ ],
2766
+ err,
2767
+ startTime || Date.now(),
2768
+ Date.now()
2769
+ ]);
2770
+ else if (typeof cb === "function") cb.apply(this, arguments);
2771
+ });
2772
+ }
2773
+ }
2774
+ var fs$writeFile = fs.writeFile;
2775
+ fs.writeFile = writeFile;
2776
+ function writeFile(path, data, options, cb) {
2777
+ if (typeof options === "function") cb = options, options = null;
2778
+ return go$writeFile(path, data, options, cb);
2779
+ function go$writeFile(path, data, options, cb, startTime) {
2780
+ return fs$writeFile(path, data, options, function(err) {
2781
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([
2782
+ go$writeFile,
2783
+ [
2784
+ path,
2785
+ data,
2786
+ options,
2787
+ cb
2788
+ ],
2789
+ err,
2790
+ startTime || Date.now(),
2791
+ Date.now()
2792
+ ]);
2793
+ else if (typeof cb === "function") cb.apply(this, arguments);
2794
+ });
2795
+ }
2796
+ }
2797
+ var fs$appendFile = fs.appendFile;
2798
+ if (fs$appendFile) fs.appendFile = appendFile;
2799
+ function appendFile(path, data, options, cb) {
2800
+ if (typeof options === "function") cb = options, options = null;
2801
+ return go$appendFile(path, data, options, cb);
2802
+ function go$appendFile(path, data, options, cb, startTime) {
2803
+ return fs$appendFile(path, data, options, function(err) {
2804
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([
2805
+ go$appendFile,
2806
+ [
2807
+ path,
2808
+ data,
2809
+ options,
2810
+ cb
2811
+ ],
2812
+ err,
2813
+ startTime || Date.now(),
2814
+ Date.now()
2815
+ ]);
2816
+ else if (typeof cb === "function") cb.apply(this, arguments);
2817
+ });
2818
+ }
2819
+ }
2820
+ var fs$copyFile = fs.copyFile;
2821
+ if (fs$copyFile) fs.copyFile = copyFile;
2822
+ function copyFile(src, dest, flags, cb) {
2823
+ if (typeof flags === "function") {
2824
+ cb = flags;
2825
+ flags = 0;
2826
+ }
2827
+ return go$copyFile(src, dest, flags, cb);
2828
+ function go$copyFile(src, dest, flags, cb, startTime) {
2829
+ return fs$copyFile(src, dest, flags, function(err) {
2830
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([
2831
+ go$copyFile,
2832
+ [
2833
+ src,
2834
+ dest,
2835
+ flags,
2836
+ cb
2837
+ ],
2838
+ err,
2839
+ startTime || Date.now(),
2840
+ Date.now()
2841
+ ]);
2842
+ else if (typeof cb === "function") cb.apply(this, arguments);
2843
+ });
2844
+ }
2845
+ }
2846
+ var fs$readdir = fs.readdir;
2847
+ fs.readdir = readdir;
2848
+ var noReaddirOptionVersions = /^v[0-5]\./;
2849
+ function readdir(path, options, cb) {
2850
+ if (typeof options === "function") cb = options, options = null;
2851
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir(path, options, cb, startTime) {
2852
+ return fs$readdir(path, fs$readdirCallback(path, options, cb, startTime));
2853
+ } : function go$readdir(path, options, cb, startTime) {
2854
+ return fs$readdir(path, options, fs$readdirCallback(path, options, cb, startTime));
2855
+ };
2856
+ return go$readdir(path, options, cb);
2857
+ function fs$readdirCallback(path, options, cb, startTime) {
2858
+ return function(err, files) {
2859
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([
2860
+ go$readdir,
2861
+ [
2862
+ path,
2863
+ options,
2864
+ cb
2865
+ ],
2866
+ err,
2867
+ startTime || Date.now(),
2868
+ Date.now()
2869
+ ]);
2870
+ else {
2871
+ if (files && files.sort) files.sort();
2872
+ if (typeof cb === "function") cb.call(this, err, files);
2873
+ }
2874
+ };
2875
+ }
2876
+ }
2877
+ if (process.version.substr(0, 4) === "v0.8") {
2878
+ var legStreams = legacy(fs);
2879
+ ReadStream = legStreams.ReadStream;
2880
+ WriteStream = legStreams.WriteStream;
2881
+ }
2882
+ var fs$ReadStream = fs.ReadStream;
2883
+ if (fs$ReadStream) {
2884
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
2885
+ ReadStream.prototype.open = ReadStream$open;
2886
+ }
2887
+ var fs$WriteStream = fs.WriteStream;
2888
+ if (fs$WriteStream) {
2889
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
2890
+ WriteStream.prototype.open = WriteStream$open;
2891
+ }
2892
+ Object.defineProperty(fs, "ReadStream", {
2893
+ get: function() {
2894
+ return ReadStream;
2895
+ },
2896
+ set: function(val) {
2897
+ ReadStream = val;
2898
+ },
2899
+ enumerable: true,
2900
+ configurable: true
2901
+ });
2902
+ Object.defineProperty(fs, "WriteStream", {
2903
+ get: function() {
2904
+ return WriteStream;
2905
+ },
2906
+ set: function(val) {
2907
+ WriteStream = val;
2908
+ },
2909
+ enumerable: true,
2910
+ configurable: true
2911
+ });
2912
+ var FileReadStream = ReadStream;
2913
+ Object.defineProperty(fs, "FileReadStream", {
2914
+ get: function() {
2915
+ return FileReadStream;
2916
+ },
2917
+ set: function(val) {
2918
+ FileReadStream = val;
2919
+ },
2920
+ enumerable: true,
2921
+ configurable: true
2922
+ });
2923
+ var FileWriteStream = WriteStream;
2924
+ Object.defineProperty(fs, "FileWriteStream", {
2925
+ get: function() {
2926
+ return FileWriteStream;
2927
+ },
2928
+ set: function(val) {
2929
+ FileWriteStream = val;
2930
+ },
2931
+ enumerable: true,
2932
+ configurable: true
2933
+ });
2934
+ function ReadStream(path, options) {
2935
+ if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this;
2936
+ else return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
2937
+ }
2938
+ function ReadStream$open() {
2939
+ var that = this;
2940
+ open(that.path, that.flags, that.mode, function(err, fd) {
2941
+ if (err) {
2942
+ if (that.autoClose) that.destroy();
2943
+ that.emit("error", err);
2944
+ } else {
2945
+ that.fd = fd;
2946
+ that.emit("open", fd);
2947
+ that.read();
2948
+ }
2949
+ });
2950
+ }
2951
+ function WriteStream(path, options) {
2952
+ if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this;
2953
+ else return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
2954
+ }
2955
+ function WriteStream$open() {
2956
+ var that = this;
2957
+ open(that.path, that.flags, that.mode, function(err, fd) {
2958
+ if (err) {
2959
+ that.destroy();
2960
+ that.emit("error", err);
2961
+ } else {
2962
+ that.fd = fd;
2963
+ that.emit("open", fd);
2964
+ }
2965
+ });
2966
+ }
2967
+ function createReadStream(path, options) {
2968
+ return new fs.ReadStream(path, options);
2969
+ }
2970
+ function createWriteStream(path, options) {
2971
+ return new fs.WriteStream(path, options);
2972
+ }
2973
+ var fs$open = fs.open;
2974
+ fs.open = open;
2975
+ function open(path, flags, mode, cb) {
2976
+ if (typeof mode === "function") cb = mode, mode = null;
2977
+ return go$open(path, flags, mode, cb);
2978
+ function go$open(path, flags, mode, cb, startTime) {
2979
+ return fs$open(path, flags, mode, function(err, fd) {
2980
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([
2981
+ go$open,
2982
+ [
2983
+ path,
2984
+ flags,
2985
+ mode,
2986
+ cb
2987
+ ],
2988
+ err,
2989
+ startTime || Date.now(),
2990
+ Date.now()
2991
+ ]);
2992
+ else if (typeof cb === "function") cb.apply(this, arguments);
2993
+ });
2994
+ }
2995
+ }
2996
+ return fs;
2997
+ }
2998
+ function enqueue(elem) {
2999
+ debug("ENQUEUE", elem[0].name, elem[1]);
3000
+ fs$1[gracefulQueue].push(elem);
3001
+ retry();
3002
+ }
3003
+ var retryTimer;
3004
+ function resetQueue() {
3005
+ var now = Date.now();
3006
+ for (var i = 0; i < fs$1[gracefulQueue].length; ++i) if (fs$1[gracefulQueue][i].length > 2) {
3007
+ fs$1[gracefulQueue][i][3] = now;
3008
+ fs$1[gracefulQueue][i][4] = now;
3009
+ }
3010
+ retry();
3011
+ }
3012
+ function retry() {
3013
+ clearTimeout(retryTimer);
3014
+ retryTimer = void 0;
3015
+ if (fs$1[gracefulQueue].length === 0) return;
3016
+ var elem = fs$1[gracefulQueue].shift();
3017
+ var fn = elem[0];
3018
+ var args = elem[1];
3019
+ var err = elem[2];
3020
+ var startTime = elem[3];
3021
+ var lastTime = elem[4];
3022
+ if (startTime === void 0) {
3023
+ debug("RETRY", fn.name, args);
3024
+ fn.apply(null, args);
3025
+ } else if (Date.now() - startTime >= 6e4) {
3026
+ debug("TIMEOUT", fn.name, args);
3027
+ var cb = args.pop();
3028
+ if (typeof cb === "function") cb.call(null, err);
3029
+ } else {
3030
+ var sinceAttempt = Date.now() - lastTime;
3031
+ var sinceStart = Math.max(lastTime - startTime, 1);
3032
+ if (sinceAttempt >= Math.min(sinceStart * 1.2, 100)) {
3033
+ debug("RETRY", fn.name, args);
3034
+ fn.apply(null, args.concat([startTime]));
3035
+ } else fs$1[gracefulQueue].push(elem);
3036
+ }
3037
+ if (retryTimer === void 0) retryTimer = setTimeout(retry, 0);
3038
+ }
3039
+ }));
3040
+ //#endregion
3041
+ //#region ../../node_modules/retry/lib/retry_operation.js
3042
+ var require_retry_operation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3043
+ function RetryOperation(timeouts, options) {
3044
+ if (typeof options === "boolean") options = { forever: options };
3045
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
3046
+ this._timeouts = timeouts;
3047
+ this._options = options || {};
3048
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
3049
+ this._fn = null;
3050
+ this._errors = [];
3051
+ this._attempts = 1;
3052
+ this._operationTimeout = null;
3053
+ this._operationTimeoutCb = null;
3054
+ this._timeout = null;
3055
+ this._operationStart = null;
3056
+ if (this._options.forever) this._cachedTimeouts = this._timeouts.slice(0);
3057
+ }
3058
+ module.exports = RetryOperation;
3059
+ RetryOperation.prototype.reset = function() {
3060
+ this._attempts = 1;
3061
+ this._timeouts = this._originalTimeouts;
3062
+ };
3063
+ RetryOperation.prototype.stop = function() {
3064
+ if (this._timeout) clearTimeout(this._timeout);
3065
+ this._timeouts = [];
3066
+ this._cachedTimeouts = null;
3067
+ };
3068
+ RetryOperation.prototype.retry = function(err) {
3069
+ if (this._timeout) clearTimeout(this._timeout);
3070
+ if (!err) return false;
3071
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
3072
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
3073
+ this._errors.unshift(/* @__PURE__ */ new Error("RetryOperation timeout occurred"));
3074
+ return false;
3075
+ }
3076
+ this._errors.push(err);
3077
+ var timeout = this._timeouts.shift();
3078
+ if (timeout === void 0) {
3079
+ if (this._cachedTimeouts) {
3080
+ this._errors.splice(this._errors.length - 1, this._errors.length);
3081
+ this._timeouts = this._cachedTimeouts.slice(0);
3082
+ timeout = this._timeouts.shift();
3083
+ } else return false;
3084
+ }
3085
+ var self = this;
3086
+ var timer = setTimeout(function() {
3087
+ self._attempts++;
3088
+ if (self._operationTimeoutCb) {
3089
+ self._timeout = setTimeout(function() {
3090
+ self._operationTimeoutCb(self._attempts);
3091
+ }, self._operationTimeout);
3092
+ if (self._options.unref) self._timeout.unref();
3093
+ }
3094
+ self._fn(self._attempts);
3095
+ }, timeout);
3096
+ if (this._options.unref) timer.unref();
3097
+ return true;
3098
+ };
3099
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
3100
+ this._fn = fn;
3101
+ if (timeoutOps) {
3102
+ if (timeoutOps.timeout) this._operationTimeout = timeoutOps.timeout;
3103
+ if (timeoutOps.cb) this._operationTimeoutCb = timeoutOps.cb;
3104
+ }
3105
+ var self = this;
3106
+ if (this._operationTimeoutCb) this._timeout = setTimeout(function() {
3107
+ self._operationTimeoutCb();
3108
+ }, self._operationTimeout);
3109
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
3110
+ this._fn(this._attempts);
3111
+ };
3112
+ RetryOperation.prototype.try = function(fn) {
3113
+ console.log("Using RetryOperation.try() is deprecated");
3114
+ this.attempt(fn);
3115
+ };
3116
+ RetryOperation.prototype.start = function(fn) {
3117
+ console.log("Using RetryOperation.start() is deprecated");
3118
+ this.attempt(fn);
3119
+ };
3120
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
3121
+ RetryOperation.prototype.errors = function() {
3122
+ return this._errors;
3123
+ };
3124
+ RetryOperation.prototype.attempts = function() {
3125
+ return this._attempts;
3126
+ };
3127
+ RetryOperation.prototype.mainError = function() {
3128
+ if (this._errors.length === 0) return null;
3129
+ var counts = {};
3130
+ var mainError = null;
3131
+ var mainErrorCount = 0;
3132
+ for (var i = 0; i < this._errors.length; i++) {
3133
+ var error = this._errors[i];
3134
+ var message = error.message;
3135
+ var count = (counts[message] || 0) + 1;
3136
+ counts[message] = count;
3137
+ if (count >= mainErrorCount) {
3138
+ mainError = error;
3139
+ mainErrorCount = count;
3140
+ }
3141
+ }
3142
+ return mainError;
3143
+ };
3144
+ }));
3145
+ //#endregion
3146
+ //#region ../../node_modules/retry/lib/retry.js
3147
+ var require_retry$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
3148
+ var RetryOperation = require_retry_operation();
3149
+ exports.operation = function(options) {
3150
+ return new RetryOperation(exports.timeouts(options), {
3151
+ forever: options && options.forever,
3152
+ unref: options && options.unref,
3153
+ maxRetryTime: options && options.maxRetryTime
3154
+ });
3155
+ };
3156
+ exports.timeouts = function(options) {
3157
+ if (options instanceof Array) return [].concat(options);
3158
+ var opts = {
3159
+ retries: 10,
3160
+ factor: 2,
3161
+ minTimeout: 1e3,
3162
+ maxTimeout: Infinity,
3163
+ randomize: false
3164
+ };
3165
+ for (var key in options) opts[key] = options[key];
3166
+ if (opts.minTimeout > opts.maxTimeout) throw new Error("minTimeout is greater than maxTimeout");
3167
+ var timeouts = [];
3168
+ for (var i = 0; i < opts.retries; i++) timeouts.push(this.createTimeout(i, opts));
3169
+ if (options && options.forever && !timeouts.length) timeouts.push(this.createTimeout(i, opts));
3170
+ timeouts.sort(function(a, b) {
3171
+ return a - b;
3172
+ });
3173
+ return timeouts;
3174
+ };
3175
+ exports.createTimeout = function(attempt, opts) {
3176
+ var random = opts.randomize ? Math.random() + 1 : 1;
3177
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
3178
+ timeout = Math.min(timeout, opts.maxTimeout);
3179
+ return timeout;
3180
+ };
3181
+ exports.wrap = function(obj, options, methods) {
3182
+ if (options instanceof Array) {
3183
+ methods = options;
3184
+ options = null;
3185
+ }
3186
+ if (!methods) {
3187
+ methods = [];
3188
+ for (var key in obj) if (typeof obj[key] === "function") methods.push(key);
3189
+ }
3190
+ for (var i = 0; i < methods.length; i++) {
3191
+ var method = methods[i];
3192
+ var original = obj[method];
3193
+ obj[method] = function retryWrapper(original) {
3194
+ var op = exports.operation(options);
3195
+ var args = Array.prototype.slice.call(arguments, 1);
3196
+ var callback = args.pop();
3197
+ args.push(function(err) {
3198
+ if (op.retry(err)) return;
3199
+ if (err) arguments[0] = op.mainError();
3200
+ callback.apply(this, arguments);
3201
+ });
3202
+ op.attempt(function() {
3203
+ original.apply(obj, args);
3204
+ });
3205
+ }.bind(obj, original);
3206
+ obj[method].options = options;
3207
+ }
3208
+ };
3209
+ }));
3210
+ //#endregion
3211
+ //#region ../../node_modules/retry/index.js
3212
+ var require_retry = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3213
+ module.exports = require_retry$1();
3214
+ }));
3215
+ //#endregion
3216
+ //#region ../../node_modules/signal-exit/signals.js
3217
+ var require_signals = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3218
+ module.exports = [
3219
+ "SIGABRT",
3220
+ "SIGALRM",
3221
+ "SIGHUP",
3222
+ "SIGINT",
3223
+ "SIGTERM"
3224
+ ];
3225
+ if (process.platform !== "win32") module.exports.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
3226
+ if (process.platform === "linux") module.exports.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
3227
+ }));
3228
+ //#endregion
3229
+ //#region ../../node_modules/signal-exit/index.js
3230
+ var require_signal_exit = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3231
+ var process = global.process;
3232
+ const processOk = function(process) {
3233
+ return process && typeof process === "object" && typeof process.removeListener === "function" && typeof process.emit === "function" && typeof process.reallyExit === "function" && typeof process.listeners === "function" && typeof process.kill === "function" && typeof process.pid === "number" && typeof process.on === "function";
3234
+ };
3235
+ /* istanbul ignore if */
3236
+ if (!processOk(process)) module.exports = function() {
3237
+ return function() {};
3238
+ };
3239
+ else {
3240
+ var assert = __require("assert");
3241
+ var signals = require_signals();
3242
+ var isWin = /^win/i.test(process.platform);
3243
+ var EE = __require("events");
3244
+ /* istanbul ignore if */
3245
+ if (typeof EE !== "function") EE = EE.EventEmitter;
3246
+ var emitter;
3247
+ if (process.__signal_exit_emitter__) emitter = process.__signal_exit_emitter__;
3248
+ else {
3249
+ emitter = process.__signal_exit_emitter__ = new EE();
3250
+ emitter.count = 0;
3251
+ emitter.emitted = {};
3252
+ }
3253
+ if (!emitter.infinite) {
3254
+ emitter.setMaxListeners(Infinity);
3255
+ emitter.infinite = true;
3256
+ }
3257
+ module.exports = function(cb, opts) {
3258
+ /* istanbul ignore if */
3259
+ if (!processOk(global.process)) return function() {};
3260
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
3261
+ if (loaded === false) load();
3262
+ var ev = "exit";
3263
+ if (opts && opts.alwaysLast) ev = "afterexit";
3264
+ var remove = function() {
3265
+ emitter.removeListener(ev, cb);
3266
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) unload();
3267
+ };
3268
+ emitter.on(ev, cb);
3269
+ return remove;
3270
+ };
3271
+ var unload = function unload() {
3272
+ if (!loaded || !processOk(global.process)) return;
3273
+ loaded = false;
3274
+ signals.forEach(function(sig) {
3275
+ try {
3276
+ process.removeListener(sig, sigListeners[sig]);
3277
+ } catch (er) {}
3278
+ });
3279
+ process.emit = originalProcessEmit;
3280
+ process.reallyExit = originalProcessReallyExit;
3281
+ emitter.count -= 1;
3282
+ };
3283
+ module.exports.unload = unload;
3284
+ var emit = function emit(event, code, signal) {
3285
+ /* istanbul ignore if */
3286
+ if (emitter.emitted[event]) return;
3287
+ emitter.emitted[event] = true;
3288
+ emitter.emit(event, code, signal);
3289
+ };
3290
+ var sigListeners = {};
3291
+ signals.forEach(function(sig) {
3292
+ sigListeners[sig] = function listener() {
3293
+ /* istanbul ignore if */
3294
+ if (!processOk(global.process)) return;
3295
+ if (process.listeners(sig).length === emitter.count) {
3296
+ unload();
3297
+ emit("exit", null, sig);
3298
+ /* istanbul ignore next */
3299
+ emit("afterexit", null, sig);
3300
+ /* istanbul ignore next */
3301
+ if (isWin && sig === "SIGHUP") sig = "SIGINT";
3302
+ /* istanbul ignore next */
3303
+ process.kill(process.pid, sig);
3304
+ }
3305
+ };
3306
+ });
3307
+ module.exports.signals = function() {
3308
+ return signals;
3309
+ };
3310
+ var loaded = false;
3311
+ var load = function load() {
3312
+ if (loaded || !processOk(global.process)) return;
3313
+ loaded = true;
3314
+ emitter.count += 1;
3315
+ signals = signals.filter(function(sig) {
3316
+ try {
3317
+ process.on(sig, sigListeners[sig]);
3318
+ return true;
3319
+ } catch (er) {
3320
+ return false;
3321
+ }
3322
+ });
3323
+ process.emit = processEmit;
3324
+ process.reallyExit = processReallyExit;
3325
+ };
3326
+ module.exports.load = load;
3327
+ var originalProcessReallyExit = process.reallyExit;
3328
+ var processReallyExit = function processReallyExit(code) {
3329
+ /* istanbul ignore if */
3330
+ if (!processOk(global.process)) return;
3331
+ process.exitCode = code || /* istanbul ignore next */ 0;
3332
+ emit("exit", process.exitCode, null);
3333
+ /* istanbul ignore next */
3334
+ emit("afterexit", process.exitCode, null);
3335
+ /* istanbul ignore next */
3336
+ originalProcessReallyExit.call(process, process.exitCode);
3337
+ };
3338
+ var originalProcessEmit = process.emit;
3339
+ var processEmit = function processEmit(ev, arg) {
3340
+ if (ev === "exit" && processOk(global.process)) {
3341
+ /* istanbul ignore else */
3342
+ if (arg !== void 0) process.exitCode = arg;
3343
+ var ret = originalProcessEmit.apply(this, arguments);
3344
+ /* istanbul ignore next */
3345
+ emit("exit", process.exitCode, null);
3346
+ /* istanbul ignore next */
3347
+ emit("afterexit", process.exitCode, null);
3348
+ /* istanbul ignore next */
3349
+ return ret;
3350
+ } else return originalProcessEmit.apply(this, arguments);
3351
+ };
3352
+ }
3353
+ }));
3354
+ //#endregion
3355
+ //#region ../../node_modules/proper-lockfile/lib/mtime-precision.js
3356
+ var require_mtime_precision = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3357
+ const cacheSymbol = Symbol();
3358
+ function probe(file, fs, callback) {
3359
+ const cachedPrecision = fs[cacheSymbol];
3360
+ if (cachedPrecision) return fs.stat(file, (err, stat) => {
3361
+ /* istanbul ignore if */
3362
+ if (err) return callback(err);
3363
+ callback(null, stat.mtime, cachedPrecision);
3364
+ });
3365
+ const mtime = /* @__PURE__ */ new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
3366
+ fs.utimes(file, mtime, mtime, (err) => {
3367
+ /* istanbul ignore if */
3368
+ if (err) return callback(err);
3369
+ fs.stat(file, (err, stat) => {
3370
+ /* istanbul ignore if */
3371
+ if (err) return callback(err);
3372
+ const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
3373
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
3374
+ callback(null, stat.mtime, precision);
3375
+ });
3376
+ });
3377
+ }
3378
+ function getMtime(precision) {
3379
+ let now = Date.now();
3380
+ if (precision === "s") now = Math.ceil(now / 1e3) * 1e3;
3381
+ return new Date(now);
3382
+ }
3383
+ module.exports.probe = probe;
3384
+ module.exports.getMtime = getMtime;
3385
+ }));
3386
+ //#endregion
3387
+ //#region ../../node_modules/proper-lockfile/lib/lockfile.js
3388
+ var require_lockfile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3389
+ const path$1 = __require("path");
3390
+ const fs = require_graceful_fs();
3391
+ const retry = require_retry();
3392
+ const onExit = require_signal_exit();
3393
+ const mtimePrecision = require_mtime_precision();
3394
+ const locks = {};
3395
+ function getLockFile(file, options) {
3396
+ return options.lockfilePath || `${file}.lock`;
3397
+ }
3398
+ function resolveCanonicalPath(file, options, callback) {
3399
+ if (!options.realpath) return callback(null, path$1.resolve(file));
3400
+ options.fs.realpath(file, callback);
3401
+ }
3402
+ function acquireLock(file, options, callback) {
3403
+ const lockfilePath = getLockFile(file, options);
3404
+ options.fs.mkdir(lockfilePath, (err) => {
3405
+ if (!err) return mtimePrecision.probe(lockfilePath, options.fs, (err, mtime, mtimePrecision) => {
3406
+ /* istanbul ignore if */
3407
+ if (err) {
3408
+ options.fs.rmdir(lockfilePath, () => {});
3409
+ return callback(err);
3410
+ }
3411
+ callback(null, mtime, mtimePrecision);
3412
+ });
3413
+ if (err.code !== "EEXIST") return callback(err);
3414
+ if (options.stale <= 0) return callback(Object.assign(/* @__PURE__ */ new Error("Lock file is already being held"), {
3415
+ code: "ELOCKED",
3416
+ file
3417
+ }));
3418
+ options.fs.stat(lockfilePath, (err, stat) => {
3419
+ if (err) {
3420
+ if (err.code === "ENOENT") return acquireLock(file, {
3421
+ ...options,
3422
+ stale: 0
3423
+ }, callback);
3424
+ return callback(err);
3425
+ }
3426
+ if (!isLockStale(stat, options)) return callback(Object.assign(/* @__PURE__ */ new Error("Lock file is already being held"), {
3427
+ code: "ELOCKED",
3428
+ file
3429
+ }));
3430
+ removeLock(file, options, (err) => {
3431
+ if (err) return callback(err);
3432
+ acquireLock(file, {
3433
+ ...options,
3434
+ stale: 0
3435
+ }, callback);
3436
+ });
3437
+ });
3438
+ });
3439
+ }
3440
+ function isLockStale(stat, options) {
3441
+ return stat.mtime.getTime() < Date.now() - options.stale;
3442
+ }
3443
+ function removeLock(file, options, callback) {
3444
+ options.fs.rmdir(getLockFile(file, options), (err) => {
3445
+ if (err && err.code !== "ENOENT") return callback(err);
3446
+ callback();
3447
+ });
3448
+ }
3449
+ function updateLock(file, options) {
3450
+ const lock = locks[file];
3451
+ /* istanbul ignore if */
3452
+ if (lock.updateTimeout) return;
3453
+ lock.updateDelay = lock.updateDelay || options.update;
3454
+ lock.updateTimeout = setTimeout(() => {
3455
+ lock.updateTimeout = null;
3456
+ options.fs.stat(lock.lockfilePath, (err, stat) => {
3457
+ const isOverThreshold = lock.lastUpdate + options.stale < Date.now();
3458
+ if (err) {
3459
+ if (err.code === "ENOENT" || isOverThreshold) return setLockAsCompromised(file, lock, Object.assign(err, { code: "ECOMPROMISED" }));
3460
+ lock.updateDelay = 1e3;
3461
+ return updateLock(file, options);
3462
+ }
3463
+ if (!(lock.mtime.getTime() === stat.mtime.getTime())) return setLockAsCompromised(file, lock, Object.assign(/* @__PURE__ */ new Error("Unable to update lock within the stale threshold"), { code: "ECOMPROMISED" }));
3464
+ const mtime = mtimePrecision.getMtime(lock.mtimePrecision);
3465
+ options.fs.utimes(lock.lockfilePath, mtime, mtime, (err) => {
3466
+ const isOverThreshold = lock.lastUpdate + options.stale < Date.now();
3467
+ if (lock.released) return;
3468
+ if (err) {
3469
+ if (err.code === "ENOENT" || isOverThreshold) return setLockAsCompromised(file, lock, Object.assign(err, { code: "ECOMPROMISED" }));
3470
+ lock.updateDelay = 1e3;
3471
+ return updateLock(file, options);
3472
+ }
3473
+ lock.mtime = mtime;
3474
+ lock.lastUpdate = Date.now();
3475
+ lock.updateDelay = null;
3476
+ updateLock(file, options);
3477
+ });
3478
+ });
3479
+ }, lock.updateDelay);
3480
+ /* istanbul ignore else */
3481
+ if (lock.updateTimeout.unref) lock.updateTimeout.unref();
3482
+ }
3483
+ function setLockAsCompromised(file, lock, err) {
3484
+ lock.released = true;
3485
+ /* istanbul ignore if */
3486
+ if (lock.updateTimeout) clearTimeout(lock.updateTimeout);
3487
+ if (locks[file] === lock) delete locks[file];
3488
+ lock.options.onCompromised(err);
3489
+ }
3490
+ function lock(file, options, callback) {
3491
+ /* istanbul ignore next */
3492
+ options = {
3493
+ stale: 1e4,
3494
+ update: null,
3495
+ realpath: true,
3496
+ retries: 0,
3497
+ fs,
3498
+ onCompromised: (err) => {
3499
+ throw err;
3500
+ },
3501
+ ...options
3502
+ };
3503
+ options.retries = options.retries || 0;
3504
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
3505
+ options.stale = Math.max(options.stale || 0, 2e3);
3506
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
3507
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1e3);
3508
+ resolveCanonicalPath(file, options, (err, file) => {
3509
+ if (err) return callback(err);
3510
+ const operation = retry.operation(options.retries);
3511
+ operation.attempt(() => {
3512
+ acquireLock(file, options, (err, mtime, mtimePrecision) => {
3513
+ if (operation.retry(err)) return;
3514
+ if (err) return callback(operation.mainError());
3515
+ const lock = locks[file] = {
3516
+ lockfilePath: getLockFile(file, options),
3517
+ mtime,
3518
+ mtimePrecision,
3519
+ options,
3520
+ lastUpdate: Date.now()
3521
+ };
3522
+ updateLock(file, options);
3523
+ callback(null, (releasedCallback) => {
3524
+ if (lock.released) return releasedCallback && releasedCallback(Object.assign(/* @__PURE__ */ new Error("Lock is already released"), { code: "ERELEASED" }));
3525
+ unlock(file, {
3526
+ ...options,
3527
+ realpath: false
3528
+ }, releasedCallback);
3529
+ });
3530
+ });
3531
+ });
3532
+ });
3533
+ }
3534
+ function unlock(file, options, callback) {
3535
+ options = {
3536
+ fs,
3537
+ realpath: true,
3538
+ ...options
3539
+ };
3540
+ resolveCanonicalPath(file, options, (err, file) => {
3541
+ if (err) return callback(err);
3542
+ const lock = locks[file];
3543
+ if (!lock) return callback(Object.assign(/* @__PURE__ */ new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
3544
+ lock.updateTimeout && clearTimeout(lock.updateTimeout);
3545
+ lock.released = true;
3546
+ delete locks[file];
3547
+ removeLock(file, options, callback);
3548
+ });
3549
+ }
3550
+ function check(file, options, callback) {
3551
+ options = {
3552
+ stale: 1e4,
3553
+ realpath: true,
3554
+ fs,
3555
+ ...options
3556
+ };
3557
+ options.stale = Math.max(options.stale || 0, 2e3);
3558
+ resolveCanonicalPath(file, options, (err, file) => {
3559
+ if (err) return callback(err);
3560
+ options.fs.stat(getLockFile(file, options), (err, stat) => {
3561
+ if (err) return err.code === "ENOENT" ? callback(null, false) : callback(err);
3562
+ return callback(null, !isLockStale(stat, options));
3563
+ });
3564
+ });
3565
+ }
3566
+ function getLocks() {
3567
+ return locks;
3568
+ }
3569
+ /* istanbul ignore next */
3570
+ onExit(() => {
3571
+ for (const file in locks) {
3572
+ const options = locks[file].options;
3573
+ try {
3574
+ options.fs.rmdirSync(getLockFile(file, options));
3575
+ } catch (e) {}
3576
+ }
3577
+ });
3578
+ module.exports.lock = lock;
3579
+ module.exports.unlock = unlock;
3580
+ module.exports.check = check;
3581
+ module.exports.getLocks = getLocks;
3582
+ }));
3583
+ //#endregion
3584
+ //#region ../../node_modules/proper-lockfile/lib/adapter.js
3585
+ var require_adapter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3586
+ const fs = require_graceful_fs();
3587
+ function createSyncFs(fs) {
3588
+ const methods = [
3589
+ "mkdir",
3590
+ "realpath",
3591
+ "stat",
3592
+ "rmdir",
3593
+ "utimes"
3594
+ ];
3595
+ const newFs = { ...fs };
3596
+ methods.forEach((method) => {
3597
+ newFs[method] = (...args) => {
3598
+ const callback = args.pop();
3599
+ let ret;
3600
+ try {
3601
+ ret = fs[`${method}Sync`](...args);
3602
+ } catch (err) {
3603
+ return callback(err);
3604
+ }
3605
+ callback(null, ret);
3606
+ };
3607
+ });
3608
+ return newFs;
3609
+ }
3610
+ function toPromise(method) {
3611
+ return (...args) => new Promise((resolve, reject) => {
3612
+ args.push((err, result) => {
3613
+ if (err) reject(err);
3614
+ else resolve(result);
3615
+ });
3616
+ method(...args);
3617
+ });
3618
+ }
3619
+ function toSync(method) {
3620
+ return (...args) => {
3621
+ let err;
3622
+ let result;
3623
+ args.push((_err, _result) => {
3624
+ err = _err;
3625
+ result = _result;
3626
+ });
3627
+ method(...args);
3628
+ if (err) throw err;
3629
+ return result;
3630
+ };
3631
+ }
3632
+ function toSyncOptions(options) {
3633
+ options = { ...options };
3634
+ options.fs = createSyncFs(options.fs || fs);
3635
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) throw Object.assign(/* @__PURE__ */ new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
3636
+ return options;
3637
+ }
3638
+ module.exports = {
3639
+ toPromise,
3640
+ toSync,
3641
+ toSyncOptions
3642
+ };
3643
+ }));
3644
+ (/* @__PURE__ */ __commonJSMin(((exports, module) => {
3645
+ const lockfile = require_lockfile();
3646
+ const { toPromise, toSync, toSyncOptions } = require_adapter();
3647
+ async function lock(file, options) {
3648
+ const release = await toPromise(lockfile.lock)(file, options);
3649
+ return toPromise(release);
3650
+ }
3651
+ function lockSync(file, options) {
3652
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
3653
+ return toSync(release);
3654
+ }
3655
+ function unlock(file, options) {
3656
+ return toPromise(lockfile.unlock)(file, options);
3657
+ }
3658
+ function unlockSync(file, options) {
3659
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
3660
+ }
3661
+ function check(file, options) {
3662
+ return toPromise(lockfile.check)(file, options);
3663
+ }
3664
+ function checkSync(file, options) {
3665
+ return toSync(lockfile.check)(file, toSyncOptions(options));
3666
+ }
3667
+ module.exports = lock;
3668
+ module.exports.lock = lock;
3669
+ module.exports.unlock = unlock;
3670
+ module.exports.lockSync = lockSync;
3671
+ module.exports.unlockSync = unlockSync;
3672
+ module.exports.check = check;
3673
+ module.exports.checkSync = checkSync;
3674
+ })))();
3675
+ //#endregion
3676
+ export { __commonJSMin as C, setLocalVcsCommandObserver as S, __toESM as T, readFileAtCommit as _, diffFileSummaries as a, resolveRevision as b, diffTrees as c, gitAt as d, gitCommonDir as f, parseGitRemote as g, listTrackedFilesAtCommit as h, diff as i, diffWorkingTree as l, listCommitRange as m, createBlobBatchReader as n, diffFileSummariesTrees as o, jjRevisionIsConflicted as p, detectLocalVcs as r, diffFileSummariesWorkingTree as s, LocalVcsToolsMissingError as t, git as u, resolveRepoContext as v, __require as w, splitGitPatchFiles as x, resolveRepoContextSync as y };