@sixb/server 0.0.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 (216) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -0
  3. package/dist/auth/access-token-boundary.d.ts +23 -0
  4. package/dist/auth/access-token-boundary.d.ts.map +1 -0
  5. package/dist/auth/application-access.d.ts +4 -0
  6. package/dist/auth/application-access.d.ts.map +1 -0
  7. package/dist/auth/browser-origin.d.ts +62 -0
  8. package/dist/auth/browser-origin.d.ts.map +1 -0
  9. package/dist/auth/csrf.d.ts +2 -0
  10. package/dist/auth/csrf.d.ts.map +1 -0
  11. package/dist/auth/guard.d.ts +35 -0
  12. package/dist/auth/guard.d.ts.map +1 -0
  13. package/dist/auth/public-routes.d.ts +8 -0
  14. package/dist/auth/public-routes.d.ts.map +1 -0
  15. package/dist/auth/responses.d.ts +11 -0
  16. package/dist/auth/responses.d.ts.map +1 -0
  17. package/dist/auth/return-to.d.ts +3 -0
  18. package/dist/auth/return-to.d.ts.map +1 -0
  19. package/dist/auth/scope.d.ts +43 -0
  20. package/dist/auth/scope.d.ts.map +1 -0
  21. package/dist/auth/session-activity.d.ts +4 -0
  22. package/dist/auth/session-activity.d.ts.map +1 -0
  23. package/dist/auth/session-cookies.d.ts +12 -0
  24. package/dist/auth/session-cookies.d.ts.map +1 -0
  25. package/dist/files/content.d.ts +141 -0
  26. package/dist/files/content.d.ts.map +1 -0
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +11522 -0
  30. package/dist/index.js.map +78 -0
  31. package/dist/openapi/security.d.ts +26 -0
  32. package/dist/openapi/security.d.ts.map +1 -0
  33. package/dist/openapi/tags.d.ts +151 -0
  34. package/dist/openapi/tags.d.ts.map +1 -0
  35. package/dist/registerRoutes.d.ts +31 -0
  36. package/dist/registerRoutes.d.ts.map +1 -0
  37. package/dist/routes/action-runs.d.ts +244 -0
  38. package/dist/routes/action-runs.d.ts.map +1 -0
  39. package/dist/routes/actions.d.ts +183 -0
  40. package/dist/routes/actions.d.ts.map +1 -0
  41. package/dist/routes/agent-api-gateway.d.ts +4 -0
  42. package/dist/routes/agent-api-gateway.d.ts.map +1 -0
  43. package/dist/routes/agents.d.ts +1061 -0
  44. package/dist/routes/agents.d.ts.map +1 -0
  45. package/dist/routes/auth.d.ts +1366 -0
  46. package/dist/routes/auth.d.ts.map +1 -0
  47. package/dist/routes/connectors.d.ts +108 -0
  48. package/dist/routes/connectors.d.ts.map +1 -0
  49. package/dist/routes/datasets.d.ts +339 -0
  50. package/dist/routes/datasets.d.ts.map +1 -0
  51. package/dist/routes/events.d.ts +116 -0
  52. package/dist/routes/events.d.ts.map +1 -0
  53. package/dist/routes/files.d.ts +340 -0
  54. package/dist/routes/files.d.ts.map +1 -0
  55. package/dist/routes/links.d.ts +175 -0
  56. package/dist/routes/links.d.ts.map +1 -0
  57. package/dist/routes/logs.d.ts +88 -0
  58. package/dist/routes/logs.d.ts.map +1 -0
  59. package/dist/routes/objects.d.ts +450 -0
  60. package/dist/routes/objects.d.ts.map +1 -0
  61. package/dist/routes/ontology.d.ts +240 -0
  62. package/dist/routes/ontology.d.ts.map +1 -0
  63. package/dist/routes/pipelines.d.ts +399 -0
  64. package/dist/routes/pipelines.d.ts.map +1 -0
  65. package/dist/routes/project.d.ts +56 -0
  66. package/dist/routes/project.d.ts.map +1 -0
  67. package/dist/routes/projections.d.ts +916 -0
  68. package/dist/routes/projections.d.ts.map +1 -0
  69. package/dist/routes/rules.d.ts +165 -0
  70. package/dist/routes/rules.d.ts.map +1 -0
  71. package/dist/routes/status.d.ts +81 -0
  72. package/dist/routes/status.d.ts.map +1 -0
  73. package/dist/routes/syncs.d.ts +294 -0
  74. package/dist/routes/syncs.d.ts.map +1 -0
  75. package/dist/routes/telemetry.d.ts +241 -0
  76. package/dist/routes/telemetry.d.ts.map +1 -0
  77. package/dist/routes/webhook-runs.d.ts +89 -0
  78. package/dist/routes/webhook-runs.d.ts.map +1 -0
  79. package/dist/routes/webhooks.d.ts +60 -0
  80. package/dist/routes/webhooks.d.ts.map +1 -0
  81. package/dist/routes/workflows.d.ts +973 -0
  82. package/dist/routes/workflows.d.ts.map +1 -0
  83. package/dist/routes/ws/agents.d.ts +99 -0
  84. package/dist/routes/ws/agents.d.ts.map +1 -0
  85. package/dist/routes/ws/events.d.ts +89 -0
  86. package/dist/routes/ws/events.d.ts.map +1 -0
  87. package/dist/routes/ws/index.d.ts +31 -0
  88. package/dist/routes/ws/index.d.ts.map +1 -0
  89. package/dist/routes/ws/log-subscription-hub.d.ts +47 -0
  90. package/dist/routes/ws/log-subscription-hub.d.ts.map +1 -0
  91. package/dist/routes/ws/logs.d.ts +110 -0
  92. package/dist/routes/ws/logs.d.ts.map +1 -0
  93. package/dist/schemas/actions.d.ts +644 -0
  94. package/dist/schemas/actions.d.ts.map +1 -0
  95. package/dist/schemas/agents.d.ts +3157 -0
  96. package/dist/schemas/agents.d.ts.map +1 -0
  97. package/dist/schemas/auth.d.ts +2023 -0
  98. package/dist/schemas/auth.d.ts.map +1 -0
  99. package/dist/schemas/common.d.ts +30 -0
  100. package/dist/schemas/common.d.ts.map +1 -0
  101. package/dist/schemas/connectors.d.ts +82 -0
  102. package/dist/schemas/connectors.d.ts.map +1 -0
  103. package/dist/schemas/datasets.d.ts +744 -0
  104. package/dist/schemas/datasets.d.ts.map +1 -0
  105. package/dist/schemas/event-payloads.d.ts +477 -0
  106. package/dist/schemas/event-payloads.d.ts.map +1 -0
  107. package/dist/schemas/events.d.ts +665 -0
  108. package/dist/schemas/events.d.ts.map +1 -0
  109. package/dist/schemas/files.d.ts +241 -0
  110. package/dist/schemas/files.d.ts.map +1 -0
  111. package/dist/schemas/links.d.ts +90 -0
  112. package/dist/schemas/links.d.ts.map +1 -0
  113. package/dist/schemas/logs.d.ts +231 -0
  114. package/dist/schemas/logs.d.ts.map +1 -0
  115. package/dist/schemas/objects.d.ts +288 -0
  116. package/dist/schemas/objects.d.ts.map +1 -0
  117. package/dist/schemas/ontology.d.ts +778 -0
  118. package/dist/schemas/ontology.d.ts.map +1 -0
  119. package/dist/schemas/pipelines.d.ts +1373 -0
  120. package/dist/schemas/pipelines.d.ts.map +1 -0
  121. package/dist/schemas/project.d.ts +9 -0
  122. package/dist/schemas/project.d.ts.map +1 -0
  123. package/dist/schemas/projections.d.ts +6992 -0
  124. package/dist/schemas/projections.d.ts.map +1 -0
  125. package/dist/schemas/rules.d.ts +204 -0
  126. package/dist/schemas/rules.d.ts.map +1 -0
  127. package/dist/schemas/status.d.ts +189 -0
  128. package/dist/schemas/status.d.ts.map +1 -0
  129. package/dist/schemas/syncs.d.ts +538 -0
  130. package/dist/schemas/syncs.d.ts.map +1 -0
  131. package/dist/schemas/telemetry.d.ts +265 -0
  132. package/dist/schemas/telemetry.d.ts.map +1 -0
  133. package/dist/schemas/webhook-runs.d.ts +169 -0
  134. package/dist/schemas/webhook-runs.d.ts.map +1 -0
  135. package/dist/schemas/workflows.d.ts +1720 -0
  136. package/dist/schemas/workflows.d.ts.map +1 -0
  137. package/dist/server.d.ts +64 -0
  138. package/dist/server.d.ts.map +1 -0
  139. package/dist/tsconfig.json +5 -0
  140. package/dist/utils/http.d.ts +23 -0
  141. package/dist/utils/http.d.ts.map +1 -0
  142. package/dist/utils/request-body.d.ts +15 -0
  143. package/dist/utils/request-body.d.ts.map +1 -0
  144. package/dist/utils/ws.d.ts +10 -0
  145. package/dist/utils/ws.d.ts.map +1 -0
  146. package/package.json +68 -0
  147. package/src/auth/access-token-boundary.ts +68 -0
  148. package/src/auth/application-access.ts +16 -0
  149. package/src/auth/browser-origin.ts +367 -0
  150. package/src/auth/csrf.ts +1 -0
  151. package/src/auth/guard.ts +169 -0
  152. package/src/auth/public-routes.ts +87 -0
  153. package/src/auth/responses.ts +54 -0
  154. package/src/auth/return-to.ts +21 -0
  155. package/src/auth/scope.ts +64 -0
  156. package/src/auth/session-activity.ts +19 -0
  157. package/src/auth/session-cookies.ts +43 -0
  158. package/src/files/content.ts +419 -0
  159. package/src/index.ts +2 -0
  160. package/src/openapi/security.ts +37 -0
  161. package/src/openapi/tags.ts +151 -0
  162. package/src/registerRoutes.ts +49 -0
  163. package/src/routes/action-runs.ts +238 -0
  164. package/src/routes/actions.ts +126 -0
  165. package/src/routes/agent-api-gateway.ts +260 -0
  166. package/src/routes/agents.ts +943 -0
  167. package/src/routes/auth.ts +2233 -0
  168. package/src/routes/connectors.ts +69 -0
  169. package/src/routes/datasets.ts +402 -0
  170. package/src/routes/events.ts +55 -0
  171. package/src/routes/files.ts +675 -0
  172. package/src/routes/links.ts +143 -0
  173. package/src/routes/logs.ts +65 -0
  174. package/src/routes/objects.ts +838 -0
  175. package/src/routes/ontology.ts +138 -0
  176. package/src/routes/pipelines.ts +332 -0
  177. package/src/routes/project.ts +16 -0
  178. package/src/routes/projections.ts +251 -0
  179. package/src/routes/rules.ts +124 -0
  180. package/src/routes/status.ts +53 -0
  181. package/src/routes/syncs.ts +243 -0
  182. package/src/routes/telemetry.ts +207 -0
  183. package/src/routes/webhook-runs.ts +81 -0
  184. package/src/routes/webhooks.ts +508 -0
  185. package/src/routes/workflows.ts +1333 -0
  186. package/src/routes/ws/agents.ts +301 -0
  187. package/src/routes/ws/events.ts +278 -0
  188. package/src/routes/ws/index.ts +12 -0
  189. package/src/routes/ws/log-subscription-hub.ts +375 -0
  190. package/src/routes/ws/logs.ts +117 -0
  191. package/src/schemas/actions.ts +123 -0
  192. package/src/schemas/agents.ts +293 -0
  193. package/src/schemas/auth.ts +317 -0
  194. package/src/schemas/common.ts +60 -0
  195. package/src/schemas/connectors.ts +21 -0
  196. package/src/schemas/datasets.ts +107 -0
  197. package/src/schemas/event-payloads.ts +79 -0
  198. package/src/schemas/events.ts +117 -0
  199. package/src/schemas/files.ts +82 -0
  200. package/src/schemas/links.ts +38 -0
  201. package/src/schemas/logs.ts +76 -0
  202. package/src/schemas/objects.ts +759 -0
  203. package/src/schemas/ontology.ts +77 -0
  204. package/src/schemas/pipelines.ts +150 -0
  205. package/src/schemas/project.ts +5 -0
  206. package/src/schemas/projections.ts +144 -0
  207. package/src/schemas/rules.ts +98 -0
  208. package/src/schemas/status.ts +51 -0
  209. package/src/schemas/syncs.ts +83 -0
  210. package/src/schemas/telemetry.ts +59 -0
  211. package/src/schemas/webhook-runs.ts +40 -0
  212. package/src/schemas/workflows.ts +229 -0
  213. package/src/server.ts +383 -0
  214. package/src/utils/http.ts +108 -0
  215. package/src/utils/request-body.ts +62 -0
  216. package/src/utils/ws.ts +59 -0
