@ipab/cli 0.1.0-rc.0 → 0.1.0-rc.10

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 (285) hide show
  1. package/README.md +230 -7
  2. package/dist/app-authoring.d.ts +16 -2
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +151 -66
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -63
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -44
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-prebuild.d.ts +18 -0
  11. package/dist/app-prebuild.d.ts.map +1 -1
  12. package/dist/app-prebuild.js +46 -0
  13. package/dist/app-prebuild.js.map +1 -1
  14. package/dist/app-templates.d.ts +0 -1
  15. package/dist/app-templates.d.ts.map +1 -1
  16. package/dist/app-templates.js +15 -45
  17. package/dist/app-templates.js.map +1 -1
  18. package/dist/assembly.d.ts +7 -0
  19. package/dist/assembly.d.ts.map +1 -0
  20. package/dist/assembly.js +130 -0
  21. package/dist/assembly.js.map +1 -0
  22. package/dist/authoring.d.ts +8 -21
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +35 -54
  25. package/dist/authoring.js.map +1 -1
  26. package/dist/builtins/skill.ipab.car +0 -0
  27. package/dist/builtins/template.bundle-viewer.car +0 -0
  28. package/dist/builtins/template.check.car +0 -0
  29. package/dist/builtins/template.node.car +0 -0
  30. package/dist/builtins/template.web-app.car +0 -0
  31. package/dist/builtins.d.ts.map +1 -1
  32. package/dist/builtins.js +5 -32
  33. package/dist/builtins.js.map +1 -1
  34. package/dist/bundled-skills.d.ts +14 -0
  35. package/dist/bundled-skills.d.ts.map +1 -0
  36. package/dist/bundled-skills.js +34 -0
  37. package/dist/bundled-skills.js.map +1 -0
  38. package/dist/cli.d.ts +8 -2
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +2009 -308
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config-secret.d.ts +3 -0
  43. package/dist/config-secret.d.ts.map +1 -0
  44. package/dist/config-secret.js +12 -0
  45. package/dist/config-secret.js.map +1 -0
  46. package/dist/config.d.ts +9 -4
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +164 -23
  49. package/dist/config.js.map +1 -1
  50. package/dist/content-provider.d.ts +32 -0
  51. package/dist/content-provider.d.ts.map +1 -0
  52. package/dist/content-provider.js +222 -0
  53. package/dist/content-provider.js.map +1 -0
  54. package/dist/context-types.d.ts +12 -0
  55. package/dist/context-types.d.ts.map +1 -0
  56. package/dist/context-types.js +2 -0
  57. package/dist/context-types.js.map +1 -0
  58. package/dist/context.d.ts +26 -0
  59. package/dist/context.d.ts.map +1 -1
  60. package/dist/context.js +56 -2
  61. package/dist/context.js.map +1 -1
  62. package/dist/daemon-ui.d.ts +93 -0
  63. package/dist/daemon-ui.d.ts.map +1 -0
  64. package/dist/daemon-ui.js +713 -0
  65. package/dist/daemon-ui.js.map +1 -0
  66. package/dist/daemon.d.ts +21 -0
  67. package/dist/daemon.d.ts.map +1 -0
  68. package/dist/daemon.js +317 -0
  69. package/dist/daemon.js.map +1 -0
  70. package/dist/doctor.d.ts +32 -0
  71. package/dist/doctor.d.ts.map +1 -0
  72. package/dist/doctor.js +684 -0
  73. package/dist/doctor.js.map +1 -0
  74. package/dist/errors.d.ts +1 -8
  75. package/dist/errors.d.ts.map +1 -1
  76. package/dist/errors.js +1 -20
  77. package/dist/errors.js.map +1 -1
  78. package/dist/get.d.ts +3 -0
  79. package/dist/get.d.ts.map +1 -0
  80. package/dist/get.js +80 -0
  81. package/dist/get.js.map +1 -0
  82. package/dist/history.d.ts.map +1 -1
  83. package/dist/history.js +6 -14
  84. package/dist/history.js.map +1 -1
  85. package/dist/host-error.d.ts +9 -0
  86. package/dist/host-error.d.ts.map +1 -0
  87. package/dist/host-error.js +21 -0
  88. package/dist/host-error.js.map +1 -0
  89. package/dist/identity.d.ts +16 -0
  90. package/dist/identity.d.ts.map +1 -0
  91. package/dist/identity.js +119 -0
  92. package/dist/identity.js.map +1 -0
  93. package/dist/ipc.d.ts +5 -1
  94. package/dist/ipc.d.ts.map +1 -1
  95. package/dist/ipc.js +125 -4
  96. package/dist/ipc.js.map +1 -1
  97. package/dist/kubo-install.d.ts +26 -0
  98. package/dist/kubo-install.d.ts.map +1 -0
  99. package/dist/kubo-install.js +724 -0
  100. package/dist/kubo-install.js.map +1 -0
  101. package/dist/kubo-peering.d.ts +11 -0
  102. package/dist/kubo-peering.d.ts.map +1 -0
  103. package/dist/kubo-peering.js +93 -0
  104. package/dist/kubo-peering.js.map +1 -0
  105. package/dist/kubo-peers.d.ts +12 -0
  106. package/dist/kubo-peers.d.ts.map +1 -0
  107. package/dist/kubo-peers.js +119 -0
  108. package/dist/kubo-peers.js.map +1 -0
  109. package/dist/kubo-release.d.ts +22 -0
  110. package/dist/kubo-release.d.ts.map +1 -0
  111. package/dist/kubo-release.js +176 -0
  112. package/dist/kubo-release.js.map +1 -0
  113. package/dist/kubo-topology.d.ts +19 -0
  114. package/dist/kubo-topology.d.ts.map +1 -0
  115. package/dist/kubo-topology.js +113 -0
  116. package/dist/kubo-topology.js.map +1 -0
  117. package/dist/kubo.d.ts +85 -0
  118. package/dist/kubo.d.ts.map +1 -0
  119. package/dist/kubo.js +755 -0
  120. package/dist/kubo.js.map +1 -0
  121. package/dist/pins.d.ts +18 -20
  122. package/dist/pins.d.ts.map +1 -1
  123. package/dist/pins.js +146 -126
  124. package/dist/pins.js.map +1 -1
  125. package/dist/pivot-rpc.d.ts +62 -0
  126. package/dist/pivot-rpc.d.ts.map +1 -0
  127. package/dist/pivot-rpc.js +407 -0
  128. package/dist/pivot-rpc.js.map +1 -0
  129. package/dist/pivot-service.d.ts +16 -0
  130. package/dist/pivot-service.d.ts.map +1 -0
  131. package/dist/pivot-service.js +50 -0
  132. package/dist/pivot-service.js.map +1 -0
  133. package/dist/publish-source.d.ts +3 -0
  134. package/dist/publish-source.d.ts.map +1 -0
  135. package/dist/publish-source.js +85 -0
  136. package/dist/publish-source.js.map +1 -0
  137. package/dist/runtime.d.ts +2 -0
  138. package/dist/runtime.d.ts.map +1 -1
  139. package/dist/runtime.js +9 -4
  140. package/dist/runtime.js.map +1 -1
  141. package/dist/search-index.d.ts +64 -0
  142. package/dist/search-index.d.ts.map +1 -0
  143. package/dist/search-index.js +409 -0
  144. package/dist/search-index.js.map +1 -0
  145. package/dist/search-service.d.ts +23 -0
  146. package/dist/search-service.d.ts.map +1 -0
  147. package/dist/search-service.js +116 -0
  148. package/dist/search-service.js.map +1 -0
  149. package/dist/skill-definition.d.ts +6 -0
  150. package/dist/skill-definition.d.ts.map +1 -0
  151. package/dist/skill-definition.js +38 -0
  152. package/dist/skill-definition.js.map +1 -0
  153. package/dist/skill-source.d.ts +9 -0
  154. package/dist/skill-source.d.ts.map +1 -0
  155. package/dist/skill-source.js +24 -0
  156. package/dist/skill-source.js.map +1 -0
  157. package/dist/skills.d.ts +104 -0
  158. package/dist/skills.d.ts.map +1 -0
  159. package/dist/skills.js +894 -0
  160. package/dist/skills.js.map +1 -0
  161. package/dist/source-bundle.d.ts +3 -9
  162. package/dist/source-bundle.d.ts.map +1 -1
  163. package/dist/source-bundle.js +17 -13
  164. package/dist/source-bundle.js.map +1 -1
  165. package/dist/space-path.d.ts +3 -0
  166. package/dist/space-path.d.ts.map +1 -0
  167. package/dist/space-path.js +17 -0
  168. package/dist/space-path.js.map +1 -0
  169. package/dist/space.d.ts +16 -4
  170. package/dist/space.d.ts.map +1 -1
  171. package/dist/space.js +170 -24
  172. package/dist/space.js.map +1 -1
  173. package/dist/state-storage-windows.d.ts +2 -0
  174. package/dist/state-storage-windows.d.ts.map +1 -0
  175. package/dist/state-storage-windows.js +114 -0
  176. package/dist/state-storage-windows.js.map +1 -0
  177. package/dist/state-storage.d.ts +5 -0
  178. package/dist/state-storage.d.ts.map +1 -0
  179. package/dist/state-storage.js +333 -0
  180. package/dist/state-storage.js.map +1 -0
  181. package/dist/state.d.ts +128 -16
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +506 -94
  184. package/dist/state.js.map +1 -1
  185. package/dist/swarm-envelope.d.ts +57 -0
  186. package/dist/swarm-envelope.d.ts.map +1 -0
  187. package/dist/swarm-envelope.js +299 -0
  188. package/dist/swarm-envelope.js.map +1 -0
  189. package/dist/swarm-files.d.ts +6 -0
  190. package/dist/swarm-files.d.ts.map +1 -0
  191. package/dist/swarm-files.js +116 -0
  192. package/dist/swarm-files.js.map +1 -0
  193. package/dist/swarm-meta.d.ts +15 -0
  194. package/dist/swarm-meta.d.ts.map +1 -0
  195. package/dist/swarm-meta.js +68 -0
  196. package/dist/swarm-meta.js.map +1 -0
  197. package/dist/swarm-observations.d.ts +40 -0
  198. package/dist/swarm-observations.d.ts.map +1 -0
  199. package/dist/swarm-observations.js +271 -0
  200. package/dist/swarm-observations.js.map +1 -0
  201. package/dist/swarm.d.ts +469 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4708 -0
  204. package/dist/swarm.js.map +1 -0
  205. package/dist/template-definition.d.ts +45 -67
  206. package/dist/template-definition.d.ts.map +1 -1
  207. package/dist/template-definition.js +35 -49
  208. package/dist/template-definition.js.map +1 -1
  209. package/dist/template-paths.d.ts +7 -0
  210. package/dist/template-paths.d.ts.map +1 -0
  211. package/dist/template-paths.js +23 -0
  212. package/dist/template-paths.js.map +1 -0
  213. package/dist/template-presentation.d.ts +20 -0
  214. package/dist/template-presentation.d.ts.map +1 -0
  215. package/dist/template-presentation.js +133 -0
  216. package/dist/template-presentation.js.map +1 -0
  217. package/dist/template-source.d.ts +4 -1
  218. package/dist/template-source.d.ts.map +1 -1
  219. package/dist/template-source.js +11 -4
  220. package/dist/template-source.js.map +1 -1
  221. package/dist/templates.d.ts +11 -0
  222. package/dist/templates.d.ts.map +1 -0
  223. package/dist/templates.js +53 -0
  224. package/dist/templates.js.map +1 -0
  225. package/dist/unixfs-tree.d.ts +67 -0
  226. package/dist/unixfs-tree.d.ts.map +1 -0
  227. package/dist/unixfs-tree.js +329 -0
  228. package/dist/unixfs-tree.js.map +1 -0
  229. package/package.json +18 -11
  230. package/src/app-authoring.ts +254 -88
  231. package/src/app-definition.ts +33 -45
  232. package/src/app-prebuild.ts +61 -0
  233. package/src/app-templates.ts +28 -71
  234. package/src/assembly.ts +185 -0
  235. package/src/authoring.ts +63 -72
  236. package/src/builtins.ts +7 -38
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2500 -376
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +215 -26
  241. package/src/content-provider.ts +299 -0
  242. package/src/context-types.ts +11 -0
  243. package/src/context.ts +100 -2
  244. package/src/daemon-ui.ts +812 -0
  245. package/src/daemon.ts +386 -0
  246. package/src/doctor.ts +1082 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +90 -0
  249. package/src/history.ts +5 -15
  250. package/src/host-error.ts +26 -0
  251. package/src/identity.ts +175 -0
  252. package/src/ipc.ts +161 -4
  253. package/src/kubo-install.ts +936 -0
  254. package/src/kubo-peering.ts +126 -0
  255. package/src/kubo-peers.ts +144 -0
  256. package/src/kubo-release.ts +230 -0
  257. package/src/kubo-topology.ts +148 -0
  258. package/src/kubo.ts +1088 -0
  259. package/src/pins.ts +190 -142
  260. package/src/pivot-rpc.ts +601 -0
  261. package/src/pivot-service.ts +87 -0
  262. package/src/publish-source.ts +103 -0
  263. package/src/runtime.ts +16 -3
  264. package/src/search-index.ts +560 -0
  265. package/src/search-service.ts +152 -0
  266. package/src/skill-definition.ts +53 -0
  267. package/src/skill-source.ts +29 -0
  268. package/src/skills.ts +1236 -0
  269. package/src/source-bundle.ts +26 -14
  270. package/src/space-path.ts +30 -0
  271. package/src/space.ts +230 -42
  272. package/src/state-storage-windows.ts +134 -0
  273. package/src/state-storage.ts +378 -0
  274. package/src/state.ts +782 -116
  275. package/src/swarm-envelope.ts +461 -0
  276. package/src/swarm-files.ts +126 -0
  277. package/src/swarm-meta.ts +98 -0
  278. package/src/swarm-observations.ts +393 -0
  279. package/src/swarm.ts +7051 -0
  280. package/src/template-definition.ts +35 -49
  281. package/src/template-paths.ts +43 -0
  282. package/src/template-presentation.ts +151 -0
  283. package/src/template-source.ts +19 -5
  284. package/src/templates.ts +77 -0
  285. package/src/unixfs-tree.ts +401 -0
