@nyte-ai/host 0.0.0-stage → 0.0.19

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 (250) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/THIRD-PARTY-NOTICES.md +866 -0
  4. package/dist/chunks/canvas-preview-0cmbkp2j.js +65 -0
  5. package/dist/chunks/canvas-preview-0nq75h9k.js +7 -0
  6. package/dist/chunks/canvas-preview-11nadadc.js +241 -0
  7. package/dist/chunks/canvas-preview-1sq7z9jq.js +17 -0
  8. package/dist/chunks/canvas-preview-2jwbe14k.js +130 -0
  9. package/dist/chunks/canvas-preview-2zdyh9ny.js +26 -0
  10. package/dist/chunks/canvas-preview-31w7xm8z.js +34 -0
  11. package/dist/chunks/canvas-preview-4b6sayhg.js +295 -0
  12. package/dist/chunks/canvas-preview-4e0pxa32.js +63 -0
  13. package/dist/chunks/canvas-preview-518dh8by.js +169 -0
  14. package/dist/chunks/canvas-preview-55s0y68g.js +387 -0
  15. package/dist/chunks/canvas-preview-5ekjx6sw.js +613 -0
  16. package/dist/chunks/canvas-preview-5mex725c.js +14 -0
  17. package/dist/chunks/canvas-preview-5z63am63.js +295 -0
  18. package/dist/chunks/canvas-preview-65xqjw7f.js +20 -0
  19. package/dist/chunks/canvas-preview-69fkk9yn.js +95 -0
  20. package/dist/chunks/canvas-preview-8xc0vn7v.js +458 -0
  21. package/dist/chunks/canvas-preview-9aqczacs.js +73 -0
  22. package/dist/chunks/canvas-preview-af86jz8t.js +141 -0
  23. package/dist/chunks/canvas-preview-aq5j4p25.js +240 -0
  24. package/dist/chunks/canvas-preview-b2v8wfnz.js +36 -0
  25. package/dist/chunks/canvas-preview-befkjea2.js +60 -0
  26. package/dist/chunks/canvas-preview-bxnqt8cd.js +103 -0
  27. package/dist/chunks/canvas-preview-cawy6vbz.js +352 -0
  28. package/dist/chunks/canvas-preview-crmzxxt8.js +518 -0
  29. package/dist/chunks/canvas-preview-drctegz4.js +591 -0
  30. package/dist/chunks/canvas-preview-e3vnkkc5.js +134 -0
  31. package/dist/chunks/canvas-preview-ec2mt7es.js +108 -0
  32. package/dist/chunks/canvas-preview-fxa0rfb0.js +61 -0
  33. package/dist/chunks/canvas-preview-g5fkjs34.js +598 -0
  34. package/dist/chunks/canvas-preview-jeddjex8.js +166 -0
  35. package/dist/chunks/canvas-preview-k1yg4fgp.js +571 -0
  36. package/dist/chunks/canvas-preview-kdqgrstc.js +194 -0
  37. package/dist/chunks/canvas-preview-kn7kvbfj.js +12 -0
  38. package/dist/chunks/canvas-preview-kp75gb63.js +141 -0
  39. package/dist/chunks/canvas-preview-mgcx2b2p.js +271 -0
  40. package/dist/chunks/canvas-preview-n2a35zv5.js +81 -0
  41. package/dist/chunks/canvas-preview-pkzqg96v.js +63 -0
  42. package/dist/chunks/canvas-preview-rp4x6y1h.js +144 -0
  43. package/dist/chunks/canvas-preview-s94ebwf5.js +112 -0
  44. package/dist/chunks/canvas-preview-skzwvw4d.js +23 -0
  45. package/dist/chunks/canvas-preview-srgfpdmf.js +60 -0
  46. package/dist/chunks/canvas-preview-tjhabynd.js +252 -0
  47. package/dist/chunks/canvas-preview-tnqe7k0b.js +374 -0
  48. package/dist/chunks/canvas-preview-vaatfznm.js +189 -0
  49. package/dist/chunks/canvas-preview-vm9zdp2t.js +398 -0
  50. package/dist/chunks/canvas-preview-w54ymtb3.js +272 -0
  51. package/dist/chunks/canvas-preview-wg80rbc2.js +46 -0
  52. package/dist/chunks/canvas-preview-y5y6ghaw.js +125 -0
  53. package/dist/chunks/canvas-preview-ycepb05s.js +176 -0
  54. package/dist/chunks/canvas-preview-yjz0f7n4.js +50 -0
  55. package/dist/chunks/canvas-preview-zaaj99wd.js +244 -0
  56. package/dist/src/canvas-preview.d.ts +29 -0
  57. package/dist/src/canvas-preview.js +271 -0
  58. package/dist/src/credentials.d.ts +44 -0
  59. package/dist/src/credentials.js +10 -0
  60. package/dist/src/deploy/cloudflare/worker.d.ts +50 -0
  61. package/dist/src/deploy/cloudflare/worker.js +196 -0
  62. package/dist/src/deploy/vercel/nitro.config.d.ts +2 -0
  63. package/dist/src/deploy/vercel/nitro.config.js +30 -0
  64. package/dist/src/deploy/vercel/server/routes/[...].d.ts +2 -0
  65. package/dist/src/deploy/vercel/server/routes/[...].js +18 -0
  66. package/dist/src/deploy/vercel/server/utils/host.d.ts +13 -0
  67. package/dist/src/deploy/vercel/server/utils/host.js +7 -0
  68. package/dist/src/deploy/vercel/server/utils/repair.d.ts +1 -0
  69. package/dist/src/deploy/vercel/server/utils/repair.js +6 -0
  70. package/dist/src/deploy/vercel/server/utils/step.d.ts +10 -0
  71. package/dist/src/deploy/vercel/server/utils/step.js +6 -0
  72. package/dist/src/deploy/vercel/server/workflows/drive.d.ts +14 -0
  73. package/dist/src/deploy/vercel/server/workflows/drive.js +13 -0
  74. package/dist/src/durable-object.d.ts +14 -0
  75. package/dist/src/durable-object.js +231 -0
  76. package/dist/src/hash.d.ts +1 -0
  77. package/dist/src/hash.js +6 -0
  78. package/dist/src/identity-key.d.ts +11 -0
  79. package/dist/src/identity-key.js +9 -0
  80. package/dist/src/identity.d.ts +12 -0
  81. package/dist/src/identity.js +6 -0
  82. package/dist/src/images/exif.d.ts +1 -0
  83. package/dist/src/images/exif.js +6 -0
  84. package/dist/src/images/node.d.ts +37 -0
  85. package/dist/src/images/node.js +12 -0
  86. package/dist/src/images/photon.d.ts +3 -0
  87. package/dist/src/images/photon.js +7 -0
  88. package/dist/src/images/worker.d.ts +1 -0
  89. package/dist/src/images/worker.js +23 -0
  90. package/dist/src/index.d.ts +20 -0
  91. package/dist/src/index.js +121 -0
  92. package/dist/src/key-file.d.ts +1 -0
  93. package/dist/src/key-file.js +7 -0
  94. package/dist/src/listen-fetch.d.ts +8 -0
  95. package/dist/src/listen-fetch.js +9 -0
  96. package/dist/src/listen.d.ts +4 -0
  97. package/dist/src/listen.js +10 -0
  98. package/dist/src/local/command.d.ts +20 -0
  99. package/dist/src/local/command.js +12 -0
  100. package/dist/src/local/feed.d.ts +7 -0
  101. package/dist/src/local/feed.js +6 -0
  102. package/dist/src/local/files.d.ts +18 -0
  103. package/dist/src/local/files.js +13 -0
  104. package/dist/src/local/git-watch.d.ts +15 -0
  105. package/dist/src/local/git-watch.js +7 -0
  106. package/dist/src/local/git.d.ts +5 -0
  107. package/dist/src/local/git.js +13 -0
  108. package/dist/src/local/github.d.ts +30 -0
  109. package/dist/src/local/github.js +9 -0
  110. package/dist/src/local/identity.d.ts +3 -0
  111. package/dist/src/local/identity.js +7 -0
  112. package/dist/src/local/jobs.d.ts +7 -0
  113. package/dist/src/local/jobs.js +7 -0
  114. package/dist/src/local/legacy-trust.d.ts +10 -0
  115. package/dist/src/local/legacy-trust.js +6 -0
  116. package/dist/src/local/patch.d.ts +16 -0
  117. package/dist/src/local/patch.js +17 -0
  118. package/dist/src/local/provider.d.ts +11 -0
  119. package/dist/src/local/provider.js +20 -0
  120. package/dist/src/local/snapshots.d.ts +7 -0
  121. package/dist/src/local/snapshots.js +11 -0
  122. package/dist/src/local/text.d.ts +1 -0
  123. package/dist/src/local/text.js +6 -0
  124. package/dist/src/local/tree.d.ts +50 -0
  125. package/dist/src/local/tree.js +16 -0
  126. package/dist/src/local/workspace-migration.d.ts +2 -0
  127. package/dist/src/local/workspace-migration.js +7 -0
  128. package/dist/src/local/worktrees.d.ts +46 -0
  129. package/dist/src/local/worktrees.js +14 -0
  130. package/dist/src/mcp/config.d.ts +75 -0
  131. package/dist/src/mcp/config.js +12 -0
  132. package/dist/src/mcp/connect.d.ts +15 -0
  133. package/dist/src/mcp/connect.js +9 -0
  134. package/dist/src/mcp/hub.d.ts +19 -0
  135. package/dist/src/mcp/hub.js +11 -0
  136. package/dist/src/mcp/oauth.d.ts +46 -0
  137. package/dist/src/mcp/oauth.js +12 -0
  138. package/dist/src/mcp/tools.d.ts +29 -0
  139. package/dist/src/mcp/tools.js +12 -0
  140. package/dist/src/open.d.ts +14 -0
  141. package/dist/src/open.js +46 -0
  142. package/dist/src/plugins/loader.d.ts +21 -0
  143. package/dist/src/plugins/loader.js +11 -0
  144. package/dist/src/postgres.d.ts +19 -0
  145. package/dist/src/postgres.js +8 -0
  146. package/dist/src/providers.d.ts +16 -0
  147. package/dist/src/providers.js +112 -0
  148. package/dist/src/secrets.d.ts +12 -0
  149. package/dist/src/secrets.js +8 -0
  150. package/dist/src/serve/binding.d.ts +39 -0
  151. package/dist/src/serve/binding.js +6 -0
  152. package/dist/src/serve/handler.d.ts +15 -0
  153. package/dist/src/serve/handler.js +8 -0
  154. package/dist/src/serve/stream-server.d.ts +6 -0
  155. package/dist/src/serve/stream-server.js +6 -0
  156. package/dist/src/session-index.d.ts +11 -0
  157. package/dist/src/session-index.js +11 -0
  158. package/dist/src/shell-env.d.ts +14 -0
  159. package/dist/src/shell-env.js +108 -0
  160. package/dist/src/sqlite-workers.d.ts +6 -0
  161. package/dist/src/sqlite-workers.js +6 -0
  162. package/dist/src/sqlite.d.ts +8 -0
  163. package/dist/src/sqlite.js +11 -0
  164. package/dist/src/store-rows.d.ts +13 -0
  165. package/dist/src/store-rows.js +26 -0
  166. package/dist/src/store-usage.d.ts +25 -0
  167. package/dist/src/store-usage.js +19 -0
  168. package/dist/src/usage-history.d.ts +54 -0
  169. package/dist/src/usage-history.js +14 -0
  170. package/dist/src/usage-scan.d.ts +24 -0
  171. package/dist/src/usage-scan.js +65 -0
  172. package/dist/src/usage-service.d.ts +23 -0
  173. package/dist/src/usage-service.js +16 -0
  174. package/dist/src/usage-summary.d.ts +9 -0
  175. package/dist/src/usage-summary.js +16 -0
  176. package/dist/src/usage-types.d.ts +86 -0
  177. package/dist/src/usage-types.js +0 -0
  178. package/dist/src/usage-worker.d.ts +1 -0
  179. package/dist/src/usage-worker.js +29 -0
  180. package/dist/src/usage.d.ts +195 -0
  181. package/dist/src/usage.js +23 -0
  182. package/package.json +140 -3
  183. package/src/canvas-preview.ts +403 -0
  184. package/src/credentials.ts +294 -0
  185. package/src/deploy/cloudflare/README.md +3 -0
  186. package/src/deploy/cloudflare/worker.ts +306 -0
  187. package/src/deploy/cloudflare/wrangler.jsonc +12 -0
  188. package/src/deploy/vercel/README.md +3 -0
  189. package/src/deploy/vercel/nitro.config.ts +29 -0
  190. package/src/deploy/vercel/server/routes/[...].ts +10 -0
  191. package/src/deploy/vercel/server/utils/host.ts +104 -0
  192. package/src/deploy/vercel/server/utils/repair.ts +35 -0
  193. package/src/deploy/vercel/server/utils/step.ts +25 -0
  194. package/src/deploy/vercel/server/workflows/drive.ts +46 -0
  195. package/src/deploy/vercel/tsconfig.json +9 -0
  196. package/src/deploy/vercel/types/bun.d.ts +2 -0
  197. package/src/durable-object.ts +386 -0
  198. package/src/hash.ts +5 -0
  199. package/src/identity-key.ts +20 -0
  200. package/src/identity.ts +66 -0
  201. package/src/images/exif.ts +69 -0
  202. package/src/images/node.ts +163 -0
  203. package/src/images/photon.ts +141 -0
  204. package/src/images/worker.ts +29 -0
  205. package/src/index.ts +39 -0
  206. package/src/key-file.ts +53 -0
  207. package/src/listen-fetch.ts +409 -0
  208. package/src/listen.ts +228 -0
  209. package/src/local/command.ts +161 -0
  210. package/src/local/feed.ts +70 -0
  211. package/src/local/files.ts +817 -0
  212. package/src/local/git-watch.ts +199 -0
  213. package/src/local/git.ts +919 -0
  214. package/src/local/github.ts +691 -0
  215. package/src/local/identity.ts +21 -0
  216. package/src/local/jobs.ts +573 -0
  217. package/src/local/legacy-trust.ts +105 -0
  218. package/src/local/patch.ts +334 -0
  219. package/src/local/provider.ts +184 -0
  220. package/src/local/snapshots.ts +778 -0
  221. package/src/local/text.ts +9 -0
  222. package/src/local/tree.ts +398 -0
  223. package/src/local/workspace-migration.ts +95 -0
  224. package/src/local/worktrees.ts +239 -0
  225. package/src/mcp/config.ts +330 -0
  226. package/src/mcp/connect.ts +92 -0
  227. package/src/mcp/hub.ts +836 -0
  228. package/src/mcp/oauth.ts +436 -0
  229. package/src/mcp/tools.ts +333 -0
  230. package/src/open.ts +449 -0
  231. package/src/plugins/loader.ts +186 -0
  232. package/src/postgres.ts +492 -0
  233. package/src/providers.ts +135 -0
  234. package/src/secrets.ts +31 -0
  235. package/src/serve/binding.ts +629 -0
  236. package/src/serve/handler.ts +362 -0
  237. package/src/serve/stream-server.ts +176 -0
  238. package/src/session-index.ts +99 -0
  239. package/src/shell-env.ts +153 -0
  240. package/src/sqlite-workers.ts +283 -0
  241. package/src/sqlite.ts +553 -0
  242. package/src/store-rows.ts +110 -0
  243. package/src/store-usage.ts +347 -0
  244. package/src/usage-history.ts +219 -0
  245. package/src/usage-scan.ts +81 -0
  246. package/src/usage-service.ts +82 -0
  247. package/src/usage-summary.ts +79 -0
  248. package/src/usage-types.ts +87 -0
  249. package/src/usage-worker.ts +24 -0
  250. package/src/usage.ts +776 -0