@@ -0,0 +1,838 @@
1
+ import {
2
+ AuthorizationError,
3
+ isAllowed,
4
+ type ObjectQuery,
5
+ ObjectQueryExecutionError,
6
+ ObjectQueryPlanningError,
7
+ ObjectQueryValidationError,
8
+ type ObjectRef,
9
+ type OntologySource,
10
+ type Sixb,
11
+ } from "@sixb/core"
12
+ import {
13
+ countObjects,
14
+ executeObjectQuery,
15
+ existsObjects,
16
+ facetObjects,
17
+ } from "@sixb/core/internal/query"
18
+ import type {
19
+ ExpandedLinkValue,
20
+ ExpandedObjectRow,
21
+ ObjectRow,
22
+ ObjectRowLinks,
23
+ } from "@sixb/core/storage"
24
+ import type { Elysia } from "elysia"
25
+ import { ZodError, z } from "zod"
26
+ import { bearerSecurityRequirement } from "../auth/access-token-boundary"
27
+ import { type RequestAuthState, requestAuthState } from "../auth/scope"
28
+ import {
29
+ createContextualFileContentResponse,
30
+ fileContentGetResponses,
31
+ fileContentHeadResponses,
32
+ } from "../files/content"
33
+ import { OPENAPI_TAGS } from "../openapi/tags"
34
+ import { ErrorResponseSchema } from "../schemas/common"
35
+ import { FileContentQuerySchema } from "../schemas/files"
36
+ import {
37
+ ObjectListResponseSchema,
38
+ ObjectParamsSchema,
39
+ ObjectQueryCountRequestSchema,
40
+ ObjectQueryExistsRequestSchema,
41
+ ObjectQueryFacetsRequestSchema,
42
+ ObjectQueryRequestSchema,
43
+ ObjectSearchQuerySchema,
44
+ ObjectSearchResponseSchema,
45
+ ObjectsQuerySchema,
46
+ TwinObjectSchema,
47
+ UpsertObjectBodySchema,
48
+ } from "../schemas/objects"
49
+ import { handleRouteError, parseOptionalInt, toIsoString } from "../utils/http"
50
+
51
+ const ObjectFileContentQuerySchema = FileContentQuerySchema.extend({
52
+ path: z
53
+ .string()
54
+ .min(1)
55
+ .regex(/^\/properties(?:\/|$)/, "Object file content paths must start with /properties/"),
56
+ })
57
+
58
+ function serializeObject(row: {
59
+ primaryId: string
60
+ objectTypeId: string
61
+ properties: Record<string, unknown>
62
+ createdAt: Date
63
+ updatedAt: Date
64
+ }) {
65
+ return {
66
+ primaryId: row.primaryId,
67
+ objectTypeId: row.objectTypeId,
68
+ properties: row.properties,
69
+ createdAt: toIsoString(row.createdAt),
70
+ updatedAt: toIsoString(row.updatedAt),
71
+ }
72
+ }
73
+
74
+ type SerializedObject = ReturnType<typeof serializeObject>
75
+ type SerializedLinkValue = SerializedExpandedObject | SerializedExpandedObject[] | null
76
+ type SerializedExpandedObject = SerializedObject & {
77
+ links?: Record<string, SerializedLinkValue>
78
+ linkProperties?: Record<string, unknown>
79
+ }
80
+
81
+ /**
82
+ * Serialize a query row together with any `links` attached by an `expand` node.
83
+ * Recurses through nested expansions; `linkProperties` carries edge metadata on
84
+ * an expanded child. Only the query route hydrates links, so the plain list and
85
+ * identity routes keep using `serializeObject`.
86
+ */
87
+ function serializeExpandedObject(row: ExpandedObjectRow): SerializedExpandedObject {
88
+ const serialized: SerializedExpandedObject = serializeObject(row)
89
+ if (row.links) serialized.links = serializeLinks(row.links)
90
+ if (row.linkProperties !== undefined) serialized.linkProperties = row.linkProperties
91
+ return serialized
92
+ }
93
+
94
+ function serializeLinks(links: ObjectRowLinks): Record<string, SerializedLinkValue> {
95
+ const result: Record<string, SerializedLinkValue> = {}
96
+ for (const [linkId, value] of Object.entries(links)) {
97
+ result[linkId] = serializeLinkValue(value)
98
+ }
99
+ return result
100
+ }
101
+
102
+ function serializeLinkValue(value: ExpandedLinkValue): SerializedLinkValue {
103
+ if (value === null) return null
104
+ if (Array.isArray(value)) return value.map(serializeExpandedObject)
105
+ // Array.isArray does not narrow a readonly[] away, so assert the scalar case.
106
+ return serializeExpandedObject(value as ExpandedObjectRow)
107
+ }
108
+
109
+ function serializePlan(plan: Awaited<ReturnType<typeof executeObjectQuery>>["plan"]) {
110
+ return {
111
+ mode: plan.mode,
112
+ providerIssues: plan.providerIssues,
113
+ fallbackIssues: plan.fallbackIssues,
114
+ issues: plan.issues,
115
+ fallback: plan.fallback,
116
+ }
117
+ }
118
+
119
+ function handleObjectQueryError(error: unknown, set: { status?: number | string }) {
120
+ if (error instanceof AuthorizationError) {
121
+ set.status = 403
122
+ return { error: error.message }
123
+ }
124
+
125
+ if (error instanceof ZodError) {
126
+ set.status = 400
127
+ return {
128
+ error: "Invalid object query request",
129
+ issues: error.issues.map((issue) => ({
130
+ path: formatZodIssuePath(issue.path),
131
+ code: issue.code,
132
+ message: issue.message,
133
+ })),
134
+ }
135
+ }
136
+
137
+ if (error instanceof ObjectQueryValidationError || error instanceof ObjectQueryPlanningError) {
138
+ set.status = 400
139
+ return {
140
+ error: error.message,
141
+ issues: error.issues,
142
+ }
143
+ }
144
+
145
+ if (error instanceof ObjectQueryExecutionError) {
146
+ set.status = 400
147
+ return {
148
+ error: error.message,
149
+ issues: [
150
+ {
151
+ path: error.path ?? "$",
152
+ code: error.code,
153
+ message: error.message,
154
+ },
155
+ ],
156
+ }
157
+ }
158
+
159
+ set.status = 500
160
+ return { error: error instanceof Error ? error.message : String(error) }
161
+ }
162
+
163
+ function formatZodIssuePath(path: readonly (string | number)[]): string {
164
+ if (path.length === 0) return "$"
165
+ return path.reduce<string>((formatted, segment) => {
166
+ if (typeof segment === "number") return `${formatted}[${segment}]`
167
+ return /^[A-Za-z_$][\w$]*$/.test(segment)
168
+ ? `${formatted}.${segment}`
169
+ : `${formatted}[${JSON.stringify(segment)}]`
170
+ }, "$")
171
+ }
172
+
173
+ async function getObjectRow(
174
+ sixb: Sixb<readonly OntologySource[]>,
175
+ scoped: ReturnType<typeof requestAuthState>["scoped"],
176
+ params: { objectTypeId: string; objectId: string }
177
+ ) {
178
+ if (scoped) {
179
+ return scoped.getObject(params.objectTypeId, params.objectId)
180
+ }
181
+
182
+ return sixb.storage.objects.getByPrimaryId({
183
+ projectId: sixb.id,
184
+ objectTypeId: params.objectTypeId,
185
+ primaryId: params.objectId,
186
+ })
187
+ }
188
+
189
+ interface ObjectSearchItem {
190
+ readonly ref: ObjectRef
191
+ readonly label: string
192
+ }
193
+
194
+ async function searchObjects(
195
+ sixb: Sixb<readonly OntologySource[]>,
196
+ authState: RequestAuthState,
197
+ query: string,
198
+ limit: number
199
+ ): Promise<readonly ObjectSearchItem[]> {
200
+ // Primary ids are available on every object store and form the reliable fallback. Scoped.list()
201
+ // narrows broad searches to viewable types before storage, rather than filtering rows afterwards.
202
+ const primaryMatches = await (authState.scoped
203
+ ? authState.scoped.list({ idPrefix: query, limit })
204
+ : sixb.list({ idPrefix: query, limit }))
205
+
206
+ const capabilities = sixb.storage.objects.queryCapabilities()
207
+ const supportsTextSearch =
208
+ capabilities.queryObjects === true &&
209
+ capabilities.nodes?.start === true &&
210
+ capabilities.nodes?.text === true &&
211
+ capabilities.nodes?.limit === true &&
212
+ typeof sixb.storage.objects.queryObjects === "function"
213
+
214
+ const searchableTypes = supportsTextSearch
215
+ ? sixb.listObjectTypes().filter(
216
+ (objectType) =>
217
+ Boolean(objectType.search?.defaultText?.length) &&
218
+ isAllowed(authState.authz, {
219
+ kind: "object.view",
220
+ objectTypeId: objectType.id,
221
+ })
222
+ )
223
+ : []
224
+
225
+ const textMatches = await Promise.all(
226
+ searchableTypes.map(async (objectType) => {
227
+ const objectQuery: ObjectQuery = {
228
+ kind: "limit",
229
+ limit,
230
+ input: {
231
+ kind: "text",
232
+ query,
233
+ input: { kind: "start", objectTypeId: objectType.id },
234
+ },
235
+ }
236
+ const result = await executeObjectQuery(
237
+ { projectId: sixb.id, query: objectQuery },
238
+ {
239
+ ontology: sixb.ontology,
240
+ storage: sixb.storage.objects,
241
+ authorization: authState.authz ?? undefined,
242
+ }
243
+ )
244
+ return result.objects
245
+ })
246
+ )
247
+
248
+ const items = new Map<string, ObjectSearchItem>()
249
+ for (const row of [...primaryMatches.objects, ...textMatches.flat()]) {
250
+ const ref = { objectTypeId: row.objectTypeId, primaryId: row.primaryId }
251
+ const identity = objectRefIdentity(ref)
252
+ if (items.has(identity)) continue
253
+ items.set(identity, { ref, label: objectSearchLabel(sixb, row) })
254
+ if (items.size === limit) break
255
+ }
256
+ return [...items.values()]
257
+ }
258
+
259
+ function objectSearchLabel(sixb: Sixb<readonly OntologySource[]>, row: ObjectRow): string {
260
+ const objectType = sixb.resolveObjectType(row.objectTypeId)
261
+ const titlePropertyId = objectType.search?.title
262
+ const title = titlePropertyId ? row.properties[titlePropertyId] : undefined
263
+ const displayTitle =
264
+ typeof title === "string" || typeof title === "number" ? String(title).trim() : ""
265
+ return displayTitle && displayTitle !== row.primaryId
266
+ ? `${objectType.name}: ${displayTitle} (${row.primaryId})`
267
+ : `${objectType.name} ${row.primaryId}`
268
+ }
269
+
270
+ function objectRefIdentity(ref: ObjectRef): string {
271
+ return `${encodeURIComponent(ref.objectTypeId)}:${encodeURIComponent(ref.primaryId)}`
272
+ }
273
+
274
+ async function objectFileContentResponse(
275
+ sixb: Sixb<readonly OntologySource[]>,
276
+ context: {
277
+ readonly params: { readonly objectTypeId: string; readonly objectId: string }
278
+ readonly query: unknown
279
+ readonly request: Request
280
+ readonly set: { status?: number | string }
281
+ },
282
+ options: { readonly head?: boolean } = {}
283
+ ) {
284
+ const { scoped } = requestAuthState(context)
285
+
286
+ return createContextualFileContentResponse({
287
+ blobStorage: sixb.blobStorage,
288
+ query: context.query,
289
+ querySchema: ObjectFileContentQuerySchema,
290
+ request: context.request,
291
+ set: context.set,
292
+ head: options.head,
293
+ hideError: (error) => error instanceof AuthorizationError,
294
+ resolveRoot: async () => {
295
+ const row = await getObjectRow(sixb, scoped, context.params)
296
+ if (!row) {
297
+ return null
298
+ }
299
+
300
+ return serializeObject(row)
301
+ },
302
+ })
303
+ }
304
+
305
+ export function registerObjectRoutes(app: Elysia, sixb: Sixb<readonly OntologySource[]>) {
306
+ return app
307
+ .get(
308
+ "/api/objects/search",
309
+ async (context) => {
310
+ const { query, set } = context
311
+ try {
312
+ const parsed = ObjectSearchQuerySchema.parse(query)
313
+ const limit = Math.min(parseOptionalInt(parsed.limit) ?? 20, 50)
314
+ if (limit < 1) {
315
+ set.status = 400
316
+ return { error: "Object search limit must be positive" }
317
+ }
318
+ const items = await searchObjects(sixb, requestAuthState(context), parsed.q, limit)
319
+ return ObjectSearchResponseSchema.parse({ items })
320
+ } catch (error) {
321
+ return handleObjectQueryError(error, set)
322
+ }
323
+ },
324
+ {
325
+ query: ObjectSearchQuerySchema,
326
+ response: {
327
+ 200: ObjectSearchResponseSchema,
328
+ 400: ErrorResponseSchema,
329
+ 403: ErrorResponseSchema,
330
+ },
331
+ detail: {
332
+ summary: "Search objects",
333
+ tags: [OPENAPI_TAGS.objects.name],
334
+ operationId: "searchObjects",
335
+ security: bearerSecurityRequirement("searchObjects"),
336
+ },
337
+ }
338
+ )
339
+ .get(
340
+ "/api/objects",
341
+ async (context) => {
342
+ const { query, set } = context
343
+ const { scoped } = requestAuthState(context)
344
+
345
+ try {
346
+ const params = {
347
+ objectTypeIds: query.objectTypeId === undefined ? undefined : [query.objectTypeId],
348
+ idPrefix: query.idPrefix,
349
+ idSuffix: query.idSuffix,
350
+ updatedAfter: query.updatedAfter,
351
+ updatedBefore: query.updatedBefore,
352
+ createdAfter: query.createdAfter,
353
+ createdBefore: query.createdBefore,
354
+ limit: query.limit,
355
+ offset: query.offset,
356
+ orderBy: query.orderBy,
357
+ order: query.order,
358
+ }
359
+ const result = scoped ? await scoped.list(params) : await sixb.list(params)
360
+
361
+ return {
362
+ objects: result.objects.map(serializeObject),
363
+ hasMore: result.hasMore,
364
+ total: result.total,
365
+ }
366
+ } catch (error) {
367
+ if (error instanceof AuthorizationError) {
368
+ set.status = 403
369
+ return { error: error.message }
370
+ }
371
+
372
+ set.status = 400
373
+ return { error: error instanceof Error ? error.message : String(error) }
374
+ }
375
+ },
376
+ {
377
+ query: ObjectsQuerySchema,
378
+ response: {
379
+ 200: ObjectListResponseSchema,
380
+ 400: ErrorResponseSchema,
381
+ 403: ErrorResponseSchema,
382
+ },
383
+ error: ({ code, error, set }) => {
384
+ if (code !== "VALIDATION" || error.type !== "query") return
385
+
386
+ set.status = 400
387
+ return { error: error.all[0]?.message ?? "Invalid object list query parameters." }
388
+ },
389
+ detail: {
390
+ summary: "List objects",
391
+ tags: [OPENAPI_TAGS.objects.name],
392
+ operationId: "listObjects",
393
+ security: bearerSecurityRequirement("listObjects"),
394
+ },
395
+ }
396
+ )
397
+ .post(
398
+ "/api/objects/query",
399
+ async (context) => {
400
+ const { body, set } = context
401
+ try {
402
+ const parsed = ObjectQueryRequestSchema.parse(body) as {
403
+ query: ObjectQuery
404
+ includeTotal?: boolean
405
+ }
406
+ const result = await executeObjectQuery(
407
+ {
408
+ projectId: sixb.id,
409
+ query: parsed.query,
410
+ includeTotal: parsed.includeTotal,
411
+ },
412
+ {
413
+ ontology: sixb.ontology,
414
+ storage: sixb.storage.objects,
415
+ authorization: requestAuthState(context).authz ?? undefined,
416
+ }
417
+ )
418
+
419
+ return {
420
+ objects: result.objects.map(serializeExpandedObject),
421
+ hasMore: result.hasMore,
422
+ nextPageToken: result.nextPageToken,
423
+ plan: serializePlan(result.plan),
424
+ ...(result.total === undefined ? {} : { total: result.total }),
425
+ }
426
+ } catch (error) {
427
+ return handleObjectQueryError(error, set)
428
+ }
429
+ },
430
+ {
431
+ detail: {
432
+ summary: "Query objects",
433
+ tags: [OPENAPI_TAGS.objects.name],
434
+ operationId: "queryObjects",
435
+ security: bearerSecurityRequirement("queryObjects"),
436
+ requestBody: {
437
+ required: true,
438
+ content: {
439
+ "application/json": {
440
+ schema: { $ref: "#/components/schemas/ObjectQueryRequest" },
441
+ },
442
+ },
443
+ },
444
+ responses: {
445
+ 200: {
446
+ description: "Response for status 200",
447
+ content: {
448
+ "application/json": {
449
+ schema: { $ref: "#/components/schemas/ObjectQueryResponse" },
450
+ },
451
+ },
452
+ },
453
+ 400: {
454
+ description: "Response for status 400",
455
+ content: {
456
+ "application/json": {
457
+ schema: { $ref: "#/components/schemas/ObjectQueryErrorResponse" },
458
+ },
459
+ },
460
+ },
461
+ 403: {
462
+ description: "Response for status 403",
463
+ content: {
464
+ "application/json": {
465
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
466
+ },
467
+ },
468
+ },
469
+ 500: {
470
+ description: "Response for status 500",
471
+ content: {
472
+ "application/json": {
473
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
474
+ },
475
+ },
476
+ },
477
+ },
478
+ },
479
+ }
480
+ )
481
+ .post(
482
+ "/api/objects/query/count",
483
+ async (context) => {
484
+ const { body, set } = context
485
+ try {
486
+ const parsed = ObjectQueryCountRequestSchema.parse(body) as {
487
+ query: ObjectQuery
488
+ }
489
+ const result = await countObjects(
490
+ {
491
+ projectId: sixb.id,
492
+ query: parsed.query,
493
+ },
494
+ {
495
+ ontology: sixb.ontology,
496
+ storage: sixb.storage.objects,
497
+ authorization: requestAuthState(context).authz ?? undefined,
498
+ }
499
+ )
500
+
501
+ return {
502
+ count: result.count,
503
+ plan: serializePlan(result.plan),
504
+ }
505
+ } catch (error) {
506
+ return handleObjectQueryError(error, set)
507
+ }
508
+ },
509
+ {
510
+ detail: {
511
+ summary: "Count objects",
512
+ tags: [OPENAPI_TAGS.objects.name],
513
+ operationId: "countObjects",
514
+ security: bearerSecurityRequirement("countObjects"),
515
+ requestBody: {
516
+ required: true,
517
+ content: {
518
+ "application/json": {
519
+ schema: { $ref: "#/components/schemas/ObjectQueryCountRequest" },
520
+ },
521
+ },
522
+ },
523
+ responses: {
524
+ 200: {
525
+ description: "Response for status 200",
526
+ content: {
527
+ "application/json": {
528
+ schema: { $ref: "#/components/schemas/ObjectQueryCountResponse" },
529
+ },
530
+ },
531
+ },
532
+ 400: {
533
+ description: "Response for status 400",
534
+ content: {
535
+ "application/json": {
536
+ schema: { $ref: "#/components/schemas/ObjectQueryErrorResponse" },
537
+ },
538
+ },
539
+ },
540
+ 403: {
541
+ description: "Response for status 403",
542
+ content: {
543
+ "application/json": {
544
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
545
+ },
546
+ },
547
+ },
548
+ 500: {
549
+ description: "Response for status 500",
550
+ content: {
551
+ "application/json": {
552
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
553
+ },
554
+ },
555
+ },
556
+ },
557
+ },
558
+ }
559
+ )
560
+ .post(
561
+ "/api/objects/query/exists",
562
+ async (context) => {
563
+ const { body, set } = context
564
+ try {
565
+ const parsed = ObjectQueryExistsRequestSchema.parse(body) as {
566
+ query: ObjectQuery
567
+ }
568
+ const result = await existsObjects(
569
+ {
570
+ projectId: sixb.id,
571
+ query: parsed.query,
572
+ },
573
+ {
574
+ ontology: sixb.ontology,
575
+ storage: sixb.storage.objects,
576
+ authorization: requestAuthState(context).authz ?? undefined,
577
+ }
578
+ )
579
+
580
+ return {
581
+ exists: result.exists,
582
+ plan: serializePlan(result.plan),
583
+ }
584
+ } catch (error) {
585
+ return handleObjectQueryError(error, set)
586
+ }
587
+ },
588
+ {
589
+ detail: {
590
+ summary: "Check object existence",
591
+ tags: [OPENAPI_TAGS.objects.name],
592
+ operationId: "existsObjects",
593
+ security: bearerSecurityRequirement("existsObjects"),
594
+ requestBody: {
595
+ required: true,
596
+ content: {
597
+ "application/json": {
598
+ schema: { $ref: "#/components/schemas/ObjectQueryExistsRequest" },
599
+ },
600
+ },
601
+ },
602
+ responses: {
603
+ 200: {
604
+ description: "Response for status 200",
605
+ content: {
606
+ "application/json": {
607
+ schema: { $ref: "#/components/schemas/ObjectQueryExistsResponse" },
608
+ },
609
+ },
610
+ },
611
+ 400: {
612
+ description: "Response for status 400",
613
+ content: {
614
+ "application/json": {
615
+ schema: { $ref: "#/components/schemas/ObjectQueryErrorResponse" },
616
+ },
617
+ },
618
+ },
619
+ 403: {
620
+ description: "Response for status 403",
621
+ content: {
622
+ "application/json": {
623
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
624
+ },
625
+ },
626
+ },
627
+ 500: {
628
+ description: "Response for status 500",
629
+ content: {
630
+ "application/json": {
631
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
632
+ },
633
+ },
634
+ },
635
+ },
636
+ },
637
+ }
638
+ )
639
+ .post(
640
+ "/api/objects/query/facets",
641
+ async (context) => {
642
+ const { body, set } = context
643
+ try {
644
+ const parsed = ObjectQueryFacetsRequestSchema.parse(body) as {
645
+ query: ObjectQuery
646
+ facets: { propertyId: string; limit: number }[]
647
+ }
648
+ const result = await facetObjects(
649
+ {
650
+ projectId: sixb.id,
651
+ query: parsed.query,
652
+ facets: parsed.facets,
653
+ },
654
+ {
655
+ ontology: sixb.ontology,
656
+ storage: sixb.storage.objects,
657
+ authorization: requestAuthState(context).authz ?? undefined,
658
+ }
659
+ )
660
+
661
+ return {
662
+ facets: result.facets,
663
+ plan: serializePlan(result.plan),
664
+ }
665
+ } catch (error) {
666
+ return handleObjectQueryError(error, set)
667
+ }
668
+ },
669
+ {
670
+ detail: {
671
+ summary: "Facet objects",
672
+ tags: [OPENAPI_TAGS.objects.name],
673
+ operationId: "facetObjects",
674
+ security: bearerSecurityRequirement("facetObjects"),
675
+ requestBody: {
676
+ required: true,
677
+ content: {
678
+ "application/json": {
679
+ schema: { $ref: "#/components/schemas/ObjectQueryFacetsRequest" },
680
+ },
681
+ },
682
+ },
683
+ responses: {
684
+ 200: {
685
+ description: "Response for status 200",
686
+ content: {
687
+ "application/json": {
688
+ schema: { $ref: "#/components/schemas/ObjectQueryFacetsResponse" },
689
+ },
690
+ },
691
+ },
692
+ 400: {
693
+ description: "Response for status 400",
694
+ content: {
695
+ "application/json": {
696
+ schema: { $ref: "#/components/schemas/ObjectQueryErrorResponse" },
697
+ },
698
+ },
699
+ },
700
+ 403: {
701
+ description: "Response for status 403",
702
+ content: {
703
+ "application/json": {
704
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
705
+ },
706
+ },
707
+ },
708
+ 500: {
709
+ description: "Response for status 500",
710
+ content: {
711
+ "application/json": {
712
+ schema: { $ref: "#/components/schemas/ErrorResponse" },
713
+ },
714
+ },
715
+ },
716
+ },
717
+ },
718
+ }
719
+ )
720
+ .get(
721
+ "/api/objects/:objectTypeId/:objectId/files/content",
722
+ (context) => objectFileContentResponse(sixb, context),
723
+ {
724
+ params: ObjectParamsSchema,
725
+ // Register the loose query so framework validation only requires `path`;
726
+ // the handler applies the stricter `^/properties` check and returns a
727
+ // consistent `{ error }` 400. Registering the strict schema here would
728
+ // make Elysia emit its own 422 validation body, breaking that contract.
729
+ query: FileContentQuerySchema,
730
+ // No top-level `response` map: Elysia's OpenAPI builder resets responses
731
+ // to JSON-only whenever one is present, which would erase the binary
732
+ // `application/octet-stream` bodies. Declaring every status in
733
+ // `detail.responses` keeps the binary content in the spec.
734
+ detail: {
735
+ summary: "Get object file content",
736
+ tags: [OPENAPI_TAGS.objectFiles.name],
737
+ operationId: "getObjectFileContent",
738
+ security: bearerSecurityRequirement("getObjectFileContent"),
739
+ responses: fileContentGetResponses(),
740
+ },
741
+ }
742
+ )
743
+ .head(
744
+ "/api/objects/:objectTypeId/:objectId/files/content",
745
+ (context) => objectFileContentResponse(sixb, context, { head: true }),
746
+ {
747
+ params: ObjectParamsSchema,
748
+ // See the GET route: register the loose query so the handler owns the
749
+ // strict `^/properties` check and its consistent 400.
750
+ query: FileContentQuerySchema,
751
+ // See the GET route: no top-level `response` map, so the binary responses
752
+ // declared in `detail.responses` survive into the spec.
753
+ detail: {
754
+ summary: "Head object file content",
755
+ tags: [OPENAPI_TAGS.objectFiles.name],
756
+ operationId: "headObjectFileContent",
757
+ security: bearerSecurityRequirement("headObjectFileContent"),
758
+ responses: fileContentHeadResponses(),
759
+ },
760
+ }
761
+ )
762
+ .get(
763
+ "/api/objects/:objectTypeId/:objectId",
764
+ async (context) => {
765
+ const { params, set } = context
766
+ const { scoped } = requestAuthState(context)
767
+
768
+ try {
769
+ const row = await getObjectRow(sixb, scoped, params)
770
+ if (!row) {
771
+ set.status = 404
772
+ return { error: "Object not found" }
773
+ }
774
+
775
+ return serializeObject(row)
776
+ } catch (error) {
777
+ // Identity reads hide existence: forbidden and missing look the same.
778
+ if (error instanceof AuthorizationError) {
779
+ set.status = 404
780
+ return { error: "Object not found" }
781
+ }
782
+
783
+ throw error
784
+ }
785
+ },
786
+ {
787
+ params: ObjectParamsSchema,
788
+ response: { 200: TwinObjectSchema, 404: ErrorResponseSchema },
789
+ detail: {
790
+ summary: "Get object by id",
791
+ tags: [OPENAPI_TAGS.objects.name],
792
+ operationId: "getObject",
793
+ security: bearerSecurityRequirement("getObject"),
794
+ },
795
+ }
796
+ )
797
+ .put(
798
+ "/api/objects/:objectTypeId/:objectId",
799
+ async (context) => {
800
+ const { params, body, set } = context
801
+ const { scoped } = requestAuthState(context)
802
+ try {
803
+ const parsedBody = UpsertObjectBodySchema.parse(body)
804
+ // Scoped when a principal is attached, privileged only when auth is off or the request is
805
+ // public — the same fallback the read routes use. Scoped for the primary-property lookup
806
+ // too: on the privileged runtime it answers 404 for an unregistered type before any grant
807
+ // is checked, which told an ungranted principal apart from a registered type (403) and so
808
+ // handed back the type universe that `listObjectTypes` filters out.
809
+ const runtime = scoped ?? sixb
810
+ const primaryPropertyId = runtime.getPrimaryPropertyId(params.objectTypeId)
811
+ const properties = { ...parsedBody.properties, [primaryPropertyId]: params.objectId }
812
+ const object = await runtime.upsertObject(params.objectTypeId, properties)
813
+ return serializeObject(object)
814
+ } catch (error) {
815
+ // Was a local catch mapping every error to 404/400, which turned a missing grant into
816
+ // "bad request". `handleRouteError` answers 403 for AuthorizationError, like the link and
817
+ // telemetry writes already did.
818
+ return handleRouteError(error, set)
819
+ }
820
+ },
821
+ {
822
+ params: ObjectParamsSchema,
823
+ body: UpsertObjectBodySchema,
824
+ response: {
825
+ 200: TwinObjectSchema,
826
+ 400: ErrorResponseSchema,
827
+ 403: ErrorResponseSchema,
828
+ 404: ErrorResponseSchema,
829
+ },
830
+ detail: {
831
+ summary: "Create or update object",
832
+ tags: [OPENAPI_TAGS.objects.name],
833
+ operationId: "upsertObject",
834
+ security: bearerSecurityRequirement("upsertObject"),
835
+ },
836
+ }
837
+ )
838
+ }