@marcoscale98/pi-extensible-workflows 5.14.1-fork.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +536 -0
  2. package/README.md +64 -0
  3. package/dist/src/agent-execution.d.ts +338 -0
  4. package/dist/src/agent-execution.js +1633 -0
  5. package/dist/src/background-widget.d.ts +74 -0
  6. package/dist/src/background-widget.js +1340 -0
  7. package/dist/src/budget.d.ts +38 -0
  8. package/dist/src/budget.js +188 -0
  9. package/dist/src/changelog.d.ts +6 -0
  10. package/dist/src/changelog.js +112 -0
  11. package/dist/src/decoders.d.ts +96 -0
  12. package/dist/src/decoders.js +629 -0
  13. package/dist/src/execution.d.ts +19 -0
  14. package/dist/src/execution.js +749 -0
  15. package/dist/src/herdr.d.ts +53 -0
  16. package/dist/src/herdr.js +270 -0
  17. package/dist/src/host-delivery.d.ts +95 -0
  18. package/dist/src/host-delivery.js +376 -0
  19. package/dist/src/host-navigator.d.ts +83 -0
  20. package/dist/src/host-navigator.js +1087 -0
  21. package/dist/src/host-phases.d.ts +89 -0
  22. package/dist/src/host-phases.js +320 -0
  23. package/dist/src/host-recovery.d.ts +141 -0
  24. package/dist/src/host-recovery.js +356 -0
  25. package/dist/src/host-runtime.d.ts +78 -0
  26. package/dist/src/host-runtime.js +378 -0
  27. package/dist/src/host-view.d.ts +116 -0
  28. package/dist/src/host-view.js +868 -0
  29. package/dist/src/host.d.ts +40 -0
  30. package/dist/src/host.js +1641 -0
  31. package/dist/src/index.d.ts +29 -0
  32. package/dist/src/index.js +13725 -0
  33. package/dist/src/index.js.map +6 -0
  34. package/dist/src/io.d.ts +14 -0
  35. package/dist/src/io.js +82 -0
  36. package/dist/src/package-identity.d.ts +4 -0
  37. package/dist/src/package-identity.js +6 -0
  38. package/dist/src/paths.d.ts +14 -0
  39. package/dist/src/paths.js +51 -0
  40. package/dist/src/persistence.d.ts +5 -0
  41. package/dist/src/persistence.js +5 -0
  42. package/dist/src/pi-runtime-adapter.d.ts +27 -0
  43. package/dist/src/pi-runtime-adapter.js +243 -0
  44. package/dist/src/pi-runtime-runner.d.ts +42 -0
  45. package/dist/src/pi-runtime-runner.js +505 -0
  46. package/dist/src/registry.d.ts +48 -0
  47. package/dist/src/registry.js +379 -0
  48. package/dist/src/retention.d.ts +17 -0
  49. package/dist/src/retention.js +195 -0
  50. package/dist/src/runtime/agent-runner.d.ts +143 -0
  51. package/dist/src/runtime/agent-runner.js +12 -0
  52. package/dist/src/runtime/index.d.ts +2 -0
  53. package/dist/src/runtime/index.js +2 -0
  54. package/dist/src/runtime/namespace.d.ts +14 -0
  55. package/dist/src/runtime/namespace.js +1 -0
  56. package/dist/src/runtime/workflow-result.d.ts +2 -0
  57. package/dist/src/runtime/workflow-result.js +6 -0
  58. package/dist/src/session-handoff.d.ts +2 -0
  59. package/dist/src/session-handoff.js +82 -0
  60. package/dist/src/session-lease.d.ts +12 -0
  61. package/dist/src/session-lease.js +180 -0
  62. package/dist/src/store.d.ts +95 -0
  63. package/dist/src/store.js +951 -0
  64. package/dist/src/subagent-manager-handle.d.ts +4 -0
  65. package/dist/src/subagent-manager-handle.js +6 -0
  66. package/dist/src/tool-timing.d.ts +12 -0
  67. package/dist/src/tool-timing.js +33 -0
  68. package/dist/src/trajectory-contracts.d.ts +8 -0
  69. package/dist/src/trajectory-contracts.js +9 -0
  70. package/dist/src/trajectory-host-handle.d.ts +12 -0
  71. package/dist/src/trajectory-host-handle.js +6 -0
  72. package/dist/src/trajectory.d.ts +128 -0
  73. package/dist/src/trajectory.js +594 -0
  74. package/dist/src/types.d.ts +960 -0
  75. package/dist/src/types.js +60 -0
  76. package/dist/src/utils.d.ts +57 -0
  77. package/dist/src/utils.js +225 -0
  78. package/dist/src/validation.d.ts +29 -0
  79. package/dist/src/validation.js +1100 -0
  80. package/dist/src/workflow-artifacts.d.ts +14 -0
  81. package/dist/src/workflow-artifacts.js +40 -0
  82. package/dist/starter/index.d.ts +1 -0
  83. package/dist/starter/index.js +103 -0
  84. package/dist/starter/index.js.map +6 -0
  85. package/dist/starter/review-loop.d.ts +72 -0
  86. package/dist/starter/review-loop.js +43 -0
  87. package/dist/starter/roles/developer.md +6 -0
  88. package/dist/starter/roles/oracle.md +18 -0
  89. package/dist/starter/roles/researcher.md +20 -0
  90. package/dist/starter/roles/reviewer.md +19 -0
  91. package/dist/starter/roles/scout.md +18 -0
  92. package/dist/subagents/index.d.ts +8 -0
  93. package/dist/subagents/index.js +8021 -0
  94. package/dist/subagents/index.js.map +6 -0
  95. package/dist/subagents/src/contracts.d.ts +173 -0
  96. package/dist/subagents/src/contracts.js +68 -0
  97. package/dist/subagents/src/decode.d.ts +15 -0
  98. package/dist/subagents/src/decode.js +182 -0
  99. package/dist/subagents/src/index.d.ts +12 -0
  100. package/dist/subagents/src/index.js +180 -0
  101. package/dist/subagents/src/manager.d.ts +3 -0
  102. package/dist/subagents/src/manager.js +1636 -0
  103. package/dist/subagents/src/navigator.d.ts +5 -0
  104. package/dist/subagents/src/navigator.js +627 -0
  105. package/dist/subagents/src/view.d.ts +70 -0
  106. package/dist/subagents/src/view.js +387 -0
  107. package/dist/subagents/src/worktree.d.ts +34 -0
  108. package/dist/subagents/src/worktree.js +68 -0
  109. package/dist/trajectory/assets/favicon.png +0 -0
  110. package/dist/trajectory/assets/index.html +772 -0
  111. package/dist/trajectory/assets/marked.min.js +6 -0
  112. package/dist/trajectory/assets/morphdom.min.js +1 -0
  113. package/dist/trajectory/index.d.ts +5 -0
  114. package/dist/trajectory/index.js +3459 -0
  115. package/dist/trajectory/index.js.map +6 -0
  116. package/dist/trajectory/src/assets/favicon.png +0 -0
  117. package/dist/trajectory/src/assets/index.html +772 -0
  118. package/dist/trajectory/src/assets/marked.min.js +6 -0
  119. package/dist/trajectory/src/assets/morphdom.min.js +1 -0
  120. package/dist/trajectory/src/export.d.ts +25 -0
  121. package/dist/trajectory/src/export.js +80 -0
  122. package/dist/trajectory/src/index.d.ts +26 -0
  123. package/dist/trajectory/src/index.js +732 -0
  124. package/dist/trajectory/src/server.d.ts +7 -0
  125. package/dist/trajectory/src/server.js +2534 -0
  126. package/dist/trajectory/src/server.js.map +6 -0
  127. package/examples/advanced-patterns/auto-model-router.mjs +78 -0
  128. package/examples/workflow-extension-template/README.md +37 -0
  129. package/examples/workflow-extension-template/extension.test.mjs +59 -0
  130. package/examples/workflow-extension-template/index.js +51 -0
  131. package/examples/workflow-extension-template/roles/reviewer.md +4 -0
  132. package/package.json +105 -0
  133. package/skills/pi-extensible-workflows/SKILL.md +160 -0
  134. package/src/agent-execution.ts +1533 -0
  135. package/src/background-widget.ts +1496 -0
  136. package/src/budget.ts +109 -0
  137. package/src/changelog.ts +114 -0
  138. package/src/decoders.ts +567 -0
  139. package/src/execution.ts +652 -0
  140. package/src/herdr.ts +240 -0
  141. package/src/host-delivery.ts +346 -0
  142. package/src/host-navigator.ts +871 -0
  143. package/src/host-phases.ts +264 -0
  144. package/src/host-recovery.ts +333 -0
  145. package/src/host-runtime.ts +373 -0
  146. package/src/host-view.ts +828 -0
  147. package/src/host.ts +1502 -0
  148. package/src/index.ts +29 -0
  149. package/src/io.ts +73 -0
  150. package/src/package-identity.ts +7 -0
  151. package/src/paths.ts +49 -0
  152. package/src/persistence.ts +11 -0
  153. package/src/pi-runtime-adapter.ts +247 -0
  154. package/src/pi-runtime-runner.ts +436 -0
  155. package/src/registry.ts +321 -0
  156. package/src/retention.ts +178 -0
  157. package/src/runtime/agent-runner.ts +158 -0
  158. package/src/runtime/index.ts +2 -0
  159. package/src/runtime/namespace.ts +16 -0
  160. package/src/runtime/workflow-result.ts +8 -0
  161. package/src/session-handoff.ts +78 -0
  162. package/src/session-lease.ts +125 -0
  163. package/src/store.ts +832 -0
  164. package/src/subagent-manager-handle.ts +8 -0
  165. package/src/tool-timing.ts +47 -0
  166. package/src/trajectory-contracts.ts +13 -0
  167. package/src/trajectory-host-handle.ts +16 -0
  168. package/src/trajectory.ts +543 -0
  169. package/src/types.ts +374 -0
  170. package/src/utils.ts +192 -0
  171. package/src/validation.ts +910 -0
  172. package/src/workflow-artifacts.ts +35 -0
  173. package/starter/index.ts +35 -0
  174. package/starter/prompts/council.md +16 -0
  175. package/starter/prompts/deep-research.md +16 -0
  176. package/starter/prompts/oracle.md +14 -0
  177. package/starter/prompts/parallel-review.md +22 -0
  178. package/starter/prompts/parallel-scout.md +16 -0
  179. package/starter/prompts/review-loop.md +14 -0
  180. package/starter/prompts/review.md +14 -0
  181. package/starter/prompts/scout.md +14 -0
  182. package/starter/review-loop.ts +73 -0
  183. package/starter/roles/developer.md +6 -0
  184. package/starter/roles/oracle.md +18 -0
  185. package/starter/roles/researcher.md +20 -0
  186. package/starter/roles/reviewer.md +19 -0
  187. package/starter/roles/scout.md +18 -0
  188. package/subagents/README.md +145 -0
  189. package/subagents/index.ts +8 -0
  190. package/subagents/src/contracts.ts +176 -0
  191. package/subagents/src/decode.ts +158 -0
  192. package/subagents/src/index.ts +194 -0
  193. package/subagents/src/manager.ts +1560 -0
  194. package/subagents/src/navigator.ts +488 -0
  195. package/subagents/src/view.ts +376 -0
  196. package/subagents/src/worktree.ts +99 -0
  197. package/trajectory/index.ts +5 -0
  198. package/trajectory/src/assets/favicon.png +0 -0
  199. package/trajectory/src/assets/index.html +772 -0
  200. package/trajectory/src/assets/marked.min.js +6 -0
  201. package/trajectory/src/assets/morphdom.min.js +1 -0
  202. package/trajectory/src/export.ts +85 -0
  203. package/trajectory/src/index.ts +604 -0
  204. package/trajectory/src/server.ts +447 -0