@@ -0,0 +1,591 @@
1
+ import {
2
+ sha2562
3
+ } from "./canvas-preview-0nq75h9k.js";
4
+ import {
5
+ run2,
6
+ findExecutable2
7
+ } from "./canvas-preview-bxnqt8cd.js";
8
+ import {
9
+ feed2
10
+ } from "./canvas-preview-yjz0f7n4.js";
11
+ import {
12
+ decodeText2
13
+ } from "./canvas-preview-kn7kvbfj.js";
14
+ import {
15
+ createIgnores2,
16
+ walkTree2,
17
+ watchTree2,
18
+ watchPath2,
19
+ readErrorCode2
20
+ } from "./canvas-preview-mgcx2b2p.js";
21
+
22
+ // src/local/files.ts
23
+ import { createHash, randomUUID } from "node:crypto";
24
+ import {
25
+ chmod,
26
+ lstat,
27
+ mkdir,
28
+ open,
29
+ readFile,
30
+ readdir,
31
+ readlink,
32
+ realpath,
33
+ rename,
34
+ rm,
35
+ stat,
36
+ unlink,
37
+ writeFile
38
+ } from "node:fs/promises";
39
+ import { basename, dirname, isAbsolute, join, matchesGlob, relative, sep } from "node:path";
40
+ import { createInterface } from "node:readline";
41
+ import { spawn } from "node:child_process";
42
+ import { asId, SdkError } from "@nyte-ai/schema";
43
+ import { serial } from "@nyte-ai/schema/serial";
44
+ import { Type } from "typebox";
45
+ import { Value } from "typebox/value";
46
+ var TEXT_LIMIT2 = 1024 * 1024;
47
+ var CHUNK = 64 * 1024;
48
+ var FIND_DEFAULT = 20;
49
+ var FIND_CAP = 50;
50
+ var FIND_TTL_MS = 5000;
51
+ var SEARCH_DEFAULT = 200;
52
+ var SEARCH_LINE = 500;
53
+ var WATCH_DELAY_MS = 100;
54
+ var WATCH_POLL_MS = 1000;
55
+ var FORMATTERS = ["oxfmt", "prettier", "biome"];
56
+ function localFiles2(root, options) {
57
+ const absolute = (path) => isAbsolute(path) ? path : join(root, path);
58
+ const within = (path) => {
59
+ const inside = relative(root, path);
60
+ return inside.startsWith("..") || isAbsolute(inside) ? path : inside.split(sep).join("/");
61
+ };
62
+ let found = null;
63
+ const scanned = () => {
64
+ if (found !== null && Date.now() - found.at < FIND_TTL_MS)
65
+ return found.paths;
66
+ const paths = collectFiles(root);
67
+ found = { at: Date.now(), paths };
68
+ paths.catch(() => {
69
+ if (found?.paths === paths)
70
+ found = null;
71
+ });
72
+ return paths;
73
+ };
74
+ return {
75
+ async read(path) {
76
+ const target = absolute(path);
77
+ const stats = await stat(target).catch(missing);
78
+ if (stats === null)
79
+ return { kind: "missing", path };
80
+ if (stats.isDirectory())
81
+ throw new SdkError("invalid", `${path} is a directory.`);
82
+ if (stats.size > TEXT_LIMIT2)
83
+ return { kind: "large", path, size: stats.size, version: await hashFile(target) };
84
+ const bytes = await readFile(target).catch(missing);
85
+ if (bytes === null)
86
+ return { kind: "missing", path };
87
+ const version = hashVersion(bytes);
88
+ const text = decodeText2(bytes);
89
+ return text === null ? { kind: "binary", path, size: bytes.byteLength, version } : { kind: "text", path, contents: text, version };
90
+ },
91
+ async bytes(path) {
92
+ const target = absolute(path);
93
+ const stats = await stat(target).catch(missing);
94
+ if (stats === null || !stats.isFile())
95
+ throw new SdkError("unknown", `No file is at ${path}.`);
96
+ const version = await hashFile(target);
97
+ let handle = null;
98
+ const close = async () => {
99
+ const held = handle;
100
+ handle = null;
101
+ await held?.close();
102
+ };
103
+ return {
104
+ size: stats.size,
105
+ mime: null,
106
+ version,
107
+ async* chunks() {
108
+ handle = await open(target, "r");
109
+ try {
110
+ for (;; ) {
111
+ const held = handle;
112
+ if (held === null)
113
+ return;
114
+ const buffer = new Uint8Array(CHUNK);
115
+ const { bytesRead } = await held.read(buffer, 0, CHUNK, null);
116
+ if (bytesRead === 0)
117
+ return;
118
+ yield buffer.subarray(0, bytesRead);
119
+ }
120
+ } finally {
121
+ await close();
122
+ }
123
+ },
124
+ close,
125
+ [Symbol.asyncDispose]: close
126
+ };
127
+ },
128
+ async stat(path) {
129
+ const target = absolute(path);
130
+ const stats = await lstat(target).catch(missing);
131
+ if (stats === null)
132
+ return null;
133
+ if (stats.isSymbolicLink()) {
134
+ const link = await readLink(target);
135
+ return { kind: "symlink", size: stats.size, version: hashVersion(link), target: link };
136
+ }
137
+ if (stats.isDirectory())
138
+ return { kind: "directory", size: stats.size, version: await directoryVersion(target) };
139
+ return { kind: "file", size: stats.size, version: await hashFile(target) };
140
+ },
141
+ async write(path, contents, writeOptions) {
142
+ const target = await resolveLink(absolute(path));
143
+ const current = await currentVersion(target);
144
+ const expect = writeOptions?.expect;
145
+ if (expect === "absent" ? current !== null : expect !== undefined && expect !== current)
146
+ return { kind: "stale", current };
147
+ const parent = dirname(target);
148
+ const folder = await stat(parent).catch(missing);
149
+ if (folder === null) {
150
+ if (writeOptions?.parents !== true)
151
+ return { kind: "missing-parent" };
152
+ await mkdir(parent, { recursive: true });
153
+ } else if (!folder.isDirectory())
154
+ throw new SdkError("invalid", `${dirname(path)} is not a directory.`);
155
+ const bytes = typeof contents === "string" ? new TextEncoder().encode(contents) : contents;
156
+ const mode = (await stat(target).catch(missing))?.mode;
157
+ const temporary = join(parent, `.${basename(target)}.${randomUUID()}.nyte-tmp`);
158
+ try {
159
+ await writeFile(temporary, bytes);
160
+ if (mode !== undefined)
161
+ await chmod(temporary, mode & 4095);
162
+ await rename(temporary, target);
163
+ } catch (error) {
164
+ await unlink(temporary).catch(() => {
165
+ return;
166
+ });
167
+ throw error;
168
+ }
169
+ return { kind: "saved", version: hashVersion(bytes) };
170
+ },
171
+ async remove(path, removeOptions) {
172
+ const target = absolute(path);
173
+ const link = await lstat(target).catch(missing);
174
+ if (link === null)
175
+ return { kind: "stale", current: null };
176
+ const current = await currentVersion(target) ?? (link.isSymbolicLink() ? hashVersion(await readLink(target)) : null);
177
+ if (removeOptions?.expect !== undefined && removeOptions.expect !== current)
178
+ return { kind: "stale", current };
179
+ await rm(target, { recursive: link.isDirectory() });
180
+ return current === null ? { kind: "stale", current } : { kind: "saved", version: current };
181
+ },
182
+ batch: () => refusedBatch(),
183
+ async format(path, contents) {
184
+ return format(root, absolute(path), contents, options?.formatter);
185
+ },
186
+ async* scan(input) {
187
+ const directory = input?.directory ?? "";
188
+ const own = isAbsolute(directory);
189
+ const base = own ? directory : root;
190
+ const start = own ? "" : directory;
191
+ const ignores = createIgnores2(base);
192
+ const ignored = input?.ignored === "include" || start !== "" && await ignores.ignored(start, true) ? "include" : "exclude";
193
+ for await (const frame of walkTree2(base, { directory: start, ignored, ignores })) {
194
+ if (frame.kind !== "entries") {
195
+ yield frame;
196
+ continue;
197
+ }
198
+ yield {
199
+ kind: "entries",
200
+ entries: frame.entries.map((entry) => ({
201
+ path: own ? join(directory, entry.path) : entry.path,
202
+ kind: entry.kind,
203
+ size: entry.size,
204
+ version: null
205
+ }))
206
+ };
207
+ }
208
+ },
209
+ async find(input) {
210
+ const limit = Math.min(Math.max(1, input.limit ?? FIND_DEFAULT), FIND_CAP);
211
+ return rank(await scanned(), input.query, limit);
212
+ },
213
+ search(input) {
214
+ const drafts = new Map((input.drafts ?? []).map((draft) => [within(absolute(draft.path)), draft.contents]));
215
+ return search(root, input, drafts, options?.ripgrep);
216
+ },
217
+ watch(input) {
218
+ const paths = (input?.paths ?? []).map((path) => within(absolute(path)));
219
+ return watchFiles(root, paths, options?.signal);
220
+ },
221
+ upload: async () => {
222
+ throw new SdkError("unavailable", "Core stores uploads; the local provider does not.");
223
+ }
224
+ };
225
+ }
226
+ function hashVersion(data) {
227
+ return asId(sha2562(data));
228
+ }
229
+ function missing(error) {
230
+ const code = readErrorCode2(error);
231
+ if (code === "ENOENT" || code === "ENOTDIR")
232
+ return null;
233
+ throw error;
234
+ }
235
+ async function hashFile(path) {
236
+ const hash = createHash("sha256");
237
+ const handle = await open(path, "r");
238
+ try {
239
+ const buffer = new Uint8Array(CHUNK);
240
+ for (;; ) {
241
+ const { bytesRead } = await handle.read(buffer, 0, CHUNK, null);
242
+ if (bytesRead === 0)
243
+ break;
244
+ hash.update(buffer.subarray(0, bytesRead));
245
+ }
246
+ } finally {
247
+ await handle.close();
248
+ }
249
+ return asId(hash.digest("hex"));
250
+ }
251
+ async function directoryVersion(path) {
252
+ return hashVersion((await readdir(path)).sort().join(`
253
+ `));
254
+ }
255
+ async function currentVersion(path) {
256
+ const stats = await stat(path).catch(missing);
257
+ if (stats === null)
258
+ return null;
259
+ return stats.isDirectory() ? directoryVersion(path) : hashFile(path).catch(missing);
260
+ }
261
+ async function readLink(path) {
262
+ return (await readlink(path)).split(sep).join("/");
263
+ }
264
+ async function resolveLink(path) {
265
+ const link = await lstat(path).catch(missing);
266
+ return link?.isSymbolicLink() === true ? realpath(path).catch(() => path) : path;
267
+ }
268
+ function refusedBatch() {
269
+ return {
270
+ put: () => refusedBatch(),
271
+ remove: () => refusedBatch(),
272
+ apply: async () => {
273
+ throw new SdkError("unavailable", "Core applies file batches; the local provider does not.");
274
+ }
275
+ };
276
+ }
277
+ async function collectFiles(root) {
278
+ const entries = [];
279
+ for await (const frame of walkTree2(root, { ignored: "exclude" }))
280
+ if (frame.kind === "entries") {
281
+ for (const entry of frame.entries)
282
+ if (entry.kind !== "directory")
283
+ entries.push({ path: entry.path, kind: entry.kind, size: entry.size, version: null });
284
+ }
285
+ return entries;
286
+ }
287
+ function rank(entries, query, limit) {
288
+ const needle = query.trim().toLowerCase();
289
+ if (needle === "")
290
+ return entries.slice(0, limit);
291
+ const scored = entries.flatMap((entry) => {
292
+ const path = entry.path.toLowerCase();
293
+ const name = path.slice(path.lastIndexOf("/") + 1);
294
+ const score = name === needle ? 0 : name.startsWith(needle) ? 1 : name.includes(needle) ? 2 : path.includes(needle) ? 3 : subsequence(path, needle) ? 4 : null;
295
+ return score === null ? [] : [{ entry, score }];
296
+ });
297
+ return scored.sort((left, right) => left.score - right.score || left.entry.path.length - right.entry.path.length || (left.entry.path < right.entry.path ? -1 : 1)).slice(0, limit).map(({ entry }) => entry);
298
+ }
299
+ function subsequence(text, needle) {
300
+ let at = 0;
301
+ for (const char of text) {
302
+ if (char === needle[at])
303
+ at += 1;
304
+ if (at === needle.length)
305
+ return true;
306
+ }
307
+ return false;
308
+ }
309
+ async function format(root, path, contents, formatter) {
310
+ const binary = formatter ?? await detectFormatter(root);
311
+ if (binary === null)
312
+ return { kind: "unavailable", reason: "No formatter is installed for this workspace." };
313
+ const name = basename(binary).replace(/\.(cmd|exe)$/i, "");
314
+ const args = name === "biome" ? ["format", `--stdin-file-path=${path}`] : name === "oxfmt" ? [`--stdin-filepath=${path}`] : ["--stdin-filepath", path];
315
+ let ran;
316
+ try {
317
+ ran = await run2(binary, args, { cwd: root, input: contents });
318
+ } catch (error) {
319
+ return { kind: "unavailable", reason: error instanceof Error ? error.message : String(error) };
320
+ }
321
+ if (ran.code !== 0)
322
+ return {
323
+ kind: "unavailable",
324
+ reason: `${name} could not format ${basename(path)}: ${ran.stderr.trim()}`
325
+ };
326
+ const formatted = ran.stdout.toString("utf8");
327
+ return formatted === contents ? { kind: "unchanged" } : { kind: "formatted", contents: formatted };
328
+ }
329
+ async function detectFormatter(root) {
330
+ for (const name of FORMATTERS) {
331
+ const found = await findExecutable2(name, [join(root, "node_modules", ".bin")]);
332
+ if (found !== null)
333
+ return found;
334
+ }
335
+ return null;
336
+ }
337
+ async function* search(root, input, drafts, ripgrep) {
338
+ const limit = Math.max(1, input.limit ?? SEARCH_DEFAULT);
339
+ if (input.query === "") {
340
+ yield { kind: "complete" };
341
+ return;
342
+ }
343
+ const binary = await findExecutable2(ripgrep ?? "rg");
344
+ const matches = binary === null ? scanText(root, input, drafts) : grep(binary, root, input, drafts);
345
+ let count = 0;
346
+ for await (const match of matches) {
347
+ if (count >= limit) {
348
+ yield { kind: "truncated", limit };
349
+ return;
350
+ }
351
+ count += 1;
352
+ yield match;
353
+ }
354
+ yield { kind: "complete" };
355
+ }
356
+ function matchFlags(input) {
357
+ const casing = input.caseSensitive === undefined ? "--smart-case" : input.caseSensitive ? "--case-sensitive" : "--ignore-case";
358
+ return [
359
+ "--json",
360
+ "--no-config",
361
+ "--no-messages",
362
+ casing,
363
+ ...input.regex === true ? [] : ["--fixed-strings"],
364
+ ...input.wholeWord === true ? ["--word-regexp"] : []
365
+ ];
366
+ }
367
+ function fileFlags(input) {
368
+ return [
369
+ "--no-config",
370
+ "--hidden",
371
+ "--no-require-git",
372
+ "--glob=!.git",
373
+ ...(input.include ?? []).map((glob) => `--glob=${glob}`),
374
+ ...(input.exclude ?? []).map((glob) => `--glob=!${glob}`)
375
+ ];
376
+ }
377
+ function rejectFailure(code, stderr) {
378
+ if (code === 2 && stderr.trim() !== "")
379
+ throw new SdkError("invalid", stderr.trim());
380
+ }
381
+ function ripgrepPath(path) {
382
+ return path.split(sep).join("/").replace(/^\.\//, "");
383
+ }
384
+ async function* grep(binary, root, input, drafts) {
385
+ if (drafts.size > 0) {
386
+ const listed = await run2(binary, ["--files", ...fileFlags(input), "."], { cwd: root });
387
+ rejectFailure(listed.code, listed.stderr);
388
+ const searched = new Set(listed.stdout.toString("utf8").split(`
389
+ `).map(ripgrepPath));
390
+ for (const [path, contents] of drafts) {
391
+ if (!searched.has(path))
392
+ continue;
393
+ const ran = await run2(binary, [...matchFlags(input), "--", input.query, "-"], {
394
+ cwd: root,
395
+ input: contents
396
+ });
397
+ rejectFailure(ran.code, ran.stderr);
398
+ for (const line of ran.stdout.toString("utf8").split(`
399
+ `)) {
400
+ const match = ripgrepMatch(line);
401
+ if (match !== null)
402
+ yield { ...match, path };
403
+ }
404
+ }
405
+ }
406
+ const child = spawn(binary, [...matchFlags(input), ...fileFlags(input), "--", input.query, "."], {
407
+ cwd: root,
408
+ stdio: ["ignore", "pipe", "pipe"],
409
+ windowsHide: true
410
+ });
411
+ let stderr = "";
412
+ child.stderr.setEncoding("utf8");
413
+ child.stderr.on("data", (chunk) => {
414
+ stderr += chunk;
415
+ });
416
+ const closed = new Promise((resolve) => child.on("close", resolve));
417
+ const lines = createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY });
418
+ try {
419
+ for await (const line of lines) {
420
+ const match = ripgrepMatch(line);
421
+ if (match !== null && !drafts.has(match.path))
422
+ yield match;
423
+ }
424
+ rejectFailure(await closed, stderr);
425
+ } finally {
426
+ lines.close();
427
+ child.kill();
428
+ await closed;
429
+ }
430
+ }
431
+ var RipgrepMatchSchema = Type.Object({
432
+ type: Type.Literal("match"),
433
+ data: Type.Object({
434
+ path: Type.Object({ text: Type.String() }),
435
+ lines: Type.Object({ text: Type.String() }),
436
+ line_number: Type.Number(),
437
+ submatches: Type.Optional(Type.Array(Type.Unknown()))
438
+ })
439
+ });
440
+ var SubmatchSchema = Type.Object({ start: Type.Number(), end: Type.Number() });
441
+ function ripgrepMatch(line) {
442
+ let record;
443
+ try {
444
+ record = JSON.parse(line);
445
+ } catch {
446
+ return null;
447
+ }
448
+ if (!Value.Check(RipgrepMatchSchema, record))
449
+ return null;
450
+ const { path, lines, line_number: number, submatches } = record.data;
451
+ const first = submatches?.[0];
452
+ const { start, end } = Value.Check(SubmatchSchema, first) ? first : { start: 0, end: 0 };
453
+ const text = lines.text.replace(/\r?\n$/, "");
454
+ const bytes = new TextEncoder().encode(text);
455
+ const decoder = new TextDecoder;
456
+ return {
457
+ kind: "match",
458
+ path: ripgrepPath(path.text),
459
+ line: number,
460
+ column: decoder.decode(bytes.subarray(0, start)).length + 1,
461
+ length: decoder.decode(bytes.subarray(start, end)).length,
462
+ text: text.slice(0, SEARCH_LINE)
463
+ };
464
+ }
465
+ function linePattern(input) {
466
+ const source = input.regex === true ? input.query : RegExp.escape(input.query);
467
+ const sensitive = input.caseSensitive ?? input.query !== input.query.toLowerCase();
468
+ try {
469
+ return new RegExp(input.wholeWord === true ? `\\b(?:${source})\\b` : source, sensitive ? "u" : "iu");
470
+ } catch (error) {
471
+ throw new SdkError("invalid", error instanceof Error ? error.message : String(error));
472
+ }
473
+ }
474
+ function passesFilters(path, input) {
475
+ const parts = path.split("/");
476
+ const prefixes = parts.map((_, index) => parts.slice(0, index + 1).join("/"));
477
+ const matches = (glob, target) => matchesGlob(target, glob) || !glob.includes("/") && matchesGlob(basename(target), glob);
478
+ const include = input.include ?? [];
479
+ return (include.length === 0 || include.some((glob) => matches(glob, path))) && !(input.exclude ?? []).some((glob) => prefixes.some((prefix) => matches(glob, prefix)));
480
+ }
481
+ async function* scanText(root, input, drafts) {
482
+ const pattern = linePattern(input);
483
+ for await (const frame of walkTree2(root, { ignored: "exclude" })) {
484
+ if (frame.kind !== "entries")
485
+ continue;
486
+ for (const entry of frame.entries) {
487
+ if (entry.kind !== "file" || !passesFilters(entry.path, input))
488
+ continue;
489
+ const text = drafts.get(entry.path) ?? await readSearchable(join(root, entry.path), entry.size);
490
+ if (text === null)
491
+ continue;
492
+ for (const [index, raw] of text.split(`
493
+ `).entries()) {
494
+ const line = raw.replace(/\r$/, "");
495
+ const found = pattern.exec(line);
496
+ if (found === null)
497
+ continue;
498
+ yield {
499
+ kind: "match",
500
+ path: entry.path,
501
+ line: index + 1,
502
+ column: found.index + 1,
503
+ length: found[0].length,
504
+ text: line.slice(0, SEARCH_LINE)
505
+ };
506
+ }
507
+ }
508
+ }
509
+ }
510
+ async function readSearchable(path, size) {
511
+ if ((size ?? 0) > TEXT_LIMIT2)
512
+ return null;
513
+ const bytes = await readFile(path).catch(() => null);
514
+ return bytes === null ? null : decodeText2(bytes);
515
+ }
516
+ function watchFiles(root, paths, signal) {
517
+ return feed2((sink) => {
518
+ const ignores = createIgnores2(root);
519
+ const known = new Map;
520
+ const started = Date.now();
521
+ const reads = serial();
522
+ const readEvent = async (path) => {
523
+ if (path.endsWith(".gitignore"))
524
+ ignores.forget(path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "");
525
+ if (await ignores.ignored(path, false))
526
+ return null;
527
+ const at = isAbsolute(path) ? path : join(root, path);
528
+ const stats = await lstat(at).catch(() => null);
529
+ if (stats?.isDirectory() === true)
530
+ return null;
531
+ const version = stats === null ? null : await currentVersion(at).catch(() => null);
532
+ const before = known.get(path);
533
+ known.set(path, version);
534
+ if (version === null)
535
+ return before === null ? null : { kind: "removed", path, version: null };
536
+ if (before === version)
537
+ return null;
538
+ const created = before === null || before === undefined && stats !== null && stats.birthtimeMs >= started - 1000;
539
+ return { kind: created ? "created" : "modified", path, version };
540
+ };
541
+ const listMoved = async (prefix, changed) => {
542
+ const inside = [...changed].flatMap((path) => path === "" ? [] : [`${prefix}/${path}`]);
543
+ if (!changed.has(""))
544
+ return inside;
545
+ const below = [...known.keys()].filter((path) => path.startsWith(`${prefix}/`));
546
+ for await (const frame of walkTree2(isAbsolute(prefix) ? prefix : join(root, prefix), {
547
+ ignored: "include"
548
+ }))
549
+ if (frame.kind === "entries") {
550
+ for (const entry of frame.entries)
551
+ if (entry.kind === "file")
552
+ below.push(`${prefix}/${entry.path}`);
553
+ }
554
+ return [prefix, ...below, ...inside];
555
+ };
556
+ const heard = (changed) => {
557
+ reads.run(async () => {
558
+ const events = [];
559
+ for (const path of await changed) {
560
+ if (path === "")
561
+ continue;
562
+ const event = await readEvent(path).catch(() => null);
563
+ if (event !== null)
564
+ events.push(event);
565
+ }
566
+ if (events.length > 0)
567
+ sink.push(events);
568
+ });
569
+ };
570
+ const watching = paths.length === 0 || paths.includes("") ? [watchTree2(root, { delay: WATCH_DELAY_MS, poll: WATCH_POLL_MS }, heard)] : paths.map((prefix) => watchPath2(isAbsolute(prefix) ? prefix : join(root, prefix), { delay: WATCH_DELAY_MS }, (changed) => heard(listMoved(prefix, changed))));
571
+ const dispose = () => {
572
+ for (const stop of watching)
573
+ stop();
574
+ };
575
+ const end = () => sink.end();
576
+ signal?.addEventListener("abort", end, { once: true });
577
+ if (signal?.aborted === true)
578
+ end();
579
+ return () => {
580
+ signal?.removeEventListener("abort", end);
581
+ dispose();
582
+ };
583
+ }, (waiting, next) => {
584
+ const merged = new Map(waiting.map((event) => [event.path, event]));
585
+ for (const event of next)
586
+ merged.set(event.path, event);
587
+ return [...merged.values()];
588
+ });
589
+ }
590
+
591
+ export { TEXT_LIMIT2, localFiles2 };