@@ -0,0 +1,560 @@
1
+ import * as dagPb from "@ipld/dag-pb";
2
+ import { CID } from "multiformats/cid";
3
+ import { openBundle } from "@ipab/bundle";
4
+ import type { IpfsStore } from "@ipab/ipfs-store";
5
+ import { HostError, object } from "./errors.js";
6
+ import {
7
+ decodeUnixfsDirectory,
8
+ type DecodedUnixfsDirectory,
9
+ } from "./unixfs-tree.js";
10
+ import type {
11
+ SearchEntryKind,
12
+ SearchFilterKind,
13
+ SearchIndexMatch,
14
+ SearchIndexRow,
15
+ State,
16
+ } from "./state.js";
17
+
18
+ export type {
19
+ SearchEntryKind,
20
+ SearchFilterKind,
21
+ SearchIndexMatch,
22
+ } from "./state.js";
23
+
24
+ export const DEFAULT_SEARCH_LIMIT = 20;
25
+ export const MAX_SEARCH_LIMIT = 100;
26
+ export const MAX_SEARCH_OFFSET = 1_000_000;
27
+
28
+ export interface SearchQueryParams {
29
+ q: string;
30
+ prefix?: string;
31
+ kind?: SearchFilterKind;
32
+ schemaCid?: string;
33
+ limit?: number;
34
+ offset?: number;
35
+ }
36
+
37
+ export interface ValidatedSearchParams {
38
+ q: string;
39
+ prefix?: string;
40
+ kind: SearchFilterKind;
41
+ schemaCid?: string;
42
+ limit: number;
43
+ offset: number;
44
+ }
45
+
46
+ export interface SearchApiResponse {
47
+ v: 1;
48
+ headCid: string;
49
+ indexedAt: string;
50
+ query: string;
51
+ offset: number;
52
+ limit: number;
53
+ total: number;
54
+ hasMore: boolean;
55
+ nextOffset: number | null;
56
+ matches: SearchIndexMatch[];
57
+ }
58
+
59
+ export interface IndexSwarmResult {
60
+ headCid: string;
61
+ indexedAt: string;
62
+ changed: boolean;
63
+ visitedDirs: number;
64
+ skippedSubtrees: number;
65
+ upserted: number;
66
+ deletedSubtrees: number;
67
+ }
68
+
69
+ function hasControlChars(value: string): boolean {
70
+ for (const char of value) {
71
+ const code = char.charCodeAt(0);
72
+ if (code < 32 || code === 127) return true;
73
+ }
74
+ return false;
75
+ }
76
+
77
+ export function validateSearchQuery(q: string): string {
78
+ if (!q || q.length > 256 || hasControlChars(q))
79
+ throw new HostError(
80
+ "Search query must be 1..256 characters without controls.",
81
+ );
82
+ return q;
83
+ }
84
+
85
+ export function validateSearchPrefix(prefix: string): string {
86
+ if (!prefix || prefix.length > 1024 || hasControlChars(prefix))
87
+ throw new HostError(
88
+ "Search prefix must be 1..1024 characters without controls.",
89
+ );
90
+ const segments = prefix.split("/");
91
+ if (
92
+ segments.some((segment) => !segment || segment === "." || segment === "..")
93
+ )
94
+ throw new HostError(
95
+ `Invalid search prefix "${prefix}": expected a canonical relative path.`,
96
+ );
97
+ return prefix;
98
+ }
99
+
100
+ export function validateSearchKind(kind: string): SearchFilterKind {
101
+ if (kind !== "all" && kind !== "bundle" && kind !== "dir" && kind !== "file")
102
+ throw new HostError(
103
+ `Invalid search kind "${kind}": expected one of all, bundle, dir, file.`,
104
+ );
105
+ return kind;
106
+ }
107
+
108
+ export function validateSearchSchemaCid(value: string): string {
109
+ try {
110
+ return CID.parse(value).toV1().toString();
111
+ } catch {
112
+ throw new HostError(`Invalid schemaCid "${value}": expected a valid CID.`);
113
+ }
114
+ }
115
+
116
+ function parseIntegerParam(
117
+ name: string,
118
+ value: string | number,
119
+ min: number,
120
+ max: number,
121
+ ): number {
122
+ const num =
123
+ typeof value === "number"
124
+ ? value
125
+ : /^\d+$/.test(value)
126
+ ? Number(value)
127
+ : Number.NaN;
128
+ if (!Number.isSafeInteger(num) || num < min || num > max)
129
+ throw new HostError(
130
+ `Invalid ${name}: expected an integer between ${min} and ${max}.`,
131
+ );
132
+ return num;
133
+ }
134
+
135
+ export function validateSearchParams(raw: {
136
+ q?: string | null;
137
+ prefix?: string | null;
138
+ kind?: string | null;
139
+ schemaCid?: string | null;
140
+ limit?: string | number | null;
141
+ offset?: string | number | null;
142
+ }): ValidatedSearchParams {
143
+ if (typeof raw.q !== "string")
144
+ throw new HostError(
145
+ "Search query must be 1..256 characters without controls.",
146
+ );
147
+ const q = validateSearchQuery(raw.q);
148
+ const prefix =
149
+ raw.prefix !== undefined && raw.prefix !== null && raw.prefix !== ""
150
+ ? validateSearchPrefix(raw.prefix)
151
+ : undefined;
152
+ const kind =
153
+ raw.kind !== undefined && raw.kind !== null && raw.kind !== ""
154
+ ? validateSearchKind(raw.kind)
155
+ : "all";
156
+ const schemaCid =
157
+ raw.schemaCid !== undefined &&
158
+ raw.schemaCid !== null &&
159
+ raw.schemaCid !== ""
160
+ ? validateSearchSchemaCid(raw.schemaCid)
161
+ : undefined;
162
+ const limit =
163
+ raw.limit !== undefined && raw.limit !== null && raw.limit !== ""
164
+ ? parseIntegerParam("limit", raw.limit, 1, MAX_SEARCH_LIMIT)
165
+ : DEFAULT_SEARCH_LIMIT;
166
+ const offset =
167
+ raw.offset !== undefined && raw.offset !== null && raw.offset !== ""
168
+ ? parseIntegerParam("offset", raw.offset, 0, MAX_SEARCH_OFFSET)
169
+ : 0;
170
+ return {
171
+ q,
172
+ ...(prefix !== undefined ? { prefix } : {}),
173
+ kind,
174
+ ...(schemaCid !== undefined ? { schemaCid } : {}),
175
+ limit,
176
+ offset,
177
+ };
178
+ }
179
+
180
+ export function parseSearchApiResponse(value: unknown): SearchApiResponse {
181
+ const data = object(value, "Pivot search response");
182
+ if ("partial" in data)
183
+ throw new HostError(
184
+ "Invalid Pivot search response: unexpected partial field.",
185
+ );
186
+ if (data.v !== 1)
187
+ throw new HostError("Unsupported Pivot search response version.");
188
+ if (typeof data.headCid !== "string")
189
+ throw new HostError("Invalid Pivot search response: missing headCid.");
190
+ let headCid: string;
191
+ try {
192
+ headCid = CID.parse(data.headCid).toV1().toString();
193
+ } catch {
194
+ throw new HostError("Invalid Pivot search response: malformed headCid.");
195
+ }
196
+ if (typeof data.indexedAt !== "string" || !data.indexedAt)
197
+ throw new HostError("Invalid Pivot search response: missing indexedAt.");
198
+ if (typeof data.query !== "string")
199
+ throw new HostError("Invalid Pivot search response: missing query.");
200
+ if (
201
+ typeof data.offset !== "number" ||
202
+ !Number.isSafeInteger(data.offset) ||
203
+ data.offset < 0
204
+ )
205
+ throw new HostError("Invalid Pivot search response: invalid offset.");
206
+ if (
207
+ typeof data.limit !== "number" ||
208
+ !Number.isSafeInteger(data.limit) ||
209
+ data.limit < 1 ||
210
+ data.limit > MAX_SEARCH_LIMIT
211
+ )
212
+ throw new HostError("Invalid Pivot search response: invalid limit.");
213
+ if (
214
+ typeof data.total !== "number" ||
215
+ !Number.isSafeInteger(data.total) ||
216
+ data.total < 0
217
+ )
218
+ throw new HostError("Invalid Pivot search response: invalid total.");
219
+ if (typeof data.hasMore !== "boolean")
220
+ throw new HostError("Invalid Pivot search response: invalid hasMore.");
221
+ if (
222
+ data.nextOffset !== null &&
223
+ (typeof data.nextOffset !== "number" ||
224
+ !Number.isSafeInteger(data.nextOffset) ||
225
+ data.nextOffset < 0)
226
+ )
227
+ throw new HostError("Invalid Pivot search response: invalid nextOffset.");
228
+ if (!Array.isArray(data.matches) || data.matches.length > MAX_SEARCH_LIMIT)
229
+ throw new HostError("Invalid Pivot search response: invalid matches.");
230
+ const matches: SearchIndexMatch[] = data.matches.map((entry: unknown) => {
231
+ const item = object(entry, "Pivot search match");
232
+ if (
233
+ typeof item.path !== "string" ||
234
+ !item.path ||
235
+ typeof item.cid !== "string"
236
+ )
237
+ throw new HostError("Invalid Pivot search match entry.");
238
+ let cid: string;
239
+ try {
240
+ cid = CID.parse(item.cid).toV1().toString();
241
+ } catch {
242
+ throw new HostError("Invalid Pivot search match CID.");
243
+ }
244
+ if (item.kind !== "bundle" && item.kind !== "dir" && item.kind !== "file")
245
+ throw new HostError("Invalid Pivot search match kind.");
246
+ const kind: SearchEntryKind = item.kind;
247
+ const match: SearchIndexMatch = { path: item.path, cid, kind };
248
+ if (item.bundle !== undefined) {
249
+ if (kind !== "bundle")
250
+ throw new HostError(
251
+ "Invalid Pivot search match: bundle metadata on non-bundle entry.",
252
+ );
253
+ const meta = object(item.bundle, "Pivot search bundle metadata");
254
+ if (
255
+ typeof meta.title !== "string" ||
256
+ typeof meta.description !== "string" ||
257
+ typeof meta.schemaCid !== "string"
258
+ )
259
+ throw new HostError("Invalid Pivot search bundle metadata.");
260
+ let schemaCid: string;
261
+ try {
262
+ schemaCid = CID.parse(meta.schemaCid).toV1().toString();
263
+ } catch {
264
+ throw new HostError("Invalid Pivot search bundle schemaCid.");
265
+ }
266
+ match.bundle = {
267
+ title: meta.title,
268
+ description: meta.description,
269
+ schemaCid,
270
+ };
271
+ }
272
+ return match;
273
+ });
274
+ return {
275
+ v: 1,
276
+ headCid,
277
+ indexedAt: data.indexedAt,
278
+ query: data.query,
279
+ offset: data.offset,
280
+ limit: data.limit,
281
+ total: data.total,
282
+ hasMore: data.hasMore,
283
+ nextOffset: data.nextOffset,
284
+ matches,
285
+ };
286
+ }
287
+
288
+ export function queryLocalSearchIndex(
289
+ state: State,
290
+ configUrl: string,
291
+ params: SearchQueryParams,
292
+ ): SearchApiResponse | null {
293
+ const validated = validateSearchParams(params);
294
+ const result = state.querySearchIndex(configUrl, validated);
295
+ if (!result) return null;
296
+ const hasMore = validated.offset + result.matches.length < result.total;
297
+ return {
298
+ v: 1,
299
+ headCid: result.headCid,
300
+ indexedAt: result.indexedAt,
301
+ query: validated.q,
302
+ offset: validated.offset,
303
+ limit: validated.limit,
304
+ total: result.total,
305
+ hasMore,
306
+ nextOffset: hasMore ? validated.offset + result.matches.length : null,
307
+ matches: result.matches,
308
+ };
309
+ }
310
+
311
+ export async function indexV7UnixfsSwarm(
312
+ state: State,
313
+ store: IpfsStore,
314
+ configUrl: string,
315
+ headCid: string,
316
+ options: {
317
+ skipRootFiles?: ReadonlySet<string>;
318
+ maxDepth?: number;
319
+ signal?: AbortSignal;
320
+ now?: () => string;
321
+ } = {},
322
+ ): Promise<IndexSwarmResult> {
323
+ const newRoot = CID.parse(headCid).toV1();
324
+ if (newRoot.code !== dagPb.code)
325
+ throw new HostError("Expected a v7 UnixFS dag-pb root CID for indexing.");
326
+ const canonicalHead = newRoot.toString();
327
+ const previous = state.searchIndexState(configUrl);
328
+ if (previous?.headCid === canonicalHead) {
329
+ return {
330
+ headCid: canonicalHead,
331
+ indexedAt: previous.indexedAt,
332
+ changed: false,
333
+ visitedDirs: 0,
334
+ skippedSubtrees: 0,
335
+ upserted: 0,
336
+ deletedSubtrees: 0,
337
+ };
338
+ }
339
+
340
+ const skipRoot = options.skipRootFiles ?? new Set<string>();
341
+ const maxDepth = options.maxDepth ?? 64;
342
+ const signal = options.signal;
343
+ const request = signal ? { signal } : {};
344
+
345
+ let oldRoot: CID | null = null;
346
+ let fullReset = false;
347
+ if (previous) {
348
+ try {
349
+ const parsedOld = CID.parse(previous.headCid).toV1();
350
+ if (parsedOld.code === dagPb.code) {
351
+ const oldBytes = await store.block.get(parsedOld.toString(), request);
352
+ decodeUnixfsDirectory(oldBytes);
353
+ oldRoot = parsedOld;
354
+ } else {
355
+ fullReset = true;
356
+ }
357
+ } catch {
358
+ signal?.throwIfAborted();
359
+ fullReset = true;
360
+ }
361
+ } else {
362
+ fullReset = true;
363
+ }
364
+
365
+ const upserts: SearchIndexRow[] = [];
366
+ const deleteSubtrees: string[] = [];
367
+ const deleteChildrenOnly: string[] = [];
368
+ let visitedDirs = 0;
369
+ let skippedSubtrees = 0;
370
+
371
+ const filterLinks = (
372
+ dir: DecodedUnixfsDirectory,
373
+ isRoot: boolean,
374
+ isBundleDir: boolean,
375
+ ): Map<string, dagPb.PBLink> => {
376
+ const out = new Map<string, dagPb.PBLink>();
377
+ for (const [name, link] of dir.links) {
378
+ if (isRoot && skipRoot.has(name)) continue;
379
+ if (
380
+ isBundleDir &&
381
+ (name === ".bundle.yaml" || name === ".bundle-type.yaml")
382
+ )
383
+ continue;
384
+ out.set(name, link);
385
+ }
386
+ return out;
387
+ };
388
+
389
+ const diffDirectory = async (
390
+ oldDirCid: CID | null,
391
+ newDirCid: CID,
392
+ currentPath: string,
393
+ depth: number,
394
+ prefetchedNewBytes?: Uint8Array,
395
+ ): Promise<void> => {
396
+ signal?.throwIfAborted();
397
+ if (depth > maxDepth)
398
+ throw new HostError(
399
+ `UnixFS tree exceeded maximum indexing depth (${maxDepth}) at "${currentPath}".`,
400
+ );
401
+ if (oldDirCid && oldDirCid.equals(newDirCid)) {
402
+ skippedSubtrees++;
403
+ return;
404
+ }
405
+ visitedDirs++;
406
+ const newBytes =
407
+ prefetchedNewBytes ??
408
+ (await store.block.get(newDirCid.toString(), request));
409
+ const newDir = decodeUnixfsDirectory(newBytes);
410
+
411
+ let oldDir: DecodedUnixfsDirectory | null = null;
412
+ if (oldDirCid && oldDirCid.code === dagPb.code) {
413
+ try {
414
+ const oldBytes = await store.block.get(oldDirCid.toString(), request);
415
+ oldDir = decodeUnixfsDirectory(oldBytes);
416
+ } catch {
417
+ signal?.throwIfAborted();
418
+ oldDir = null;
419
+ if (currentPath) deleteSubtrees.push(currentPath);
420
+ }
421
+ } else if (oldDirCid && currentPath) {
422
+ // Previously a file or non-directory; clean any stale rows under currentPath.
423
+ deleteSubtrees.push(currentPath);
424
+ }
425
+
426
+ const isRoot = currentPath === "";
427
+ let isBundleDir = false;
428
+ if (!isRoot) {
429
+ if (newDir.links.has(".bundle.yaml")) {
430
+ try {
431
+ const bundle = await openBundle(newDirCid, {
432
+ resolveCid: (cid, opts) =>
433
+ store.block.get(cid.toV1().toString(), opts),
434
+ shallow: true,
435
+ ...(signal ? { signal } : {}),
436
+ });
437
+ isBundleDir = true;
438
+ upserts.push({
439
+ path: currentPath,
440
+ cid: newDirCid.toString(),
441
+ kind: "bundle",
442
+ title: bundle.manifest.title,
443
+ description: bundle.manifest.description,
444
+ schemaCid: bundle.schemaKey,
445
+ });
446
+ } catch {
447
+ signal?.throwIfAborted();
448
+ upserts.push({
449
+ path: currentPath,
450
+ cid: newDirCid.toString(),
451
+ kind: "dir",
452
+ title: null,
453
+ description: null,
454
+ schemaCid: null,
455
+ });
456
+ }
457
+ } else {
458
+ upserts.push({
459
+ path: currentPath,
460
+ cid: newDirCid.toString(),
461
+ kind: "dir",
462
+ title: null,
463
+ description: null,
464
+ schemaCid: null,
465
+ });
466
+ }
467
+ }
468
+
469
+ const newLinks = filterLinks(newDir, isRoot, isBundleDir);
470
+ const oldLinks = oldDir
471
+ ? filterLinks(oldDir, isRoot, !isRoot && oldDir.links.has(".bundle.yaml"))
472
+ : null;
473
+
474
+ if (oldLinks) {
475
+ for (const name of oldLinks.keys()) {
476
+ if (!newLinks.has(name)) {
477
+ const removedPath = currentPath ? `${currentPath}/${name}` : name;
478
+ deleteSubtrees.push(removedPath);
479
+ }
480
+ }
481
+ }
482
+
483
+ const sortedNames = [...newLinks.keys()].sort((a, b) =>
484
+ a < b ? -1 : a > b ? 1 : 0,
485
+ );
486
+ for (const name of sortedNames) {
487
+ signal?.throwIfAborted();
488
+ const newChildCid = newLinks.get(name)!.Hash.toV1();
489
+ const oldChildCid = oldLinks?.get(name)?.Hash.toV1() ?? null;
490
+ const childPath = currentPath ? `${currentPath}/${name}` : name;
491
+
492
+ if (oldChildCid && oldChildCid.equals(newChildCid)) {
493
+ skippedSubtrees++;
494
+ continue;
495
+ }
496
+
497
+ if (newChildCid.code !== dagPb.code) {
498
+ if (oldChildCid) deleteChildrenOnly.push(childPath);
499
+ upserts.push({
500
+ path: childPath,
501
+ cid: newChildCid.toString(),
502
+ kind: "file",
503
+ title: null,
504
+ description: null,
505
+ schemaCid: null,
506
+ });
507
+ continue;
508
+ }
509
+
510
+ const childBytes = await store.block.get(newChildCid.toString(), request);
511
+ let isChildDir: boolean;
512
+ try {
513
+ decodeUnixfsDirectory(childBytes);
514
+ isChildDir = true;
515
+ } catch {
516
+ isChildDir = false;
517
+ }
518
+ if (isChildDir) {
519
+ await diffDirectory(
520
+ oldChildCid,
521
+ newChildCid,
522
+ childPath,
523
+ depth + 1,
524
+ childBytes,
525
+ );
526
+ } else {
527
+ if (oldChildCid) deleteChildrenOnly.push(childPath);
528
+ upserts.push({
529
+ path: childPath,
530
+ cid: newChildCid.toString(),
531
+ kind: "file",
532
+ title: null,
533
+ description: null,
534
+ schemaCid: null,
535
+ });
536
+ }
537
+ }
538
+ };
539
+
540
+ await diffDirectory(oldRoot, newRoot, "", 0);
541
+ const indexedAt = (options.now ?? (() => new Date().toISOString()))();
542
+ state.applySearchIndexDelta(configUrl, {
543
+ headCid: canonicalHead,
544
+ indexedAt,
545
+ fullReset,
546
+ deleteSubtrees,
547
+ deleteChildrenOnly,
548
+ upserts,
549
+ });
550
+
551
+ return {
552
+ headCid: canonicalHead,
553
+ indexedAt,
554
+ changed: true,
555
+ visitedDirs,
556
+ skippedSubtrees,
557
+ upserted: upserts.length,
558
+ deletedSubtrees: deleteSubtrees.length,
559
+ };
560
+ }
@@ -0,0 +1,152 @@
1
+ import { HostError } from "./errors.js";
2
+ import { bytes } from "./space.js";
3
+ import type { KuboNode, p2pForward } from "./kubo.js";
4
+ import type { NetworkingSnapshot } from "./swarm-observations.js";
5
+ import {
6
+ PIVOT_PROTOCOL,
7
+ startPivotHttpServer,
8
+ withPivotP2pForward,
9
+ type PivotServer,
10
+ } from "./pivot-rpc.js";
11
+ import {
12
+ parseSearchApiResponse,
13
+ validateSearchParams,
14
+ type SearchApiResponse,
15
+ type SearchQueryParams,
16
+ type ValidatedSearchParams,
17
+ } from "./search-index.js";
18
+
19
+ export const SEARCH_PROTOCOL = PIVOT_PROTOCOL;
20
+
21
+ const MAX_SEARCH_RESPONSE_BYTES = 2 * 1024 * 1024;
22
+
23
+ export type SearchServerHandle = PivotServer;
24
+
25
+ export async function startSearchServer(options: {
26
+ query: (params: ValidatedSearchParams) => SearchApiResponse | null;
27
+ diagnostic?: (text: string) => void;
28
+ }): Promise<SearchServerHandle> {
29
+ return startPivotHttpServer({
30
+ search: options.query,
31
+ ...(options.diagnostic ? { diagnostic: options.diagnostic } : {}),
32
+ });
33
+ }
34
+
35
+ export function buildSearchQueryString(params: ValidatedSearchParams): string {
36
+ const qs = new URLSearchParams();
37
+ qs.set("q", params.q);
38
+ if (params.prefix !== undefined) qs.set("prefix", params.prefix);
39
+ if (params.kind !== "all") qs.set("kind", params.kind);
40
+ if (params.schemaCid !== undefined) qs.set("schemaCid", params.schemaCid);
41
+ qs.set("limit", String(params.limit));
42
+ qs.set("offset", String(params.offset));
43
+ return qs.toString();
44
+ }
45
+
46
+ export async function queryRemotePivotSearch(options: {
47
+ node: KuboNode;
48
+ pivotPeerId: string;
49
+ pivotAddresses?: readonly string[];
50
+ params: SearchQueryParams;
51
+ fetcher?: typeof fetch;
52
+ signal?: AbortSignal;
53
+ timeoutMs?: number;
54
+ p2pForwardFn?: typeof p2pForward;
55
+ }): Promise<SearchApiResponse> {
56
+ const validated = validateSearchParams(options.params);
57
+ const fetcher = options.fetcher ?? fetch;
58
+ const timeoutMs = options.timeoutMs ?? 10_000;
59
+ return withPivotP2pForward(
60
+ {
61
+ node: options.node,
62
+ pivotPeerId: options.pivotPeerId,
63
+ ...(options.pivotAddresses
64
+ ? { pivotAddresses: options.pivotAddresses }
65
+ : {}),
66
+ ...(options.signal ? { signal: options.signal } : {}),
67
+ fetcher,
68
+ ...(options.p2pForwardFn ? { p2pForwardFn: options.p2pForwardFn } : {}),
69
+ },
70
+ async ({ host, port }) => {
71
+ const qs = buildSearchQueryString(validated);
72
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
73
+ const combinedSignal = options.signal
74
+ ? AbortSignal.any([options.signal, timeoutSignal])
75
+ : timeoutSignal;
76
+ const response = await fetcher(`http://${host}:${port}/v1/search?${qs}`, {
77
+ method: "GET",
78
+ redirect: "error",
79
+ cache: "no-store",
80
+ signal: combinedSignal,
81
+ });
82
+ const text = response.body
83
+ ? new TextDecoder("utf-8", { fatal: true }).decode(
84
+ await bytes(response.body, MAX_SEARCH_RESPONSE_BYTES),
85
+ )
86
+ : "";
87
+ if (!response.ok) {
88
+ let detail = `HTTP ${response.status}`;
89
+ try {
90
+ const parsed = JSON.parse(text) as { error?: unknown };
91
+ if (typeof parsed.error === "string" && parsed.error)
92
+ detail = `${detail}: ${parsed.error}`;
93
+ else if (
94
+ parsed.error &&
95
+ typeof parsed.error === "object" &&
96
+ "message" in parsed.error &&
97
+ typeof parsed.error.message === "string"
98
+ )
99
+ detail = `${detail}: ${parsed.error.message}`;
100
+ } catch {
101
+ // Ignore non-JSON error body.
102
+ }
103
+ throw new HostError(
104
+ `Pivot ${options.pivotPeerId} search failed (${detail}).`,
105
+ );
106
+ }
107
+ let json: unknown;
108
+ try {
109
+ json = JSON.parse(text) as unknown;
110
+ } catch {
111
+ throw new HostError(
112
+ `Pivot ${options.pivotPeerId} returned invalid JSON for search.`,
113
+ );
114
+ }
115
+ return parseSearchApiResponse(json);
116
+ },
117
+ );
118
+ }
119
+
120
+ export function rankPivotCandidates(
121
+ candidates: readonly string[],
122
+ snapshot?: NetworkingSnapshot | null,
123
+ now = Date.now(),
124
+ ): string[] {
125
+ const unique = [...new Set(candidates)];
126
+ if (!snapshot) return unique.sort();
127
+ const connByPeer = new Map<string, "direct" | "relay">();
128
+ for (const conn of snapshot.connections?.peers ?? []) {
129
+ const existing = connByPeer.get(conn.peerId);
130
+ if (existing !== "direct") connByPeer.set(conn.peerId, conn.transport);
131
+ }
132
+ const pivotByPeer = new Map(
133
+ snapshot.pivots.map((pivot) => [pivot.peerId, pivot]),
134
+ );
135
+ const score = (peerId: string): [number, number, string] => {
136
+ const conn = connByPeer.get(peerId);
137
+ const obs = pivotByPeer.get(peerId);
138
+ const cooling = obs !== undefined && obs.retryAt > now;
139
+ if (conn === "direct" && !cooling) return [0, 0, peerId];
140
+ if (conn === "relay" && !cooling) return [1, 0, peerId];
141
+ if (obs?.selected && !cooling) return [2, obs.failures, peerId];
142
+ if (!cooling) return [3, obs?.failures ?? 0, peerId];
143
+ return [4, obs.retryAt, peerId];
144
+ };
145
+ return unique.sort((a, b) => {
146
+ const sa = score(a);
147
+ const sb = score(b);
148
+ if (sa[0] !== sb[0]) return sa[0] - sb[0];
149
+ if (sa[1] !== sb[1]) return sa[1] - sb[1];
150
+ return sa[2] < sb[2] ? -1 : sa[2] > sb[2] ? 1 : 0;
151
+ });
152
+ }