@@ -0,0 +1,2534 @@
1
+ // trajectory/src/server.ts
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import { readFile, rm, writeFile } from "node:fs/promises";
5
+ import { fileURLToPath } from "node:url";
6
+ import { URL } from "node:url";
7
+
8
+ // src/trajectory-contracts.ts
9
+ var TRAJECTORY_ACTIONS = ["checkpoint-approve", "checkpoint-reject", "pause", "resume", "steer", "stop", "retry", "share"];
10
+ function isTrajectoryAction(value) {
11
+ return typeof value === "string" && TRAJECTORY_ACTIONS.includes(value);
12
+ }
13
+ function isTrajectoryTarget(value) {
14
+ const target = value;
15
+ return typeof value === "object" && value !== null && !Array.isArray(value) && (target.kind === "run" || target.kind === "subagent") && typeof target.id === "string" && target.id.length >= 1 && target.id.length <= 200;
16
+ }
17
+ function trajectoryActionError(action, target) {
18
+ return target.kind === "subagent" && (action === "checkpoint-approve" || action === "checkpoint-reject" || action === "pause" || action === "resume" || action === "share") ? `Trajectory action ${action} is not supported for subagent targets` : target.kind === "run" && action === "steer" ? "Trajectory action steer is not supported for run targets" : void 0;
19
+ }
20
+
21
+ // src/paths.ts
22
+ import { realpathSync } from "node:fs";
23
+ import { basename, join, resolve } from "node:path";
24
+
25
+ // src/types.ts
26
+ var WORKFLOW_AGENT_STALL_THRESHOLD_MS = 10 * 60 * 1e3;
27
+ var WORKFLOW_ERROR_BRAND = /* @__PURE__ */ Symbol.for("pi-extensible-workflows.workflow-error");
28
+ var WorkflowError = class extends Error {
29
+ constructor(code, message) {
30
+ super(message);
31
+ this.code = code;
32
+ this.name = "WorkflowError";
33
+ this[WORKFLOW_ERROR_BRAND] = true;
34
+ }
35
+ code;
36
+ static [Symbol.hasInstance](value) {
37
+ if (Function.prototype[Symbol.hasInstance].call(this, value)) return true;
38
+ return Object.hasOwn(this, WORKFLOW_ERROR_BRAND) && typeof value === "object" && value !== null && WORKFLOW_ERROR_BRAND in value;
39
+ }
40
+ };
41
+ Object.defineProperty(WorkflowError, WORKFLOW_ERROR_BRAND, { value: true });
42
+
43
+ // ../../node_modules/balanced-match/dist/esm/index.js
44
+ var balanced = (a, b, str) => {
45
+ const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
46
+ const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
47
+ const r = ma !== null && mb != null && range(ma, mb, str);
48
+ return r && {
49
+ start: r[0],
50
+ end: r[1],
51
+ pre: str.slice(0, r[0]),
52
+ body: str.slice(r[0] + ma.length, r[1]),
53
+ post: str.slice(r[1] + mb.length)
54
+ };
55
+ };
56
+ var maybeMatch = (reg, str) => {
57
+ const m = str.match(reg);
58
+ return m ? m[0] : null;
59
+ };
60
+ var range = (a, b, str) => {
61
+ let begs, beg, left, right = void 0, result;
62
+ let ai = str.indexOf(a);
63
+ let bi = str.indexOf(b, ai + 1);
64
+ let i = ai;
65
+ if (ai >= 0 && bi > 0) {
66
+ if (a === b) {
67
+ return [ai, bi];
68
+ }
69
+ begs = [];
70
+ left = str.length;
71
+ while (i >= 0 && !result) {
72
+ if (i === ai) {
73
+ begs.push(i);
74
+ ai = str.indexOf(a, i + 1);
75
+ } else if (begs.length === 1) {
76
+ const r = begs.pop();
77
+ if (r !== void 0)
78
+ result = [r, bi];
79
+ } else {
80
+ beg = begs.pop();
81
+ if (beg !== void 0 && beg < left) {
82
+ left = beg;
83
+ right = bi;
84
+ }
85
+ bi = str.indexOf(b, i + 1);
86
+ }
87
+ i = ai < bi && ai >= 0 ? ai : bi;
88
+ }
89
+ if (begs.length && right !== void 0) {
90
+ result = [left, right];
91
+ }
92
+ }
93
+ return result;
94
+ };
95
+
96
+ // ../../node_modules/brace-expansion/dist/esm/index.js
97
+ var escSlash = "\0SLASH" + Math.random() + "\0";
98
+ var escOpen = "\0OPEN" + Math.random() + "\0";
99
+ var escClose = "\0CLOSE" + Math.random() + "\0";
100
+ var escComma = "\0COMMA" + Math.random() + "\0";
101
+ var escPeriod = "\0PERIOD" + Math.random() + "\0";
102
+ var escSlashPattern = new RegExp(escSlash, "g");
103
+ var escOpenPattern = new RegExp(escOpen, "g");
104
+ var escClosePattern = new RegExp(escClose, "g");
105
+ var escCommaPattern = new RegExp(escComma, "g");
106
+ var escPeriodPattern = new RegExp(escPeriod, "g");
107
+ var slashPattern = /\\\\/g;
108
+ var openPattern = /\\{/g;
109
+ var closePattern = /\\}/g;
110
+ var commaPattern = /\\,/g;
111
+ var periodPattern = /\\\./g;
112
+ var EXPANSION_MAX = 1e5;
113
+ var EXPANSION_MAX_LENGTH = 4e6;
114
+ function numeric(str) {
115
+ return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
116
+ }
117
+ function escapeBraces(str) {
118
+ return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);
119
+ }
120
+ function unescapeBraces(str) {
121
+ return str.replace(escSlashPattern, "\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");
122
+ }
123
+ function parseCommaParts(str) {
124
+ if (!str) {
125
+ return [""];
126
+ }
127
+ const parts = [];
128
+ const m = balanced("{", "}", str);
129
+ if (!m) {
130
+ return str.split(",");
131
+ }
132
+ const { pre, body, post } = m;
133
+ const p = pre.split(",");
134
+ p[p.length - 1] += "{" + body + "}";
135
+ const postParts = parseCommaParts(post);
136
+ if (post.length) {
137
+ ;
138
+ p[p.length - 1] += postParts.shift();
139
+ p.push.apply(p, postParts);
140
+ }
141
+ parts.push.apply(parts, p);
142
+ return parts;
143
+ }
144
+ function expand(str, options = {}) {
145
+ if (!str) {
146
+ return [];
147
+ }
148
+ const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH } = options;
149
+ if (str.slice(0, 2) === "{}") {
150
+ str = "\\{\\}" + str.slice(2);
151
+ }
152
+ return expand_(escapeBraces(str), max, maxLength, true).map(unescapeBraces);
153
+ }
154
+ function embrace(str) {
155
+ return "{" + str + "}";
156
+ }
157
+ function isPadded(el) {
158
+ return /^-?0\d/.test(el);
159
+ }
160
+ function lte(i, y) {
161
+ return i <= y;
162
+ }
163
+ function gte(i, y) {
164
+ return i >= y;
165
+ }
166
+ function combine(acc, pre, values, max, maxLength, dropEmpties) {
167
+ const out = [];
168
+ let length = 0;
169
+ for (let a = 0; a < acc.length; a++) {
170
+ for (let v = 0; v < values.length; v++) {
171
+ if (out.length >= max)
172
+ return out;
173
+ const expansion = acc[a] + pre + values[v];
174
+ if (dropEmpties && !expansion)
175
+ continue;
176
+ if (length + expansion.length > maxLength)
177
+ return out;
178
+ out.push(expansion);
179
+ length += expansion.length;
180
+ }
181
+ }
182
+ return out;
183
+ }
184
+ function expandSequence(body, isAlphaSequence, max, maxLength) {
185
+ const n = body.split(/\.\./);
186
+ const N = [];
187
+ if (n[0] === void 0 || n[1] === void 0) {
188
+ return N;
189
+ }
190
+ const x = numeric(n[0]);
191
+ const y = numeric(n[1]);
192
+ const width = Math.max(n[0].length, n[1].length);
193
+ let incr = n.length === 3 && n[2] !== void 0 ? Math.max(Math.abs(numeric(n[2])), 1) : 1;
194
+ let test = lte;
195
+ const reverse = y < x;
196
+ if (reverse) {
197
+ incr *= -1;
198
+ test = gte;
199
+ }
200
+ const pad = n.some(isPadded);
201
+ let length = 0;
202
+ for (let i = x; test(i, y) && N.length < max; i += incr) {
203
+ let c;
204
+ if (isAlphaSequence) {
205
+ c = String.fromCharCode(i);
206
+ if (c === "\\") {
207
+ c = "";
208
+ }
209
+ } else {
210
+ c = String(i);
211
+ if (pad) {
212
+ const need = width - c.length;
213
+ if (need > 0) {
214
+ const z = new Array(need + 1).join("0");
215
+ if (i < 0) {
216
+ c = "-" + z + c.slice(1);
217
+ } else {
218
+ c = z + c;
219
+ }
220
+ }
221
+ }
222
+ }
223
+ if (length + c.length > maxLength)
224
+ break;
225
+ N.push(c);
226
+ length += c.length;
227
+ }
228
+ return N;
229
+ }
230
+ function expand_(str, max, maxLength, isTop) {
231
+ let acc = [""];
232
+ let dropEmpties = false;
233
+ let firstGroup = true;
234
+ for (; ; ) {
235
+ const m = balanced("{", "}", str);
236
+ if (!m) {
237
+ return combine(acc, str, [""], max, maxLength, dropEmpties);
238
+ }
239
+ const pre = m.pre;
240
+ if (/\$$/.test(pre)) {
241
+ acc = combine(acc, pre + "{" + m.body + "}", [""], max, maxLength, dropEmpties && !m.post.length);
242
+ firstGroup = false;
243
+ if (!m.post.length)
244
+ break;
245
+ str = m.post;
246
+ continue;
247
+ }
248
+ const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
249
+ const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
250
+ const isSequence = isNumericSequence || isAlphaSequence;
251
+ const isOptions = m.body.indexOf(",") >= 0;
252
+ if (!isSequence && !isOptions) {
253
+ if (m.post.match(/,(?!,).*\}/)) {
254
+ str = m.pre + "{" + m.body + escClose + m.post;
255
+ isTop = true;
256
+ continue;
257
+ }
258
+ return combine(acc, pre + "{" + m.body + "}" + m.post, [""], max, maxLength, dropEmpties);
259
+ }
260
+ if (firstGroup) {
261
+ dropEmpties = isTop && !isSequence;
262
+ firstGroup = false;
263
+ }
264
+ let values;
265
+ if (isSequence) {
266
+ values = expandSequence(m.body, isAlphaSequence, max, maxLength);
267
+ } else {
268
+ let n = parseCommaParts(m.body);
269
+ if (n.length === 1 && n[0] !== void 0) {
270
+ n = expand_(n[0], max, maxLength, false).map(embrace);
271
+ if (n.length === 1) {
272
+ acc = combine(acc, pre + n[0], [""], max, maxLength, dropEmpties && !m.post.length);
273
+ if (!m.post.length)
274
+ break;
275
+ str = m.post;
276
+ continue;
277
+ }
278
+ }
279
+ let dropsEmpties = dropEmpties && !m.post.length && !pre;
280
+ for (let d = 0; dropsEmpties && d < acc.length; d++) {
281
+ if (acc[d]) {
282
+ dropsEmpties = false;
283
+ }
284
+ }
285
+ values = [];
286
+ let valuesLength = 0;
287
+ outer: for (let j = 0; j < n.length; j++) {
288
+ const expanded = expand_(n[j], max, maxLength, false);
289
+ for (let k = 0; k < expanded.length; k++) {
290
+ const v = expanded[k];
291
+ if (dropsEmpties && !v)
292
+ continue;
293
+ if (values.length >= max || valuesLength + v.length > maxLength) {
294
+ break outer;
295
+ }
296
+ values.push(v);
297
+ valuesLength += v.length;
298
+ }
299
+ }
300
+ }
301
+ acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);
302
+ if (!m.post.length)
303
+ break;
304
+ str = m.post;
305
+ }
306
+ return acc;
307
+ }
308
+
309
+ // ../../node_modules/minimatch/dist/esm/assert-valid-pattern.js
310
+ var MAX_PATTERN_LENGTH = 1024 * 64;
311
+ var assertValidPattern = (pattern) => {
312
+ if (typeof pattern !== "string") {
313
+ throw new TypeError("invalid pattern");
314
+ }
315
+ if (pattern.length > MAX_PATTERN_LENGTH) {
316
+ throw new TypeError("pattern is too long");
317
+ }
318
+ };
319
+
320
+ // ../../node_modules/minimatch/dist/esm/brace-expressions.js
321
+ var posixClasses = {
322
+ "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
323
+ "[:alpha:]": ["\\p{L}\\p{Nl}", true],
324
+ "[:ascii:]": ["\\x00-\\x7f", false],
325
+ "[:blank:]": ["\\p{Zs}\\t", true],
326
+ "[:cntrl:]": ["\\p{Cc}", true],
327
+ "[:digit:]": ["\\p{Nd}", true],
328
+ "[:graph:]": ["\\p{Z}\\p{C}", true, true],
329
+ "[:lower:]": ["\\p{Ll}", true],
330
+ "[:print:]": ["\\p{C}", true],
331
+ "[:punct:]": ["\\p{P}", true],
332
+ "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
333
+ "[:upper:]": ["\\p{Lu}", true],
334
+ "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
335
+ "[:xdigit:]": ["A-Fa-f0-9", false]
336
+ };
337
+ var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
338
+ var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
339
+ var rangesToString = (ranges) => ranges.join("");
340
+ var parseClass = (glob, position) => {
341
+ const pos = position;
342
+ if (glob.charAt(pos) !== "[") {
343
+ throw new Error("not in a brace expression");
344
+ }
345
+ const ranges = [];
346
+ const negs = [];
347
+ let i = pos + 1;
348
+ let sawStart = false;
349
+ let uflag = false;
350
+ let escaping = false;
351
+ let negate = false;
352
+ let endPos = pos;
353
+ let rangeStart = "";
354
+ WHILE: while (i < glob.length) {
355
+ const c = glob.charAt(i);
356
+ if ((c === "!" || c === "^") && i === pos + 1) {
357
+ negate = true;
358
+ i++;
359
+ continue;
360
+ }
361
+ if (c === "]" && sawStart && !escaping) {
362
+ endPos = i + 1;
363
+ break;
364
+ }
365
+ sawStart = true;
366
+ if (c === "\\") {
367
+ if (!escaping) {
368
+ escaping = true;
369
+ i++;
370
+ continue;
371
+ }
372
+ }
373
+ if (c === "[" && !escaping) {
374
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
375
+ if (glob.startsWith(cls, i)) {
376
+ if (rangeStart) {
377
+ return ["$.", false, glob.length - pos, true];
378
+ }
379
+ i += cls.length;
380
+ if (neg)
381
+ negs.push(unip);
382
+ else
383
+ ranges.push(unip);
384
+ uflag = uflag || u;
385
+ continue WHILE;
386
+ }
387
+ }
388
+ }
389
+ escaping = false;
390
+ if (rangeStart) {
391
+ if (c > rangeStart) {
392
+ ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
393
+ } else if (c === rangeStart) {
394
+ ranges.push(braceEscape(c));
395
+ }
396
+ rangeStart = "";
397
+ i++;
398
+ continue;
399
+ }
400
+ if (glob.startsWith("-]", i + 1)) {
401
+ ranges.push(braceEscape(c + "-"));
402
+ i += 2;
403
+ continue;
404
+ }
405
+ if (glob.startsWith("-", i + 1)) {
406
+ rangeStart = c;
407
+ i += 2;
408
+ continue;
409
+ }
410
+ ranges.push(braceEscape(c));
411
+ i++;
412
+ }
413
+ if (endPos < i) {
414
+ return ["", false, 0, false];
415
+ }
416
+ if (!ranges.length && !negs.length) {
417
+ return ["$.", false, glob.length - pos, true];
418
+ }
419
+ if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
420
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
421
+ return [regexpEscape(r), false, endPos - pos, false];
422
+ }
423
+ const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
424
+ const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
425
+ const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
426
+ return [comb, uflag, endPos - pos, true];
427
+ };
428
+
429
+ // ../../node_modules/minimatch/dist/esm/unescape.js
430
+ var unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {
431
+ if (magicalBraces) {
432
+ return windowsPathsNoEscape ? s.replace(/\[([^/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\])\]/g, "$1$2").replace(/\\([^/])/g, "$1");
433
+ }
434
+ return windowsPathsNoEscape ? s.replace(/\[([^/\\{}])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\{}])\]/g, "$1$2").replace(/\\([^/{}])/g, "$1");
435
+ };
436
+
437
+ // ../../node_modules/minimatch/dist/esm/ast.js
438
+ var _a;
439
+ var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
440
+ var isExtglobType = (c) => types.has(c);
441
+ var isExtglobAST = (c) => isExtglobType(c.type);
442
+ var adoptionMap = /* @__PURE__ */ new Map([
443
+ ["!", ["@"]],
444
+ ["?", ["?", "@"]],
445
+ ["@", ["@"]],
446
+ ["*", ["*", "+", "?", "@"]],
447
+ ["+", ["+", "@"]]
448
+ ]);
449
+ var adoptionWithSpaceMap = /* @__PURE__ */ new Map([
450
+ ["!", ["?"]],
451
+ ["@", ["?"]],
452
+ ["+", ["?", "*"]]
453
+ ]);
454
+ var adoptionAnyMap = /* @__PURE__ */ new Map([
455
+ ["!", ["?", "@"]],
456
+ ["?", ["?", "@"]],
457
+ ["@", ["?", "@"]],
458
+ ["*", ["*", "+", "?", "@"]],
459
+ ["+", ["+", "@", "?", "*"]]
460
+ ]);
461
+ var usurpMap = /* @__PURE__ */ new Map([
462
+ ["!", /* @__PURE__ */ new Map([["!", "@"]])],
463
+ [
464
+ "?",
465
+ /* @__PURE__ */ new Map([
466
+ ["*", "*"],
467
+ ["+", "*"]
468
+ ])
469
+ ],
470
+ [
471
+ "@",
472
+ /* @__PURE__ */ new Map([
473
+ ["!", "!"],
474
+ ["?", "?"],
475
+ ["@", "@"],
476
+ ["*", "*"],
477
+ ["+", "+"]
478
+ ])
479
+ ],
480
+ [
481
+ "+",
482
+ /* @__PURE__ */ new Map([
483
+ ["?", "*"],
484
+ ["*", "*"]
485
+ ])
486
+ ]
487
+ ]);
488
+ var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
489
+ var startNoDot = "(?!\\.)";
490
+ var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
491
+ var justDots = /* @__PURE__ */ new Set(["..", "."]);
492
+ var reSpecials = new Set("().*{}+?[]^$\\!");
493
+ var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
494
+ var qmark = "[^/]";
495
+ var star = qmark + "*?";
496
+ var starNoEmpty = qmark + "+?";
497
+ var ID = 0;
498
+ var AST = class {
499
+ type;
500
+ #root;
501
+ #hasMagic;
502
+ #uflag = false;
503
+ #parts = [];
504
+ #parent;
505
+ #parentIndex;
506
+ #negs;
507
+ #filledNegs = false;
508
+ #options;
509
+ #toString;
510
+ // set to true if it's an extglob with no children
511
+ // (which really means one child of '')
512
+ #emptyExt = false;
513
+ id = ++ID;
514
+ get depth() {
515
+ return (this.#parent?.depth ?? -1) + 1;
516
+ }
517
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
518
+ return {
519
+ "@@type": "AST",
520
+ id: this.id,
521
+ type: this.type,
522
+ root: this.#root.id,
523
+ parent: this.#parent?.id,
524
+ depth: this.depth,
525
+ partsLength: this.#parts.length,
526
+ parts: this.#parts
527
+ };
528
+ }
529
+ constructor(type, parent, options = {}) {
530
+ this.type = type;
531
+ if (type)
532
+ this.#hasMagic = true;
533
+ this.#parent = parent;
534
+ this.#root = this.#parent ? this.#parent.#root : this;
535
+ this.#options = this.#root === this ? options : this.#root.#options;
536
+ this.#negs = this.#root === this ? [] : this.#root.#negs;
537
+ if (type === "!" && !this.#root.#filledNegs)
538
+ this.#negs.push(this);
539
+ this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
540
+ }
541
+ get hasMagic() {
542
+ if (this.#hasMagic !== void 0)
543
+ return this.#hasMagic;
544
+ for (const p of this.#parts) {
545
+ if (typeof p === "string")
546
+ continue;
547
+ if (p.type || p.hasMagic)
548
+ return this.#hasMagic = true;
549
+ }
550
+ return this.#hasMagic;
551
+ }
552
+ // reconstructs the pattern
553
+ toString() {
554
+ return this.#toString !== void 0 ? this.#toString : !this.type ? this.#toString = this.#parts.map((p) => String(p)).join("") : this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";
555
+ }
556
+ #fillNegs() {
557
+ if (this !== this.#root)
558
+ throw new Error("should only call on root");
559
+ if (this.#filledNegs)
560
+ return this;
561
+ this.toString();
562
+ this.#filledNegs = true;
563
+ let n;
564
+ while (n = this.#negs.pop()) {
565
+ if (n.type !== "!")
566
+ continue;
567
+ let p = n;
568
+ let pp = p.#parent;
569
+ while (pp) {
570
+ for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
571
+ for (const part of n.#parts) {
572
+ if (typeof part === "string") {
573
+ throw new Error("string part in extglob AST??");
574
+ }
575
+ part.copyIn(pp.#parts[i]);
576
+ }
577
+ }
578
+ p = pp;
579
+ pp = p.#parent;
580
+ }
581
+ }
582
+ return this;
583
+ }
584
+ push(...parts) {
585
+ for (const p of parts) {
586
+ if (p === "")
587
+ continue;
588
+ if (typeof p !== "string" && !(p instanceof _a && p.#parent === this)) {
589
+ throw new Error("invalid part: " + p);
590
+ }
591
+ this.#parts.push(p);
592
+ }
593
+ }
594
+ toJSON() {
595
+ const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];
596
+ if (this.isStart() && !this.type)
597
+ ret.unshift([]);
598
+ if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {
599
+ ret.push({});
600
+ }
601
+ return ret;
602
+ }
603
+ isStart() {
604
+ if (this.#root === this)
605
+ return true;
606
+ if (!this.#parent?.isStart())
607
+ return false;
608
+ if (this.#parentIndex === 0)
609
+ return true;
610
+ const p = this.#parent;
611
+ for (let i = 0; i < this.#parentIndex; i++) {
612
+ const pp = p.#parts[i];
613
+ if (!(pp instanceof _a && pp.type === "!")) {
614
+ return false;
615
+ }
616
+ }
617
+ return true;
618
+ }
619
+ isEnd() {
620
+ if (this.#root === this)
621
+ return true;
622
+ if (this.#parent?.type === "!")
623
+ return true;
624
+ if (!this.#parent?.isEnd())
625
+ return false;
626
+ if (!this.type)
627
+ return this.#parent?.isEnd();
628
+ const pl = this.#parent ? this.#parent.#parts.length : 0;
629
+ return this.#parentIndex === pl - 1;
630
+ }
631
+ copyIn(part) {
632
+ if (typeof part === "string")
633
+ this.push(part);
634
+ else
635
+ this.push(part.clone(this));
636
+ }
637
+ clone(parent) {
638
+ const c = new _a(this.type, parent);
639
+ for (const p of this.#parts) {
640
+ c.copyIn(p);
641
+ }
642
+ return c;
643
+ }
644
+ static #parseAST(str, ast, pos, opt, extDepth) {
645
+ const maxDepth = opt.maxExtglobRecursion ?? 2;
646
+ let escaping = false;
647
+ let inBrace = false;
648
+ let braceStart = -1;
649
+ let braceNeg = false;
650
+ if (ast.type === null) {
651
+ let i2 = pos;
652
+ let acc2 = "";
653
+ while (i2 < str.length) {
654
+ const c = str.charAt(i2++);
655
+ if (escaping || c === "\\") {
656
+ escaping = !escaping;
657
+ acc2 += c;
658
+ continue;
659
+ }
660
+ if (inBrace) {
661
+ if (i2 === braceStart + 1) {
662
+ if (c === "^" || c === "!") {
663
+ braceNeg = true;
664
+ }
665
+ } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
666
+ inBrace = false;
667
+ }
668
+ acc2 += c;
669
+ continue;
670
+ } else if (c === "[") {
671
+ inBrace = true;
672
+ braceStart = i2;
673
+ braceNeg = false;
674
+ acc2 += c;
675
+ continue;
676
+ }
677
+ const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i2) === "(" && extDepth <= maxDepth;
678
+ if (doRecurse) {
679
+ ast.push(acc2);
680
+ acc2 = "";
681
+ const ext2 = new _a(c, ast);
682
+ i2 = _a.#parseAST(str, ext2, i2, opt, extDepth + 1);
683
+ ast.push(ext2);
684
+ continue;
685
+ }
686
+ acc2 += c;
687
+ }
688
+ ast.push(acc2);
689
+ return i2;
690
+ }
691
+ let i = pos + 1;
692
+ let part = new _a(null, ast);
693
+ const parts = [];
694
+ let acc = "";
695
+ while (i < str.length) {
696
+ const c = str.charAt(i++);
697
+ if (escaping || c === "\\") {
698
+ escaping = !escaping;
699
+ acc += c;
700
+ continue;
701
+ }
702
+ if (inBrace) {
703
+ if (i === braceStart + 1) {
704
+ if (c === "^" || c === "!") {
705
+ braceNeg = true;
706
+ }
707
+ } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {
708
+ inBrace = false;
709
+ }
710
+ acc += c;
711
+ continue;
712
+ } else if (c === "[") {
713
+ inBrace = true;
714
+ braceStart = i;
715
+ braceNeg = false;
716
+ acc += c;
717
+ continue;
718
+ }
719
+ const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i) === "(" && /* c8 ignore start - the maxDepth is sufficient here */
720
+ (extDepth <= maxDepth || ast && ast.#canAdoptType(c));
721
+ if (doRecurse) {
722
+ const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
723
+ part.push(acc);
724
+ acc = "";
725
+ const ext2 = new _a(c, part);
726
+ part.push(ext2);
727
+ i = _a.#parseAST(str, ext2, i, opt, extDepth + depthAdd);
728
+ continue;
729
+ }
730
+ if (c === "|") {
731
+ part.push(acc);
732
+ acc = "";
733
+ parts.push(part);
734
+ part = new _a(null, ast);
735
+ continue;
736
+ }
737
+ if (c === ")") {
738
+ if (acc === "" && ast.#parts.length === 0) {
739
+ ast.#emptyExt = true;
740
+ }
741
+ part.push(acc);
742
+ acc = "";
743
+ ast.push(...parts, part);
744
+ return i;
745
+ }
746
+ acc += c;
747
+ }
748
+ ast.type = null;
749
+ ast.#hasMagic = void 0;
750
+ ast.#parts = [str.substring(pos - 1)];
751
+ return i;
752
+ }
753
+ #canAdoptWithSpace(child) {
754
+ return this.#canAdopt(child, adoptionWithSpaceMap);
755
+ }
756
+ #canAdopt(child, map = adoptionMap) {
757
+ if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null) {
758
+ return false;
759
+ }
760
+ const gc = child.#parts[0];
761
+ if (!gc || typeof gc !== "object" || gc.type === null) {
762
+ return false;
763
+ }
764
+ return this.#canAdoptType(gc.type, map);
765
+ }
766
+ #canAdoptType(c, map = adoptionAnyMap) {
767
+ return !!map.get(this.type)?.includes(c);
768
+ }
769
+ #adoptWithSpace(child, index) {
770
+ const gc = child.#parts[0];
771
+ const blank = new _a(null, gc, this.options);
772
+ blank.#parts.push("");
773
+ gc.push(blank);
774
+ this.#adopt(child, index);
775
+ }
776
+ #adopt(child, index) {
777
+ const gc = child.#parts[0];
778
+ this.#parts.splice(index, 1, ...gc.#parts);
779
+ for (const p of gc.#parts) {
780
+ if (typeof p === "object")
781
+ p.#parent = this;
782
+ }
783
+ this.#toString = void 0;
784
+ }
785
+ #canUsurpType(c) {
786
+ const m = usurpMap.get(this.type);
787
+ return !!m?.has(c);
788
+ }
789
+ #canUsurp(child) {
790
+ if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null || this.#parts.length !== 1) {
791
+ return false;
792
+ }
793
+ const gc = child.#parts[0];
794
+ if (!gc || typeof gc !== "object" || gc.type === null) {
795
+ return false;
796
+ }
797
+ return this.#canUsurpType(gc.type);
798
+ }
799
+ #usurp(child) {
800
+ const m = usurpMap.get(this.type);
801
+ const gc = child.#parts[0];
802
+ const nt = m?.get(gc.type);
803
+ if (!nt)
804
+ return false;
805
+ this.#parts = gc.#parts;
806
+ for (const p of this.#parts) {
807
+ if (typeof p === "object") {
808
+ p.#parent = this;
809
+ }
810
+ }
811
+ this.type = nt;
812
+ this.#toString = void 0;
813
+ this.#emptyExt = false;
814
+ }
815
+ static fromGlob(pattern, options = {}) {
816
+ const ast = new _a(null, void 0, options);
817
+ _a.#parseAST(pattern, ast, 0, options, 0);
818
+ return ast;
819
+ }
820
+ // returns the regular expression if there's magic, or the unescaped
821
+ // string if not.
822
+ toMMPattern() {
823
+ if (this !== this.#root)
824
+ return this.#root.toMMPattern();
825
+ const glob = this.toString();
826
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
827
+ const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();
828
+ if (!anyMagic) {
829
+ return body;
830
+ }
831
+ const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
832
+ return Object.assign(new RegExp(`^${re}$`, flags), {
833
+ _src: re,
834
+ _glob: glob
835
+ });
836
+ }
837
+ get options() {
838
+ return this.#options;
839
+ }
840
+ // returns the string match, the regexp source, whether there's magic
841
+ // in the regexp (so a regular expression is required) and whether or
842
+ // not the uflag is needed for the regular expression (for posix classes)
843
+ // TODO: instead of injecting the start/end at this point, just return
844
+ // the BODY of the regexp, along with the start/end portions suitable
845
+ // for binding the start/end in either a joined full-path makeRe context
846
+ // (where we bind to (^|/), or a standalone matchPart context (where
847
+ // we bind to ^, and not /). Otherwise slashes get duped!
848
+ //
849
+ // In part-matching mode, the start is:
850
+ // - if not isStart: nothing
851
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
852
+ // - if dots allowed or not possible: ^
853
+ // - if dots possible and not allowed: ^(?!\.)
854
+ // end is:
855
+ // - if not isEnd(): nothing
856
+ // - else: $
857
+ //
858
+ // In full-path matching mode, we put the slash at the START of the
859
+ // pattern, so start is:
860
+ // - if first pattern: same as part-matching mode
861
+ // - if not isStart(): nothing
862
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
863
+ // - if dots allowed or not possible: /
864
+ // - if dots possible and not allowed: /(?!\.)
865
+ // end is:
866
+ // - if last pattern, same as part-matching mode
867
+ // - else nothing
868
+ //
869
+ // Always put the (?:$|/) on negated tails, though, because that has to be
870
+ // there to bind the end of the negated pattern portion, and it's easier to
871
+ // just stick it in now rather than try to inject it later in the middle of
872
+ // the pattern.
873
+ //
874
+ // We can just always return the same end, and leave it up to the caller
875
+ // to know whether it's going to be used joined or in parts.
876
+ // And, if the start is adjusted slightly, can do the same there:
877
+ // - if not isStart: nothing
878
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
879
+ // - if dots allowed or not possible: (?:/|^)
880
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
881
+ //
882
+ // But it's better to have a simpler binding without a conditional, for
883
+ // performance, so probably better to return both start options.
884
+ //
885
+ // Then the caller just ignores the end if it's not the first pattern,
886
+ // and the start always gets applied.
887
+ //
888
+ // But that's always going to be $ if it's the ending pattern, or nothing,
889
+ // so the caller can just attach $ at the end of the pattern when building.
890
+ //
891
+ // So the todo is:
892
+ // - better detect what kind of start is needed
893
+ // - return both flavors of starting pattern
894
+ // - attach $ at the end of the pattern when creating the actual RegExp
895
+ //
896
+ // Ah, but wait, no, that all only applies to the root when the first pattern
897
+ // is not an extglob. If the first pattern IS an extglob, then we need all
898
+ // that dot prevention biz to live in the extglob portions, because eg
899
+ // +(*|.x*) can match .xy but not .yx.
900
+ //
901
+ // So, return the two flavors if it's #root and the first child is not an
902
+ // AST, otherwise leave it to the child AST to handle it, and there,
903
+ // use the (?:^|/) style of start binding.
904
+ //
905
+ // Even simplified further:
906
+ // - Since the start for a join is eg /(?!\.) and the start for a part
907
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
908
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
909
+ toRegExpSource(allowDot) {
910
+ const dot = allowDot ?? !!this.#options.dot;
911
+ if (this.#root === this) {
912
+ this.#flatten();
913
+ this.#fillNegs();
914
+ }
915
+ if (!isExtglobAST(this)) {
916
+ const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s) => typeof s !== "string");
917
+ const src = this.#parts.map((p) => {
918
+ const [re, _, hasMagic, uflag] = typeof p === "string" ? _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
919
+ this.#hasMagic = this.#hasMagic || hasMagic;
920
+ this.#uflag = this.#uflag || uflag;
921
+ return re;
922
+ }).join("");
923
+ let start2 = "";
924
+ if (this.isStart()) {
925
+ if (typeof this.#parts[0] === "string") {
926
+ const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
927
+ if (!dotTravAllowed) {
928
+ const aps = addPatternStart;
929
+ const needNoTrav = (
930
+ // dots are allowed, and the pattern starts with [ or .
931
+ dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
932
+ src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
933
+ src.startsWith("\\.\\.") && aps.has(src.charAt(4))
934
+ );
935
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
936
+ start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
937
+ }
938
+ }
939
+ }
940
+ let end = "";
941
+ if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {
942
+ end = "(?:$|\\/)";
943
+ }
944
+ const final2 = start2 + src + end;
945
+ return [
946
+ final2,
947
+ unescape(src),
948
+ this.#hasMagic = !!this.#hasMagic,
949
+ this.#uflag
950
+ ];
951
+ }
952
+ const repeated = this.type === "*" || this.type === "+";
953
+ const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
954
+ let body = this.#partsToRegExp(dot);
955
+ if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
956
+ const s = this.toString();
957
+ const me = this;
958
+ me.#parts = [s];
959
+ me.type = null;
960
+ me.#hasMagic = void 0;
961
+ return [s, unescape(this.toString()), false, false];
962
+ }
963
+ let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);
964
+ if (bodyDotAllowed === body) {
965
+ bodyDotAllowed = "";
966
+ }
967
+ if (bodyDotAllowed) {
968
+ body = `(?:${body})(?:${bodyDotAllowed})*?`;
969
+ }
970
+ let final = "";
971
+ if (this.type === "!" && this.#emptyExt) {
972
+ final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
973
+ } else {
974
+ const close = this.type === "!" ? (
975
+ // !() must match something,but !(x) can match ''
976
+ "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"
977
+ ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
978
+ final = start + body + close;
979
+ }
980
+ return [
981
+ final,
982
+ unescape(body),
983
+ this.#hasMagic = !!this.#hasMagic,
984
+ this.#uflag
985
+ ];
986
+ }
987
+ #flatten() {
988
+ if (!isExtglobAST(this)) {
989
+ for (const p of this.#parts) {
990
+ if (typeof p === "object") {
991
+ p.#flatten();
992
+ }
993
+ }
994
+ } else {
995
+ let iterations = 0;
996
+ let done = false;
997
+ do {
998
+ done = true;
999
+ for (let i = 0; i < this.#parts.length; i++) {
1000
+ const c = this.#parts[i];
1001
+ if (typeof c === "object") {
1002
+ c.#flatten();
1003
+ if (this.#canAdopt(c)) {
1004
+ done = false;
1005
+ this.#adopt(c, i);
1006
+ } else if (this.#canAdoptWithSpace(c)) {
1007
+ done = false;
1008
+ this.#adoptWithSpace(c, i);
1009
+ } else if (this.#canUsurp(c)) {
1010
+ done = false;
1011
+ this.#usurp(c);
1012
+ }
1013
+ }
1014
+ }
1015
+ } while (!done && ++iterations < 10);
1016
+ }
1017
+ this.#toString = void 0;
1018
+ }
1019
+ #partsToRegExp(dot) {
1020
+ return this.#parts.map((p) => {
1021
+ if (typeof p === "string") {
1022
+ throw new Error("string type in extglob ast??");
1023
+ }
1024
+ const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
1025
+ this.#uflag = this.#uflag || uflag;
1026
+ return re;
1027
+ }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
1028
+ }
1029
+ static #parseGlob(glob, hasMagic, noEmpty = false) {
1030
+ let escaping = false;
1031
+ let re = "";
1032
+ let uflag = false;
1033
+ let inStar = false;
1034
+ for (let i = 0; i < glob.length; i++) {
1035
+ const c = glob.charAt(i);
1036
+ if (escaping) {
1037
+ escaping = false;
1038
+ re += (reSpecials.has(c) ? "\\" : "") + c;
1039
+ continue;
1040
+ }
1041
+ if (c === "*") {
1042
+ if (inStar)
1043
+ continue;
1044
+ inStar = true;
1045
+ re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
1046
+ hasMagic = true;
1047
+ continue;
1048
+ } else {
1049
+ inStar = false;
1050
+ }
1051
+ if (c === "\\") {
1052
+ if (i === glob.length - 1) {
1053
+ re += "\\\\";
1054
+ } else {
1055
+ escaping = true;
1056
+ }
1057
+ continue;
1058
+ }
1059
+ if (c === "[") {
1060
+ const [src, needUflag, consumed, magic] = parseClass(glob, i);
1061
+ if (consumed) {
1062
+ re += src;
1063
+ uflag = uflag || needUflag;
1064
+ i += consumed - 1;
1065
+ hasMagic = hasMagic || magic;
1066
+ continue;
1067
+ }
1068
+ }
1069
+ if (c === "?") {
1070
+ re += qmark;
1071
+ hasMagic = true;
1072
+ continue;
1073
+ }
1074
+ re += regExpEscape(c);
1075
+ }
1076
+ return [re, unescape(glob), !!hasMagic, uflag];
1077
+ }
1078
+ };
1079
+ _a = AST;
1080
+
1081
+ // ../../node_modules/minimatch/dist/esm/escape.js
1082
+ var escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {
1083
+ if (magicalBraces) {
1084
+ return windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, "[$&]") : s.replace(/[?*()[\]\\{}]/g, "\\$&");
1085
+ }
1086
+ return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
1087
+ };
1088
+
1089
+ // ../../node_modules/minimatch/dist/esm/index.js
1090
+ var minimatch = (p, pattern, options = {}) => {
1091
+ assertValidPattern(pattern);
1092
+ if (!options.nocomment && pattern.charAt(0) === "#") {
1093
+ return false;
1094
+ }
1095
+ return new Minimatch(pattern, options).match(p);
1096
+ };
1097
+ var starDotExtRE = /^\*+([^+@!?*[(]*)$/;
1098
+ var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
1099
+ var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
1100
+ var starDotExtTestNocase = (ext2) => {
1101
+ ext2 = ext2.toLowerCase();
1102
+ return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
1103
+ };
1104
+ var starDotExtTestNocaseDot = (ext2) => {
1105
+ ext2 = ext2.toLowerCase();
1106
+ return (f) => f.toLowerCase().endsWith(ext2);
1107
+ };
1108
+ var starDotStarRE = /^\*+\.\*+$/;
1109
+ var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
1110
+ var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
1111
+ var dotStarRE = /^\.\*+$/;
1112
+ var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
1113
+ var starRE = /^\*+$/;
1114
+ var starTest = (f) => f.length !== 0 && !f.startsWith(".");
1115
+ var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
1116
+ var qmarksRE = /^\?+([^+@!?*[(]*)?$/;
1117
+ var qmarksTestNocase = ([$0, ext2 = ""]) => {
1118
+ const noext = qmarksTestNoExt([$0]);
1119
+ if (!ext2)
1120
+ return noext;
1121
+ ext2 = ext2.toLowerCase();
1122
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
1123
+ };
1124
+ var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
1125
+ const noext = qmarksTestNoExtDot([$0]);
1126
+ if (!ext2)
1127
+ return noext;
1128
+ ext2 = ext2.toLowerCase();
1129
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
1130
+ };
1131
+ var qmarksTestDot = ([$0, ext2 = ""]) => {
1132
+ const noext = qmarksTestNoExtDot([$0]);
1133
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
1134
+ };
1135
+ var qmarksTest = ([$0, ext2 = ""]) => {
1136
+ const noext = qmarksTestNoExt([$0]);
1137
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
1138
+ };
1139
+ var qmarksTestNoExt = ([$0]) => {
1140
+ const len = $0.length;
1141
+ return (f) => f.length === len && !f.startsWith(".");
1142
+ };
1143
+ var qmarksTestNoExtDot = ([$0]) => {
1144
+ const len = $0.length;
1145
+ return (f) => f.length === len && f !== "." && f !== "..";
1146
+ };
1147
+ var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
1148
+ var path = {
1149
+ win32: { sep: "\\" },
1150
+ posix: { sep: "/" }
1151
+ };
1152
+ var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
1153
+ minimatch.sep = sep;
1154
+ var GLOBSTAR = /* @__PURE__ */ Symbol("globstar **");
1155
+ minimatch.GLOBSTAR = GLOBSTAR;
1156
+ var qmark2 = "[^/]";
1157
+ var star2 = qmark2 + "*?";
1158
+ var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
1159
+ var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
1160
+ var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
1161
+ minimatch.filter = filter;
1162
+ var ext = (a, b = {}) => Object.assign({}, a, b);
1163
+ var defaults = (def) => {
1164
+ if (!def || typeof def !== "object" || !Object.keys(def).length) {
1165
+ return minimatch;
1166
+ }
1167
+ const orig = minimatch;
1168
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
1169
+ return Object.assign(m, {
1170
+ Minimatch: class Minimatch extends orig.Minimatch {
1171
+ constructor(pattern, options = {}) {
1172
+ super(pattern, ext(def, options));
1173
+ }
1174
+ static defaults(options) {
1175
+ return orig.defaults(ext(def, options)).Minimatch;
1176
+ }
1177
+ },
1178
+ AST: class AST extends orig.AST {
1179
+ /* c8 ignore start */
1180
+ constructor(type, parent, options = {}) {
1181
+ super(type, parent, ext(def, options));
1182
+ }
1183
+ /* c8 ignore stop */
1184
+ static fromGlob(pattern, options = {}) {
1185
+ return orig.AST.fromGlob(pattern, ext(def, options));
1186
+ }
1187
+ },
1188
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
1189
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
1190
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
1191
+ defaults: (options) => orig.defaults(ext(def, options)),
1192
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
1193
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
1194
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
1195
+ sep: orig.sep,
1196
+ GLOBSTAR
1197
+ });
1198
+ };
1199
+ minimatch.defaults = defaults;
1200
+ var braceExpand = (pattern, options = {}) => {
1201
+ assertValidPattern(pattern);
1202
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
1203
+ return [pattern];
1204
+ }
1205
+ return expand(pattern, { max: options.braceExpandMax });
1206
+ };
1207
+ minimatch.braceExpand = braceExpand;
1208
+ var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
1209
+ minimatch.makeRe = makeRe;
1210
+ var match = (list, pattern, options = {}) => {
1211
+ const mm = new Minimatch(pattern, options);
1212
+ list = list.filter((f) => mm.match(f));
1213
+ if (mm.options.nonull && !list.length) {
1214
+ list.push(pattern);
1215
+ }
1216
+ return list;
1217
+ };
1218
+ minimatch.match = match;
1219
+ var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
1220
+ var regExpEscape2 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1221
+ var Minimatch = class {
1222
+ options;
1223
+ set;
1224
+ pattern;
1225
+ windowsPathsNoEscape;
1226
+ nonegate;
1227
+ negate;
1228
+ comment;
1229
+ empty;
1230
+ preserveMultipleSlashes;
1231
+ partial;
1232
+ globSet;
1233
+ globParts;
1234
+ nocase;
1235
+ isWindows;
1236
+ platform;
1237
+ windowsNoMagicRoot;
1238
+ maxGlobstarRecursion;
1239
+ regexp;
1240
+ constructor(pattern, options = {}) {
1241
+ assertValidPattern(pattern);
1242
+ options = options || {};
1243
+ this.options = options;
1244
+ this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
1245
+ this.pattern = pattern;
1246
+ this.platform = options.platform || defaultPlatform;
1247
+ this.isWindows = this.platform === "win32";
1248
+ const awe = "allowWindowsEscape";
1249
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[awe] === false;
1250
+ if (this.windowsPathsNoEscape) {
1251
+ this.pattern = this.pattern.replace(/\\/g, "/");
1252
+ }
1253
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
1254
+ this.regexp = null;
1255
+ this.negate = false;
1256
+ this.nonegate = !!options.nonegate;
1257
+ this.comment = false;
1258
+ this.empty = false;
1259
+ this.partial = !!options.partial;
1260
+ this.nocase = !!this.options.nocase;
1261
+ this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
1262
+ this.globSet = [];
1263
+ this.globParts = [];
1264
+ this.set = [];
1265
+ this.make();
1266
+ }
1267
+ hasMagic() {
1268
+ if (this.options.magicalBraces && this.set.length > 1) {
1269
+ return true;
1270
+ }
1271
+ for (const pattern of this.set) {
1272
+ for (const part of pattern) {
1273
+ if (typeof part !== "string")
1274
+ return true;
1275
+ }
1276
+ }
1277
+ return false;
1278
+ }
1279
+ debug(..._) {
1280
+ }
1281
+ make() {
1282
+ const pattern = this.pattern;
1283
+ const options = this.options;
1284
+ if (!options.nocomment && pattern.charAt(0) === "#") {
1285
+ this.comment = true;
1286
+ return;
1287
+ }
1288
+ if (!pattern) {
1289
+ this.empty = true;
1290
+ return;
1291
+ }
1292
+ this.parseNegate();
1293
+ this.globSet = [...new Set(this.braceExpand())];
1294
+ if (options.debug) {
1295
+ this.debug = (...args) => console.error(...args);
1296
+ }
1297
+ this.debug(this.pattern, this.globSet);
1298
+ const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
1299
+ this.globParts = this.preprocess(rawGlobParts);
1300
+ this.debug(this.pattern, this.globParts);
1301
+ let set = this.globParts.map((s, _, __) => {
1302
+ if (this.isWindows && this.windowsNoMagicRoot) {
1303
+ const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
1304
+ const isDrive = /^[a-z]:/i.test(s[0]);
1305
+ if (isUNC) {
1306
+ return [
1307
+ ...s.slice(0, 4),
1308
+ ...s.slice(4).map((ss) => this.parse(ss))
1309
+ ];
1310
+ } else if (isDrive) {
1311
+ return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
1312
+ }
1313
+ }
1314
+ return s.map((ss) => this.parse(ss));
1315
+ });
1316
+ this.debug(this.pattern, set);
1317
+ this.set = set.filter((s) => s.indexOf(false) === -1);
1318
+ if (this.isWindows) {
1319
+ for (let i = 0; i < this.set.length; i++) {
1320
+ const p = this.set[i];
1321
+ if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
1322
+ p[2] = "?";
1323
+ }
1324
+ }
1325
+ }
1326
+ this.debug(this.pattern, this.set);
1327
+ }
1328
+ // various transforms to equivalent pattern sets that are
1329
+ // faster to process in a filesystem walk. The goal is to
1330
+ // eliminate what we can, and push all ** patterns as far
1331
+ // to the right as possible, even if it increases the number
1332
+ // of patterns that we have to process.
1333
+ preprocess(globParts) {
1334
+ if (this.options.noglobstar) {
1335
+ for (const partset of globParts) {
1336
+ for (let j = 0; j < partset.length; j++) {
1337
+ if (partset[j] === "**") {
1338
+ partset[j] = "*";
1339
+ }
1340
+ }
1341
+ }
1342
+ }
1343
+ const { optimizationLevel = 1 } = this.options;
1344
+ if (optimizationLevel >= 2) {
1345
+ globParts = this.firstPhasePreProcess(globParts);
1346
+ globParts = this.secondPhasePreProcess(globParts);
1347
+ } else if (optimizationLevel >= 1) {
1348
+ globParts = this.levelOneOptimize(globParts);
1349
+ } else {
1350
+ globParts = this.adjascentGlobstarOptimize(globParts);
1351
+ }
1352
+ return globParts;
1353
+ }
1354
+ // just get rid of adjascent ** portions
1355
+ adjascentGlobstarOptimize(globParts) {
1356
+ return globParts.map((parts) => {
1357
+ let gs = -1;
1358
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
1359
+ let i = gs;
1360
+ while (parts[i + 1] === "**") {
1361
+ i++;
1362
+ }
1363
+ if (i !== gs) {
1364
+ parts.splice(gs, i - gs);
1365
+ }
1366
+ }
1367
+ return parts;
1368
+ });
1369
+ }
1370
+ // get rid of adjascent ** and resolve .. portions
1371
+ levelOneOptimize(globParts) {
1372
+ return globParts.map((parts) => {
1373
+ parts = parts.reduce((set, part) => {
1374
+ const prev = set[set.length - 1];
1375
+ if (part === "**" && prev === "**") {
1376
+ return set;
1377
+ }
1378
+ if (part === "..") {
1379
+ if (prev && prev !== ".." && prev !== "." && prev !== "**") {
1380
+ set.pop();
1381
+ return set;
1382
+ }
1383
+ }
1384
+ set.push(part);
1385
+ return set;
1386
+ }, []);
1387
+ return parts.length === 0 ? [""] : parts;
1388
+ });
1389
+ }
1390
+ levelTwoFileOptimize(parts) {
1391
+ if (!Array.isArray(parts)) {
1392
+ parts = this.slashSplit(parts);
1393
+ }
1394
+ let didSomething = false;
1395
+ do {
1396
+ didSomething = false;
1397
+ if (!this.preserveMultipleSlashes) {
1398
+ for (let i = 1; i < parts.length - 1; i++) {
1399
+ const p = parts[i];
1400
+ if (i === 1 && p === "" && parts[0] === "")
1401
+ continue;
1402
+ if (p === "." || p === "") {
1403
+ didSomething = true;
1404
+ parts.splice(i, 1);
1405
+ i--;
1406
+ }
1407
+ }
1408
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
1409
+ didSomething = true;
1410
+ parts.pop();
1411
+ }
1412
+ }
1413
+ let dd = 0;
1414
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
1415
+ const p = parts[dd - 1];
1416
+ if (p && p !== "." && p !== ".." && p !== "**" && !(this.isWindows && /^[a-z]:$/i.test(p))) {
1417
+ didSomething = true;
1418
+ parts.splice(dd - 1, 2);
1419
+ dd -= 2;
1420
+ }
1421
+ }
1422
+ } while (didSomething);
1423
+ return parts.length === 0 ? [""] : parts;
1424
+ }
1425
+ // First phase: single-pattern processing
1426
+ // <pre> is 1 or more portions
1427
+ // <rest> is 1 or more portions
1428
+ // <p> is any portion other than ., .., '', or **
1429
+ // <e> is . or ''
1430
+ //
1431
+ // **/.. is *brutal* for filesystem walking performance, because
1432
+ // it effectively resets the recursive walk each time it occurs,
1433
+ // and ** cannot be reduced out by a .. pattern part like a regexp
1434
+ // or most strings (other than .., ., and '') can be.
1435
+ //
1436
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
1437
+ // <pre>/<e>/<rest> -> <pre>/<rest>
1438
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
1439
+ // **/**/<rest> -> **/<rest>
1440
+ //
1441
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
1442
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
1443
+ firstPhasePreProcess(globParts) {
1444
+ let didSomething = false;
1445
+ do {
1446
+ didSomething = false;
1447
+ for (let parts of globParts) {
1448
+ let gs = -1;
1449
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
1450
+ let gss = gs;
1451
+ while (parts[gss + 1] === "**") {
1452
+ gss++;
1453
+ }
1454
+ if (gss > gs) {
1455
+ parts.splice(gs + 1, gss - gs);
1456
+ }
1457
+ let next = parts[gs + 1];
1458
+ const p = parts[gs + 2];
1459
+ const p2 = parts[gs + 3];
1460
+ if (next !== "..")
1461
+ continue;
1462
+ if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
1463
+ continue;
1464
+ }
1465
+ didSomething = true;
1466
+ parts.splice(gs, 1);
1467
+ const other = parts.slice(0);
1468
+ other[gs] = "**";
1469
+ globParts.push(other);
1470
+ gs--;
1471
+ }
1472
+ if (!this.preserveMultipleSlashes) {
1473
+ for (let i = 1; i < parts.length - 1; i++) {
1474
+ const p = parts[i];
1475
+ if (i === 1 && p === "" && parts[0] === "")
1476
+ continue;
1477
+ if (p === "." || p === "") {
1478
+ didSomething = true;
1479
+ parts.splice(i, 1);
1480
+ i--;
1481
+ }
1482
+ }
1483
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
1484
+ didSomething = true;
1485
+ parts.pop();
1486
+ }
1487
+ }
1488
+ let dd = 0;
1489
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
1490
+ const p = parts[dd - 1];
1491
+ if (p && p !== "." && p !== ".." && p !== "**") {
1492
+ didSomething = true;
1493
+ const needDot = dd === 1 && parts[dd + 1] === "**";
1494
+ const splin = needDot ? ["."] : [];
1495
+ parts.splice(dd - 1, 2, ...splin);
1496
+ if (parts.length === 0)
1497
+ parts.push("");
1498
+ dd -= 2;
1499
+ }
1500
+ }
1501
+ }
1502
+ } while (didSomething);
1503
+ return globParts;
1504
+ }
1505
+ // second phase: multi-pattern dedupes
1506
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
1507
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
1508
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
1509
+ //
1510
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
1511
+ // ^-- not valid because ** doens't follow symlinks
1512
+ secondPhasePreProcess(globParts) {
1513
+ for (let i = 0; i < globParts.length - 1; i++) {
1514
+ for (let j = i + 1; j < globParts.length; j++) {
1515
+ const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
1516
+ if (matched) {
1517
+ globParts[i] = [];
1518
+ globParts[j] = matched;
1519
+ break;
1520
+ }
1521
+ }
1522
+ }
1523
+ return globParts.filter((gs) => gs.length);
1524
+ }
1525
+ partsMatch(a, b, emptyGSMatch = false) {
1526
+ let ai = 0;
1527
+ let bi = 0;
1528
+ let result = [];
1529
+ let which = "";
1530
+ while (ai < a.length && bi < b.length) {
1531
+ if (a[ai] === b[bi]) {
1532
+ result.push(which === "b" ? b[bi] : a[ai]);
1533
+ ai++;
1534
+ bi++;
1535
+ } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
1536
+ result.push(a[ai]);
1537
+ ai++;
1538
+ } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
1539
+ result.push(b[bi]);
1540
+ bi++;
1541
+ } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
1542
+ if (which === "b")
1543
+ return false;
1544
+ which = "a";
1545
+ result.push(a[ai]);
1546
+ ai++;
1547
+ bi++;
1548
+ } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
1549
+ if (which === "a")
1550
+ return false;
1551
+ which = "b";
1552
+ result.push(b[bi]);
1553
+ ai++;
1554
+ bi++;
1555
+ } else {
1556
+ return false;
1557
+ }
1558
+ }
1559
+ return a.length === b.length && result;
1560
+ }
1561
+ parseNegate() {
1562
+ if (this.nonegate)
1563
+ return;
1564
+ const pattern = this.pattern;
1565
+ let negate = false;
1566
+ let negateOffset = 0;
1567
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
1568
+ negate = !negate;
1569
+ negateOffset++;
1570
+ }
1571
+ if (negateOffset)
1572
+ this.pattern = pattern.slice(negateOffset);
1573
+ this.negate = negate;
1574
+ }
1575
+ // set partial to true to test if, for example,
1576
+ // "/a/b" matches the start of "/*/b/*/d"
1577
+ // Partial means, if you run out of file before you run
1578
+ // out of pattern, then that's fine, as long as all
1579
+ // the parts match.
1580
+ matchOne(file, pattern, partial = false) {
1581
+ let fileStartIndex = 0;
1582
+ let patternStartIndex = 0;
1583
+ if (this.isWindows) {
1584
+ const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
1585
+ const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
1586
+ const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
1587
+ const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
1588
+ const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
1589
+ const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
1590
+ if (typeof fdi === "number" && typeof pdi === "number") {
1591
+ const [fd, pd] = [
1592
+ file[fdi],
1593
+ pattern[pdi]
1594
+ ];
1595
+ if (fd.toLowerCase() === pd.toLowerCase()) {
1596
+ pattern[pdi] = fd;
1597
+ patternStartIndex = pdi;
1598
+ fileStartIndex = fdi;
1599
+ }
1600
+ }
1601
+ }
1602
+ const { optimizationLevel = 1 } = this.options;
1603
+ if (optimizationLevel >= 2) {
1604
+ file = this.levelTwoFileOptimize(file);
1605
+ }
1606
+ if (pattern.includes(GLOBSTAR)) {
1607
+ return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
1608
+ }
1609
+ return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
1610
+ }
1611
+ #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
1612
+ const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
1613
+ const lastgs = pattern.lastIndexOf(GLOBSTAR);
1614
+ const [head, body, tail] = partial ? [
1615
+ pattern.slice(patternIndex, firstgs),
1616
+ pattern.slice(firstgs + 1),
1617
+ []
1618
+ ] : [
1619
+ pattern.slice(patternIndex, firstgs),
1620
+ pattern.slice(firstgs + 1, lastgs),
1621
+ pattern.slice(lastgs + 1)
1622
+ ];
1623
+ if (head.length) {
1624
+ const fileHead = file.slice(fileIndex, fileIndex + head.length);
1625
+ if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
1626
+ return false;
1627
+ }
1628
+ fileIndex += head.length;
1629
+ patternIndex += head.length;
1630
+ }
1631
+ let fileTailMatch = 0;
1632
+ if (tail.length) {
1633
+ if (tail.length + fileIndex > file.length)
1634
+ return false;
1635
+ let tailStart = file.length - tail.length;
1636
+ if (this.#matchOne(file, tail, partial, tailStart, 0)) {
1637
+ fileTailMatch = tail.length;
1638
+ } else {
1639
+ if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) {
1640
+ return false;
1641
+ }
1642
+ tailStart--;
1643
+ if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
1644
+ return false;
1645
+ }
1646
+ fileTailMatch = tail.length + 1;
1647
+ }
1648
+ }
1649
+ if (!body.length) {
1650
+ let sawSome = !!fileTailMatch;
1651
+ for (let i2 = fileIndex; i2 < file.length - fileTailMatch; i2++) {
1652
+ const f = String(file[i2]);
1653
+ sawSome = true;
1654
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {
1655
+ return false;
1656
+ }
1657
+ }
1658
+ return partial || sawSome;
1659
+ }
1660
+ const bodySegments = [[[], 0]];
1661
+ let currentBody = bodySegments[0];
1662
+ let nonGsParts = 0;
1663
+ const nonGsPartsSums = [0];
1664
+ for (const b of body) {
1665
+ if (b === GLOBSTAR) {
1666
+ nonGsPartsSums.push(nonGsParts);
1667
+ currentBody = [[], 0];
1668
+ bodySegments.push(currentBody);
1669
+ } else {
1670
+ currentBody[0].push(b);
1671
+ nonGsParts++;
1672
+ }
1673
+ }
1674
+ let i = bodySegments.length - 1;
1675
+ const fileLength = file.length - fileTailMatch;
1676
+ for (const b of bodySegments) {
1677
+ b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
1678
+ }
1679
+ return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
1680
+ }
1681
+ // return false for "nope, not matching"
1682
+ // return null for "not matching, cannot keep trying"
1683
+ #matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
1684
+ const bs = bodySegments[bodyIndex];
1685
+ if (!bs) {
1686
+ for (let i = fileIndex; i < file.length; i++) {
1687
+ sawTail = true;
1688
+ const f = file[i];
1689
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {
1690
+ return false;
1691
+ }
1692
+ }
1693
+ return sawTail;
1694
+ }
1695
+ const [body, after] = bs;
1696
+ while (fileIndex <= after) {
1697
+ const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
1698
+ if (m && globStarDepth < this.maxGlobstarRecursion) {
1699
+ const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
1700
+ if (sub !== false) {
1701
+ return sub;
1702
+ }
1703
+ }
1704
+ const f = file[fileIndex];
1705
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {
1706
+ return false;
1707
+ }
1708
+ fileIndex++;
1709
+ }
1710
+ return partial || null;
1711
+ }
1712
+ #matchOne(file, pattern, partial, fileIndex, patternIndex) {
1713
+ let fi;
1714
+ let pi;
1715
+ let pl;
1716
+ let fl;
1717
+ for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
1718
+ this.debug("matchOne loop");
1719
+ let p = pattern[pi];
1720
+ let f = file[fi];
1721
+ this.debug(pattern, p, f);
1722
+ if (p === false || p === GLOBSTAR) {
1723
+ return false;
1724
+ }
1725
+ let hit;
1726
+ if (typeof p === "string") {
1727
+ hit = f === p;
1728
+ this.debug("string match", p, f, hit);
1729
+ } else {
1730
+ hit = p.test(f);
1731
+ this.debug("pattern match", p, f, hit);
1732
+ }
1733
+ if (!hit)
1734
+ return false;
1735
+ }
1736
+ if (fi === fl && pi === pl) {
1737
+ return true;
1738
+ } else if (fi === fl) {
1739
+ return partial;
1740
+ } else if (pi === pl) {
1741
+ return fi === fl - 1 && file[fi] === "";
1742
+ } else {
1743
+ throw new Error("wtf?");
1744
+ }
1745
+ }
1746
+ braceExpand() {
1747
+ return braceExpand(this.pattern, this.options);
1748
+ }
1749
+ parse(pattern) {
1750
+ assertValidPattern(pattern);
1751
+ const options = this.options;
1752
+ if (pattern === "**")
1753
+ return GLOBSTAR;
1754
+ if (pattern === "")
1755
+ return "";
1756
+ let m;
1757
+ let fastTest = null;
1758
+ if (m = pattern.match(starRE)) {
1759
+ fastTest = options.dot ? starTestDot : starTest;
1760
+ } else if (m = pattern.match(starDotExtRE)) {
1761
+ fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
1762
+ } else if (m = pattern.match(qmarksRE)) {
1763
+ fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
1764
+ } else if (m = pattern.match(starDotStarRE)) {
1765
+ fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
1766
+ } else if (m = pattern.match(dotStarRE)) {
1767
+ fastTest = dotStarTest;
1768
+ }
1769
+ const re = AST.fromGlob(pattern, this.options).toMMPattern();
1770
+ if (fastTest && typeof re === "object") {
1771
+ Reflect.defineProperty(re, "test", { value: fastTest });
1772
+ }
1773
+ return re;
1774
+ }
1775
+ makeRe() {
1776
+ if (this.regexp || this.regexp === false)
1777
+ return this.regexp;
1778
+ const set = this.set;
1779
+ if (!set.length) {
1780
+ this.regexp = false;
1781
+ return this.regexp;
1782
+ }
1783
+ const options = this.options;
1784
+ const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;
1785
+ const flags = new Set(options.nocase ? ["i"] : []);
1786
+ let re = set.map((pattern) => {
1787
+ const pp = pattern.map((p) => {
1788
+ if (p instanceof RegExp) {
1789
+ for (const f of p.flags.split(""))
1790
+ flags.add(f);
1791
+ }
1792
+ return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
1793
+ });
1794
+ pp.forEach((p, i) => {
1795
+ const next = pp[i + 1];
1796
+ const prev = pp[i - 1];
1797
+ if (p !== GLOBSTAR || prev === GLOBSTAR) {
1798
+ return;
1799
+ }
1800
+ if (prev === void 0) {
1801
+ if (next !== void 0 && next !== GLOBSTAR) {
1802
+ pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
1803
+ } else {
1804
+ pp[i] = twoStar;
1805
+ }
1806
+ } else if (next === void 0) {
1807
+ pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + ")?";
1808
+ } else if (next !== GLOBSTAR) {
1809
+ pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
1810
+ pp[i + 1] = GLOBSTAR;
1811
+ }
1812
+ });
1813
+ const filtered = pp.filter((p) => p !== GLOBSTAR);
1814
+ if (this.partial && filtered.length >= 1) {
1815
+ const prefixes = [];
1816
+ for (let i = 1; i <= filtered.length; i++) {
1817
+ prefixes.push(filtered.slice(0, i).join("/"));
1818
+ }
1819
+ return "(?:" + prefixes.join("|") + ")";
1820
+ }
1821
+ return filtered.join("/");
1822
+ }).join("|");
1823
+ const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
1824
+ re = "^" + open + re + close + "$";
1825
+ if (this.partial) {
1826
+ re = "^(?:\\/|" + open + re.slice(1, -1) + close + ")$";
1827
+ }
1828
+ if (this.negate)
1829
+ re = "^(?!" + re + ").+$";
1830
+ try {
1831
+ this.regexp = new RegExp(re, [...flags].join(""));
1832
+ } catch {
1833
+ this.regexp = false;
1834
+ }
1835
+ return this.regexp;
1836
+ }
1837
+ slashSplit(p) {
1838
+ if (this.preserveMultipleSlashes) {
1839
+ return p.split("/");
1840
+ } else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
1841
+ return ["", ...p.split(/\/+/)];
1842
+ } else {
1843
+ return p.split(/\/+/);
1844
+ }
1845
+ }
1846
+ match(f, partial = this.partial) {
1847
+ this.debug("match", f, this.pattern);
1848
+ if (this.comment) {
1849
+ return false;
1850
+ }
1851
+ if (this.empty) {
1852
+ return f === "";
1853
+ }
1854
+ if (f === "/" && partial) {
1855
+ return true;
1856
+ }
1857
+ const options = this.options;
1858
+ if (this.isWindows) {
1859
+ f = f.split("\\").join("/");
1860
+ }
1861
+ const ff = this.slashSplit(f);
1862
+ this.debug(this.pattern, "split", ff);
1863
+ const set = this.set;
1864
+ this.debug(this.pattern, "set", set);
1865
+ let filename = ff[ff.length - 1];
1866
+ if (!filename) {
1867
+ for (let i = ff.length - 2; !filename && i >= 0; i--) {
1868
+ filename = ff[i];
1869
+ }
1870
+ }
1871
+ for (const pattern of set) {
1872
+ let file = ff;
1873
+ if (options.matchBase && pattern.length === 1) {
1874
+ file = [filename];
1875
+ }
1876
+ const hit = this.matchOne(file, pattern, partial);
1877
+ if (hit) {
1878
+ if (options.flipNegate) {
1879
+ return true;
1880
+ }
1881
+ return !this.negate;
1882
+ }
1883
+ }
1884
+ if (options.flipNegate) {
1885
+ return false;
1886
+ }
1887
+ return this.negate;
1888
+ }
1889
+ static defaults(def) {
1890
+ return minimatch.defaults(def).Minimatch;
1891
+ }
1892
+ };
1893
+ minimatch.AST = AST;
1894
+ minimatch.Minimatch = Minimatch;
1895
+ minimatch.escape = escape;
1896
+ minimatch.unescape = unescape;
1897
+
1898
+ // src/utils.ts
1899
+ var ESCAPE_CHARACTER = String.fromCharCode(27);
1900
+ var BELL_CHARACTER = String.fromCharCode(7);
1901
+ var ANSI_ESCAPE_SEQUENCE = new RegExp(`${ESCAPE_CHARACTER}(?:\\[[0-?]*[ -/]*[@-~]|\\][^${BELL_CHARACTER}]*(?:${BELL_CHARACTER}|${ESCAPE_CHARACTER}\\\\))`, "g");
1902
+ var TERMINAL_CONTROL_CHARACTER = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}-${String.fromCharCode(159)}]`, "g");
1903
+
1904
+ // src/paths.ts
1905
+ function canonicalPath(path2) {
1906
+ const absolute = resolve(path2);
1907
+ try {
1908
+ return realpathSync(absolute);
1909
+ } catch {
1910
+ return absolute;
1911
+ }
1912
+ }
1913
+ function sameFilesystemPath(left, right) {
1914
+ return canonicalPath(left) === canonicalPath(right);
1915
+ }
1916
+
1917
+ // trajectory/src/server.ts
1918
+ var TRAJECTORY_IDLE_EXIT_MS = 5 * 60 * 1e3;
1919
+ var MAX_FRAME_BYTES = 32 * 1024 * 1024;
1920
+ var MAX_PENDING_REQUESTS = 128;
1921
+ var TRANSCRIPT_REQUEST_TIMEOUT_MS = 1e4;
1922
+ var ACTION_REQUEST_TIMEOUT_MS = 5 * 60 * 1e3;
1923
+ var TIMING_ENTRY_TYPE = "pi-workflows:tool-timing";
1924
+ function isTimingEntry(value) {
1925
+ return Boolean(value && typeof value === "object" && !Array.isArray(value) && value.type === "custom" && value.customType === TIMING_ENTRY_TYPE);
1926
+ }
1927
+ function compactTranscript(value) {
1928
+ if (Array.isArray(value)) return value.filter(isTimingEntry);
1929
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { revision: 0, status: "missing", timing: [] };
1930
+ const record = value;
1931
+ return { ...record, ...Array.isArray(record.timing) ? { timing: record.timing.filter(isTimingEntry) } : {} };
1932
+ }
1933
+ function compactRun(run) {
1934
+ if (!run || typeof run !== "object" || Array.isArray(run)) return run;
1935
+ const record = run;
1936
+ if (!record.transcripts || typeof record.transcripts !== "object" || Array.isArray(record.transcripts)) return { ...record, transcripts: {} };
1937
+ const transcripts = {};
1938
+ for (const [id, entries] of Object.entries(record.transcripts)) transcripts[id] = compactTranscript(entries);
1939
+ return { ...record, transcripts };
1940
+ }
1941
+ function compactSubagent(subagent) {
1942
+ if (!subagent || typeof subagent !== "object" || Array.isArray(subagent)) return subagent;
1943
+ const record = subagent;
1944
+ return { ...record, transcript: compactTranscript(record.transcript) };
1945
+ }
1946
+ function compactPublishers(publishers) {
1947
+ return publishers.map((publisher) => {
1948
+ if (!publisher || typeof publisher !== "object" || Array.isArray(publisher)) return publisher;
1949
+ const value = publisher;
1950
+ return { ...value, ...Array.isArray(value.runs) ? { runs: value.runs.map(compactRun) } : {}, ...Array.isArray(value.subagents) ? { subagents: value.subagents.map(compactSubagent) } : {} };
1951
+ });
1952
+ }
1953
+ var MAX_METADATA_STRING_BYTES = 64 * 1024;
1954
+ var MAX_METADATA_ARRAY_ENTRIES = 256;
1955
+ var MAX_METADATA_OBJECT_KEYS = 64;
1956
+ var METADATA_ARRAY_KEYS = /* @__PURE__ */ new Set(["agents", "runs", "subagents"]);
1957
+ var METADATA_OBJECT_KEYS = /* @__PURE__ */ new Set(["transcripts"]);
1958
+ function boundedMetadata(value, key = "", depth = 0) {
1959
+ if (typeof value === "string") {
1960
+ const bytes = Buffer.from(value);
1961
+ return bytes.length > MAX_METADATA_STRING_BYTES ? bytes.subarray(0, MAX_METADATA_STRING_BYTES).toString("utf8") : value;
1962
+ }
1963
+ if (typeof value === "number" || typeof value === "boolean" || value === null) return value;
1964
+ if (depth >= 12) return void 0;
1965
+ if (Array.isArray(value)) {
1966
+ const array = value;
1967
+ const entries = key === "attemptDetails" ? array.slice(-8) : METADATA_ARRAY_KEYS.has(key) ? array : array.length <= MAX_METADATA_ARRAY_ENTRIES ? array : [...array.slice(0, 32), ...array.slice(-MAX_METADATA_ARRAY_ENTRIES + 32)];
1968
+ return entries.map((entry) => boundedMetadata(entry, "", depth + 1));
1969
+ }
1970
+ if (value && typeof value === "object") {
1971
+ const result = {};
1972
+ const properties = METADATA_OBJECT_KEYS.has(key) ? Object.keys(value).sort() : Object.keys(value).sort().slice(0, MAX_METADATA_OBJECT_KEYS);
1973
+ for (const property of properties) result[property] = boundedMetadata(value[property], property, depth + 1);
1974
+ return result;
1975
+ }
1976
+ return void 0;
1977
+ }
1978
+ function minimalPublisher(publisher) {
1979
+ return boundedMetadata(publisher);
1980
+ }
1981
+ function tinyPublisher(publisher) {
1982
+ if (!publisher || typeof publisher !== "object" || Array.isArray(publisher)) return { id: "publisher" };
1983
+ const value = publisher;
1984
+ return { id: typeof value.id === "string" ? value.id.slice(0, 200) : "publisher", title: typeof value.title === "string" ? value.title.slice(0, 200) : void 0, cwd: typeof value.cwd === "string" ? value.cwd.slice(0, 1024) : void 0, sessionId: typeof value.sessionId === "string" ? value.sessionId.slice(0, 200) : void 0, themes: value.themes, connected: value.connected === true };
1985
+ }
1986
+ function encodePublisherList(publishers, updatedAt, maxBytes, initial, truncated, projector, fallback) {
1987
+ const prefix = `{"type":"state","publishers":[`;
1988
+ const suffix = (isTruncated) => `],"updatedAt":${String(updatedAt)}${initial ? ',"initial":true' : ""}${isTruncated ? ',"truncated":true' : ""}}`;
1989
+ const markerBytes = Buffer.byteLength(suffix(true)) - Buffer.byteLength(suffix(false));
1990
+ const parts = [];
1991
+ let bytes = Buffer.byteLength(prefix) + Buffer.byteLength(suffix(false));
1992
+ let wasTruncated = truncated;
1993
+ for (const publisher of publishers) {
1994
+ let serialized2;
1995
+ try {
1996
+ serialized2 = JSON.stringify(projector(publisher));
1997
+ } catch {
1998
+ wasTruncated = true;
1999
+ continue;
2000
+ }
2001
+ let nextBytes = bytes + Buffer.byteLength(serialized2) + (parts.length ? 1 : 0);
2002
+ if (nextBytes + markerBytes >= maxBytes && fallback !== void 0) {
2003
+ try {
2004
+ serialized2 = JSON.stringify(fallback(publisher));
2005
+ } catch {
2006
+ wasTruncated = true;
2007
+ continue;
2008
+ }
2009
+ nextBytes = bytes + Buffer.byteLength(serialized2) + (parts.length ? 1 : 0);
2010
+ }
2011
+ if (nextBytes + markerBytes >= maxBytes) {
2012
+ wasTruncated = true;
2013
+ continue;
2014
+ }
2015
+ parts.push(serialized2);
2016
+ bytes = nextBytes;
2017
+ }
2018
+ const serialized = `${prefix}${parts.join(",")}${suffix(wasTruncated)}`;
2019
+ if (Buffer.byteLength(serialized) < maxBytes) return { serialized, truncated: wasTruncated };
2020
+ return { serialized: `${prefix}${suffix(true)}`, truncated: true };
2021
+ }
2022
+ function encodeState(state, maxBytes) {
2023
+ const initial = state.initial === true;
2024
+ const compactedPublishers = compactPublishers(state.publishers);
2025
+ const full = encodePublisherList(compactedPublishers, state.updatedAt, maxBytes, initial, state.truncated === true, (publisher) => publisher);
2026
+ if (!full.truncated) return full.serialized;
2027
+ return encodePublisherList(compactedPublishers, state.updatedAt, maxBytes, initial, true, minimalPublisher, tinyPublisher).serialized;
2028
+ }
2029
+ function encodeApplication(value, maxBytes) {
2030
+ let serialized;
2031
+ try {
2032
+ serialized = JSON.stringify(value);
2033
+ } catch {
2034
+ return "{}";
2035
+ }
2036
+ if (Buffer.byteLength(serialized) < maxBytes) return serialized;
2037
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2038
+ const record = value;
2039
+ if (record.type === "transcript") serialized = JSON.stringify({ type: "transcript", ...typeof record.requestId === "string" ? { requestId: record.requestId } : {}, ...typeof record.publisherId === "string" ? { publisherId: record.publisherId } : {}, ...typeof record.runId === "string" ? { runId: record.runId } : {}, ...typeof record.agentId === "string" ? { agentId: record.agentId } : {}, ...typeof record.subagentId === "string" ? { subagentId: record.subagentId } : {}, ok: false, status: "oversized", revision: typeof record.revision === "number" ? record.revision : 0, error: "Transcript is too large" });
2040
+ else if (record.type === "action-result") serialized = JSON.stringify({ type: "action-result", ...typeof record.requestId === "string" ? { requestId: record.requestId } : {}, ok: false, error: "Trajectory action result is too large" });
2041
+ else serialized = JSON.stringify({ type: "error", error: "Trajectory message is too large" });
2042
+ }
2043
+ return Buffer.byteLength(serialized) < maxBytes ? serialized : "{}";
2044
+ }
2045
+ function frame(payload, maxBytes) {
2046
+ const body = Buffer.from(payload);
2047
+ if (body.length >= maxBytes) throw new Error("Trajectory WebSocket frame is too large");
2048
+ if (body.length < 126) return Buffer.concat([Buffer.from([129, body.length]), body]);
2049
+ if (body.length <= 65535) {
2050
+ const header2 = Buffer.alloc(4);
2051
+ header2[0] = 129;
2052
+ header2[1] = 126;
2053
+ header2.writeUInt16BE(body.length, 2);
2054
+ return Buffer.concat([header2, body]);
2055
+ }
2056
+ const header = Buffer.alloc(10);
2057
+ header[0] = 129;
2058
+ header[1] = 127;
2059
+ header.writeBigUInt64BE(BigInt(body.length), 2);
2060
+ return Buffer.concat([header, body]);
2061
+ }
2062
+ function isState(value) {
2063
+ return Boolean(value && typeof value === "object" && !Array.isArray(value) && value.type === "state");
2064
+ }
2065
+ function writeFrame(client, packet, state) {
2066
+ if (state && client.backpressured) {
2067
+ client.pendingState = packet;
2068
+ return;
2069
+ }
2070
+ try {
2071
+ if (state) client.pendingState = void 0;
2072
+ if (!client.socket.write(packet)) client.backpressured = true;
2073
+ } catch {
2074
+ client.socket.destroy();
2075
+ }
2076
+ }
2077
+ function send(client, value, maxBytes) {
2078
+ try {
2079
+ const state = isState(value);
2080
+ const packet = frame(state ? encodeState(value, maxBytes) : encodeApplication(value, maxBytes), maxBytes);
2081
+ writeFrame(client, packet, state);
2082
+ } catch {
2083
+ client.socket.destroy();
2084
+ }
2085
+ }
2086
+ function parseFrames(client, chunk, maxBytes) {
2087
+ client.buffer = Buffer.concat([client.buffer, chunk]);
2088
+ if (client.buffer.length > maxBytes + 14) throw new Error("Trajectory WebSocket buffer is too large");
2089
+ const messages = [];
2090
+ while (client.buffer.length >= 2) {
2091
+ const first = client.buffer[0] ?? 0;
2092
+ const second = client.buffer[1] ?? 0;
2093
+ const opcode = first & 15;
2094
+ const masked = (second & 128) !== 0;
2095
+ if ((first & 112) !== 0 || (first & 128) === 0 || !masked) throw new Error("Invalid Trajectory WebSocket frame");
2096
+ let offset = 2;
2097
+ let length = second & 127;
2098
+ if (length === 126) {
2099
+ if (client.buffer.length < 4) break;
2100
+ length = client.buffer.readUInt16BE(2);
2101
+ offset = 4;
2102
+ } else if (length === 127) {
2103
+ if (client.buffer.length < 10) break;
2104
+ const longLength = client.buffer.readBigUInt64BE(2);
2105
+ if (longLength > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("Trajectory WebSocket frame is too large");
2106
+ length = Number(longLength);
2107
+ offset = 10;
2108
+ }
2109
+ if (length >= maxBytes) throw new Error("Trajectory WebSocket frame is too large");
2110
+ if (opcode >= 8 && (length > 125 || (first & 128) === 0)) throw new Error("Invalid Trajectory WebSocket control frame");
2111
+ if (client.buffer.length < offset + 4 + length) break;
2112
+ const mask = client.buffer.subarray(offset, offset + 4);
2113
+ offset += 4;
2114
+ const data = client.buffer.subarray(offset, offset + length);
2115
+ client.buffer = client.buffer.subarray(offset + length);
2116
+ if (opcode === 8) {
2117
+ client.socket.end();
2118
+ break;
2119
+ }
2120
+ if (opcode === 9) {
2121
+ const pong = Buffer.alloc(2 + length);
2122
+ pong[0] = 138;
2123
+ pong[1] = length;
2124
+ for (let index = 0; index < length; index += 1) pong[index + 2] = (data[index] ?? 0) ^ (mask[index % 4] ?? 0);
2125
+ writeFrame(client, pong, false);
2126
+ continue;
2127
+ }
2128
+ if (opcode === 10) continue;
2129
+ if (opcode !== 1) throw new Error("Unsupported Trajectory WebSocket frame");
2130
+ const decoded = Buffer.alloc(length);
2131
+ for (let index = 0; index < length; index += 1) decoded[index] = (data[index] ?? 0) ^ (mask[index % 4] ?? 0);
2132
+ messages.push(decoded.toString("utf8"));
2133
+ }
2134
+ return messages;
2135
+ }
2136
+ function writeJson(response, status, value) {
2137
+ const body = JSON.stringify(value);
2138
+ response.writeHead(status, { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
2139
+ response.end(body);
2140
+ }
2141
+ function authorized(request, port) {
2142
+ const origin = request.headers.origin;
2143
+ return origin === void 0 || origin === `http://127.0.0.1:${String(port)}` || origin === `http://localhost:${String(port)}`;
2144
+ }
2145
+ function createTrajectoryServer(port, lockPath, options = {}) {
2146
+ const maxFrameBytes = options.maxFrameBytes ?? MAX_FRAME_BYTES;
2147
+ const serverFingerprint = options.fingerprint ?? "";
2148
+ const clients = /* @__PURE__ */ new Set();
2149
+ const publishers = /* @__PURE__ */ new Map();
2150
+ let latest = { type: "state", publishers: [], updatedAt: Date.now(), initial: true };
2151
+ const pending = /* @__PURE__ */ new Map();
2152
+ let idleTimer;
2153
+ let closed = false;
2154
+ const emit = (client, value) => {
2155
+ send(client, value, maxFrameBytes);
2156
+ };
2157
+ const pendingFor = (browser) => {
2158
+ let requests = pending.get(browser);
2159
+ if (!requests) {
2160
+ requests = /* @__PURE__ */ new Map();
2161
+ pending.set(browser, requests);
2162
+ }
2163
+ return requests;
2164
+ };
2165
+ const hasPendingRequest = (requests, requestId) => [...requests.values()].some((request) => request.requestId === requestId);
2166
+ const publisherRequestIdFor = (requestId) => [...pending.values()].some((requests) => requests.has(requestId)) ? randomUUID() : requestId;
2167
+ const errorResponse = (_publisherRequestId, request, status, error) => request.kind === "action" ? { type: "action-result", requestId: request.requestId, ok: false, error } : { type: "transcript", requestId: request.requestId, publisherId: request.publisherId, ...request.target.runId === void 0 ? {} : { runId: request.target.runId }, ...request.target.agentId === void 0 ? {} : { agentId: request.target.agentId }, ...request.target.subagentId === void 0 ? {} : { subagentId: request.target.subagentId }, ok: false, status, revision: request.target.revision ?? 0, error };
2168
+ const clearPending = (client, error) => {
2169
+ const own = pending.get(client);
2170
+ if (own) {
2171
+ for (const [requestId, request] of own) {
2172
+ clearTimeout(request.timer);
2173
+ emit(client, errorResponse(requestId, request, "disconnected", error));
2174
+ }
2175
+ own.clear();
2176
+ pending.delete(client);
2177
+ }
2178
+ for (const [browser, requests] of pending) {
2179
+ for (const [requestId, request] of requests) {
2180
+ if (request.publisher !== client) continue;
2181
+ clearTimeout(request.timer);
2182
+ requests.delete(requestId);
2183
+ emit(browser, errorResponse(requestId, request, "disconnected", error));
2184
+ }
2185
+ if (!requests.size) pending.delete(browser);
2186
+ }
2187
+ };
2188
+ const rejectRequest = (browser, requestId, request, error) => {
2189
+ const requests = pending.get(browser);
2190
+ if (!requests || requests.get(requestId) !== request) return;
2191
+ requests.delete(requestId);
2192
+ if (!requests.size) pending.delete(browser);
2193
+ emit(browser, errorResponse(requestId, request, "failed", error));
2194
+ };
2195
+ const scheduleIdleExit = () => {
2196
+ if (closed || [...publishers.values()].some(({ value }) => value.connected === true) || idleTimer !== void 0) return;
2197
+ idleTimer = setTimeout(() => {
2198
+ server.closeAllConnections();
2199
+ for (const client of clients) client.socket.destroy();
2200
+ server.close(() => {
2201
+ void rm(lockPath, { force: true }).then(() => {
2202
+ process.exit(0);
2203
+ }).catch(() => {
2204
+ process.exit(1);
2205
+ });
2206
+ });
2207
+ }, TRAJECTORY_IDLE_EXIT_MS);
2208
+ idleTimer.unref();
2209
+ };
2210
+ const cancelIdleExit = () => {
2211
+ if (idleTimer !== void 0) {
2212
+ clearTimeout(idleTimer);
2213
+ idleTimer = void 0;
2214
+ }
2215
+ };
2216
+ const broadcast = (value) => {
2217
+ if (isState(value)) {
2218
+ try {
2219
+ const stateFrame = frame(encodeState(value, maxFrameBytes), maxFrameBytes);
2220
+ for (const client of clients) if (client.kind === "browser") writeFrame(client, stateFrame, true);
2221
+ } catch {
2222
+ for (const client of clients) if (client.kind === "browser") client.socket.destroy();
2223
+ }
2224
+ return;
2225
+ }
2226
+ for (const client of clients) if (client.kind === "browser") emit(client, value);
2227
+ };
2228
+ const publishState = () => {
2229
+ const values = [...publishers.values()].map(({ value, generation }) => ({ ...value, generation }));
2230
+ latest = { type: "state", publishers: values, updatedAt: Date.now() };
2231
+ broadcast(latest);
2232
+ };
2233
+ const disconnect = (client) => {
2234
+ clearPending(client, client.kind === "publisher" ? "Publisher is disconnected" : "Trajectory browser disconnected");
2235
+ clients.delete(client);
2236
+ if (client.kind === "publisher" && client.publisherId && publishers.get(client.publisherId)?.client === client) {
2237
+ publishers.delete(client.publisherId);
2238
+ publishState();
2239
+ scheduleIdleExit();
2240
+ }
2241
+ };
2242
+ const handleMessage = (client, raw) => {
2243
+ let value;
2244
+ try {
2245
+ value = JSON.parse(raw);
2246
+ } catch {
2247
+ return;
2248
+ }
2249
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
2250
+ const message = value;
2251
+ if (client.superseded) return;
2252
+ if (message.type === "publisher:detach" && client.kind === "publisher" && client.publisherId && publishers.get(client.publisherId)?.client === client) {
2253
+ clearPending(client, "Publisher is disconnected");
2254
+ publishers.delete(client.publisherId);
2255
+ publishState();
2256
+ scheduleIdleExit();
2257
+ return;
2258
+ }
2259
+ if (message.type === "ui:attach") {
2260
+ client.kind = "browser";
2261
+ emit(client, latest);
2262
+ return;
2263
+ }
2264
+ if (client.kind === "publisher" && message.type === "publisher:attach" && typeof message.publisherId === "string") {
2265
+ cancelIdleExit();
2266
+ client.publisherId = message.publisherId;
2267
+ const previous = publishers.get(message.publisherId);
2268
+ if (previous && previous.client !== client) {
2269
+ previous.client.superseded = true;
2270
+ clearPending(previous.client, "Publisher replaced");
2271
+ emit(previous.client, { type: "publisher:replaced" });
2272
+ previous.client.socket.end();
2273
+ }
2274
+ const generation = (previous?.generation ?? 0) + 1;
2275
+ publishers.set(message.publisherId, { client, value: { ...previous?.value ?? { id: message.publisherId }, id: message.publisherId, connected: true }, generation });
2276
+ publishState();
2277
+ return;
2278
+ }
2279
+ if (client.kind === "publisher" && message.type === "publisher:state" && typeof message.publisher === "object" && message.publisher !== null) {
2280
+ const publisher = message.publisher;
2281
+ const id = typeof publisher.id === "string" ? publisher.id : client.publisherId;
2282
+ if (!id || client.publisherId !== id || publishers.get(id)?.client !== client) return;
2283
+ cancelIdleExit();
2284
+ const previous = publishers.get(id);
2285
+ const generation = previous?.generation ?? 1;
2286
+ const runs = Array.isArray(message.runs) ? message.runs : [];
2287
+ const subagents = Array.isArray(message.subagents) ? message.subagents : [];
2288
+ publishers.set(id, { client, value: { ...publisher, connected: true, runs, subagents, generation, ...message.truncated === true || publisher.truncated === true ? { truncated: true } : {} }, generation });
2289
+ publishState();
2290
+ return;
2291
+ }
2292
+ if (client.kind === "publisher" && (message.type === "publisher:action-result" || message.type === "publisher:transcript-result") && typeof message.requestId === "string") {
2293
+ for (const [browser, requests2] of pending) {
2294
+ const request2 = requests2.get(message.requestId);
2295
+ if (!request2 || request2.publisher !== client || request2.publisherId !== message.publisherId || message.type !== (request2.kind === "action" ? "publisher:action-result" : "publisher:transcript-result")) continue;
2296
+ const responseRevision = message.requestedRevision ?? message.revision;
2297
+ const targetMatches = request2.kind === "action" || request2.target.runId === message.runId && request2.target.agentId === message.agentId && request2.target.subagentId === message.subagentId && (request2.target.revision === void 0 || request2.target.revision === responseRevision);
2298
+ if (!targetMatches) return;
2299
+ clearTimeout(request2.timer);
2300
+ requests2.delete(message.requestId);
2301
+ if (!requests2.size) pending.delete(browser);
2302
+ if (request2.kind === "action") emit(browser, { type: "action-result", requestId: request2.requestId, ...message.ok === true ? { ok: true, ...message.result === void 0 ? {} : { result: message.result } } : { ok: false, error: typeof message.error === "string" ? message.error : "Trajectory action failed" } });
2303
+ else emit(browser, { type: "transcript", requestId: request2.requestId, publisherId: request2.publisherId, ...request2.target.runId === void 0 ? {} : { runId: request2.target.runId }, ...request2.target.agentId === void 0 ? {} : { agentId: request2.target.agentId }, ...request2.target.subagentId === void 0 ? {} : { subagentId: request2.target.subagentId }, ok: message.ok === true, status: typeof message.status === "string" ? message.status : message.ok === true ? "available" : "failed", revision: typeof message.revision === "number" ? message.revision : request2.target.revision ?? 0, ...message.ok === true ? { entries: Array.isArray(message.entries) ? message.entries : [] } : { error: typeof message.error === "string" ? message.error : "Transcript failed" } });
2304
+ return;
2305
+ }
2306
+ return;
2307
+ }
2308
+ if (client.kind === "browser" && message.type === "ui:transcript") {
2309
+ const validId = (value2) => typeof value2 === "string" && value2.length >= 1 && value2.length <= 200;
2310
+ if (!validId(message.publisherId)) return;
2311
+ const runRequest = validId(message.runId) && validId(message.agentId) && message.subagentId === void 0;
2312
+ const subagentRequest = validId(message.subagentId) && message.runId === void 0 && message.agentId === void 0;
2313
+ if (!runRequest && !subagentRequest) return;
2314
+ const requestId2 = validId(message.requestId) ? message.requestId : randomUUID();
2315
+ const revision = message.revision === void 0 ? void 0 : typeof message.revision === "number" && Number.isSafeInteger(message.revision) && message.revision >= 0 ? message.revision : void 0;
2316
+ const target2 = publishers.get(message.publisherId);
2317
+ if (!target2 || !target2.value.connected) {
2318
+ emit(client, { type: "transcript", requestId: requestId2, publisherId: message.publisherId, ...runRequest ? { runId: message.runId, agentId: message.agentId } : { subagentId: message.subagentId }, ok: false, status: "disconnected", revision: revision ?? 0, error: "Publisher is disconnected" });
2319
+ return;
2320
+ }
2321
+ let legacyEntries;
2322
+ if (runRequest && Array.isArray(target2.value.runs)) {
2323
+ for (const item of target2.value.runs) {
2324
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
2325
+ const record = item;
2326
+ if (record.run?.id !== message.runId || !record.transcripts || typeof record.transcripts !== "object" || Array.isArray(record.transcripts)) continue;
2327
+ const found = record.transcripts[message.agentId];
2328
+ if (Array.isArray(found)) legacyEntries = found;
2329
+ break;
2330
+ }
2331
+ } else if (subagentRequest && Array.isArray(target2.value.subagents)) {
2332
+ for (const item of target2.value.subagents) {
2333
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
2334
+ const record = item;
2335
+ if (record.id === message.subagentId && Array.isArray(record.transcript)) {
2336
+ legacyEntries = record.transcript;
2337
+ break;
2338
+ }
2339
+ }
2340
+ }
2341
+ if (legacyEntries !== void 0) {
2342
+ const reply = { type: "transcript", requestId: requestId2, publisherId: message.publisherId, ...runRequest ? { runId: message.runId, agentId: message.agentId } : { subagentId: message.subagentId }, ok: true, status: legacyEntries.length ? "available" : "empty", revision: revision ?? 1, entries: legacyEntries };
2343
+ if (Buffer.byteLength(JSON.stringify(reply)) > maxFrameBytes) emit(client, { ...reply, ok: false, status: "oversized", entries: void 0, error: "Transcript is too large" });
2344
+ else emit(client, reply);
2345
+ return;
2346
+ }
2347
+ const requests2 = pendingFor(client);
2348
+ const requestTarget = runRequest ? { runId: message.runId, agentId: message.agentId, ...revision === void 0 ? {} : { revision } } : { subagentId: message.subagentId, ...revision === void 0 ? {} : { revision } };
2349
+ if (requests2.size >= MAX_PENDING_REQUESTS || hasPendingRequest(requests2, requestId2)) {
2350
+ emit(client, { type: "transcript", requestId: requestId2, publisherId: message.publisherId, ...runRequest ? { runId: message.runId, agentId: message.agentId } : { subagentId: message.subagentId }, ok: false, status: "failed", revision: revision ?? 0, error: "Too many pending Trajectory requests" });
2351
+ return;
2352
+ }
2353
+ const publisherRequestId2 = publisherRequestIdFor(requestId2);
2354
+ const request2 = { requestId: requestId2, kind: "transcript", browser: client, publisherId: message.publisherId, publisher: target2.client, target: requestTarget, timer: setTimeout(() => {
2355
+ rejectRequest(client, publisherRequestId2, request2, "Trajectory request timed out");
2356
+ }, TRANSCRIPT_REQUEST_TIMEOUT_MS) };
2357
+ requests2.set(publisherRequestId2, request2);
2358
+ emit(target2.client, { type: "publisher:transcript", requestId: publisherRequestId2, publisherId: message.publisherId, ...runRequest ? { runId: message.runId, agentId: message.agentId } : { subagentId: message.subagentId }, ...revision === void 0 ? {} : { revision } });
2359
+ return;
2360
+ }
2361
+ if (client.kind !== "browser" || message.type !== "ui:action" || typeof message.publisherId !== "string") return;
2362
+ const requestId = typeof message.requestId === "string" && message.requestId.length >= 1 && message.requestId.length <= 200 ? message.requestId : randomUUID();
2363
+ if (!isTrajectoryAction(message.action)) {
2364
+ emit(client, { type: "action-result", requestId, ok: false, error: "Unsupported Trajectory action" });
2365
+ return;
2366
+ }
2367
+ if (!isTrajectoryTarget(message.target)) {
2368
+ emit(client, { type: "action-result", requestId, ok: false, error: "Invalid Trajectory action target" });
2369
+ return;
2370
+ }
2371
+ const actionError = trajectoryActionError(message.action, message.target);
2372
+ if (actionError !== void 0) {
2373
+ emit(client, { type: "action-result", requestId, ok: false, error: actionError });
2374
+ return;
2375
+ }
2376
+ const target = publishers.get(message.publisherId);
2377
+ if (!target || !target.value.connected) {
2378
+ emit(client, { type: "action-result", requestId, ok: false, error: "Publisher is disconnected" });
2379
+ return;
2380
+ }
2381
+ const publisherRequestId = publisherRequestIdFor(requestId);
2382
+ const outbound = { type: "publisher:action", requestId: publisherRequestId, action: message.action, target: message.target, ...typeof message.name === "string" ? { name: message.name } : {}, ...message.payload === void 0 ? {} : { payload: message.payload } };
2383
+ if (Buffer.byteLength(JSON.stringify(outbound)) >= maxFrameBytes) {
2384
+ emit(client, { type: "action-result", requestId, ok: false, error: "Trajectory action is too large" });
2385
+ return;
2386
+ }
2387
+ const requests = pendingFor(client);
2388
+ if (requests.size >= MAX_PENDING_REQUESTS || hasPendingRequest(requests, requestId)) {
2389
+ emit(client, { type: "action-result", requestId, ok: false, error: "Too many pending Trajectory requests" });
2390
+ return;
2391
+ }
2392
+ const request = { requestId, kind: "action", browser: client, publisherId: message.publisherId, publisher: target.client, target: {}, timer: setTimeout(() => {
2393
+ rejectRequest(client, publisherRequestId, request, "Trajectory request timed out");
2394
+ }, ACTION_REQUEST_TIMEOUT_MS) };
2395
+ requests.set(publisherRequestId, request);
2396
+ emit(target.client, outbound);
2397
+ };
2398
+ const server = createServer((request, response) => {
2399
+ let url;
2400
+ try {
2401
+ url = new URL(request.url ?? "/", `http://127.0.0.1:${String(port)}`);
2402
+ } catch {
2403
+ writeJson(response, 400, { error: "Invalid request" });
2404
+ return;
2405
+ }
2406
+ if (!authorized(request, port)) {
2407
+ writeJson(response, 403, { error: "Forbidden" });
2408
+ return;
2409
+ }
2410
+ const path2 = url.pathname;
2411
+ if (request.method === "GET" && path2 === "/health") {
2412
+ writeJson(response, 200, { ok: true });
2413
+ return;
2414
+ }
2415
+ if (request.method === "GET" && (path2 === "/" || path2 === "/index.html")) {
2416
+ void readFile(new URL("./assets/index.html", import.meta.url)).then((html) => {
2417
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-length": html.byteLength, "cache-control": "no-store" });
2418
+ response.end(html);
2419
+ }).catch(() => {
2420
+ writeJson(response, 500, { error: "Trajectory UI is unavailable" });
2421
+ });
2422
+ return;
2423
+ }
2424
+ if (request.method === "GET" && path2 === "/marked.min.js") {
2425
+ void readFile(new URL("./assets/marked.min.js", import.meta.url)).then((script) => {
2426
+ response.writeHead(200, { "content-type": "application/javascript; charset=utf-8", "content-length": script.byteLength, "cache-control": "no-store" });
2427
+ response.end(script);
2428
+ }).catch(() => {
2429
+ writeJson(response, 500, { error: "Trajectory markdown renderer is unavailable" });
2430
+ });
2431
+ return;
2432
+ }
2433
+ if (request.method === "GET" && path2 === "/morphdom.min.js") {
2434
+ void readFile(new URL("./assets/morphdom.min.js", import.meta.url)).then((script) => {
2435
+ response.writeHead(200, { "content-type": "application/javascript; charset=utf-8", "content-length": script.byteLength, "cache-control": "no-store" });
2436
+ response.end(script);
2437
+ }).catch(() => {
2438
+ writeJson(response, 500, { error: "Trajectory DOM diffing library is unavailable" });
2439
+ });
2440
+ return;
2441
+ }
2442
+ if (request.method === "GET" && (path2 === "/favicon.png" || path2 === "/favicon.ico")) {
2443
+ void readFile(new URL("./assets/favicon.png", import.meta.url)).then((icon) => {
2444
+ response.writeHead(200, { "content-type": "image/png", "content-length": icon.byteLength, "cache-control": "no-store" });
2445
+ response.end(icon);
2446
+ }).catch(() => {
2447
+ writeJson(response, 404, { error: "Not found" });
2448
+ });
2449
+ return;
2450
+ }
2451
+ writeJson(response, 404, { error: "Not found" });
2452
+ });
2453
+ server.on("upgrade", (request, socket) => {
2454
+ let url;
2455
+ try {
2456
+ url = new URL(request.url ?? "/", `http://127.0.0.1:${String(port)}`);
2457
+ } catch {
2458
+ socket.destroy();
2459
+ return;
2460
+ }
2461
+ const key = request.headers["sec-websocket-key"];
2462
+ if (!authorized(request, port) || url.pathname !== "/ws" || typeof key !== "string") {
2463
+ socket.destroy();
2464
+ return;
2465
+ }
2466
+ const accept = createHash("sha1").update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64");
2467
+ socket.write(`HTTP/1.1 101 Switching Protocols\r
2468
+ Upgrade: websocket\r
2469
+ Connection: Upgrade\r
2470
+ Sec-WebSocket-Accept: ${accept}\r
2471
+ \r
2472
+ `);
2473
+ const client = { socket, kind: "publisher", buffer: Buffer.alloc(0), pendingState: void 0, backpressured: false, superseded: false };
2474
+ socket.on("drain", () => {
2475
+ const pendingState = client.pendingState;
2476
+ client.pendingState = void 0;
2477
+ client.backpressured = false;
2478
+ if (pendingState !== void 0) writeFrame(client, pendingState, true);
2479
+ });
2480
+ clients.add(client);
2481
+ socket.on("data", (chunk) => {
2482
+ if (!Buffer.isBuffer(chunk)) return;
2483
+ try {
2484
+ for (const message of parseFrames(client, chunk, maxFrameBytes)) handleMessage(client, message);
2485
+ } catch {
2486
+ socket.destroy();
2487
+ }
2488
+ });
2489
+ socket.on("close", () => {
2490
+ disconnect(client);
2491
+ });
2492
+ socket.on("error", () => {
2493
+ disconnect(client);
2494
+ });
2495
+ });
2496
+ server.once("listening", () => {
2497
+ void writeFile(lockPath, `${JSON.stringify({ pid: process.pid, port, fingerprint: serverFingerprint, startedAt: Date.now() })}
2498
+ `, { mode: 384 }).catch(() => {
2499
+ process.exitCode = 1;
2500
+ });
2501
+ scheduleIdleExit();
2502
+ });
2503
+ server.on("close", () => {
2504
+ closed = true;
2505
+ if (idleTimer !== void 0) {
2506
+ clearTimeout(idleTimer);
2507
+ idleTimer = void 0;
2508
+ }
2509
+ });
2510
+ return server;
2511
+ }
2512
+ async function main() {
2513
+ const args = /* @__PURE__ */ new Map();
2514
+ for (let index = 2; index + 1 < process.argv.length; index += 2) args.set(process.argv[index] ?? "", process.argv[index + 1] ?? "");
2515
+ const port = Number(args.get("--port"));
2516
+ const lockPath = args.get("--lock");
2517
+ const fingerprint = args.get("--fingerprint");
2518
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535 || !lockPath || !fingerprint) throw new Error("Invalid Trajectory server arguments");
2519
+ const server = createTrajectoryServer(port, lockPath, { fingerprint });
2520
+ await new Promise((resolve2, reject) => {
2521
+ server.once("error", reject);
2522
+ server.listen(port, "127.0.0.1", () => {
2523
+ resolve2();
2524
+ });
2525
+ });
2526
+ }
2527
+ if (process.argv[1] && sameFilesystemPath(fileURLToPath(import.meta.url), process.argv[1])) void main().catch((error) => {
2528
+ console.error(error);
2529
+ process.exitCode = 1;
2530
+ });
2531
+ export {
2532
+ createTrajectoryServer
2533
+ };
2534
+ //# sourceMappingURL=server.js.map